如何根据文化解析DateTime字符串?

时间:2015-06-28 22:54:39

标签: c# datetime windows-runtime windows-phone-8.1

我正在为Windows Phone 8.1 WinRT创建一个应用程序。 我最初基于en-US 文化保存了一个 Datetime.now(),但后来文化发生了变化,当我尝试解析DateTime.Parse()中保存的字符串时,我得到一个格式异常

//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.

无论如何,我可以告诉它如何解析并将usTime字符串转换为deTime DateTime?

1 个答案:

答案 0 :(得分:1)

您可以将IFormatProvider传递给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);