How to parse a DateTime string based on culture?

假装没事ソ 提交于 2020-01-06 15:51:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!