如何基于区域性分析DateTime字符串

本文关键字:DateTime 字符串 何基于 区域性 | 更新日期: 2023-09-27 18:00:18

我当时正在为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字符串并将其转换为deTimeDateTime吗?

如何基于区域性分析DateTime字符串

您可以将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);