How to parse a DateTime string based on culture?

2019-09-15 10:56发布

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条回答
Rolldiameter
2楼-- · 2019-09-15 11:14

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);
查看更多
登录 后发表回答