问题
Well I was creating a application for windows phone 8.1 WinRT.
I save a Datetime.now() based on en-US culture initially but later the culture gets changed and when I try to parse the saved string in DateTime.Parse()
, I get a format exception.
//Setting en-US culture
var culture = new CultureInfo("en-US");
Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = culture.Name;
//Saving DateTime.Now in a string format
String usTime = DateTime.Now.ToString();
//Changing it to the de-DE culture
culture = new CultureInfo("de-DE");
Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = culture.Name;
//Now trying to parse the usTime
DateTime deTime = DateTime.Parse(usTime);
//Here I get an error saying format exception.
Is there anyway I can tell it how to parse and convert usTime string to deTime DateTime?
回答1:
You can pass an IFormatProvider
to DateTime.Parse
var cultureUS = new CultureInfo("en-US");
//Now trying to parse the usTime with US culture format provider
DateTime deTime = DateTime.Parse(usTime, cultureUS);
来源:https://stackoverflow.com/questions/31105593/how-to-parse-a-datetime-string-based-on-culture