【问题标题】:How to parse a DateTime string based on culture?如何根据文化解析 DateTime 字符串?
【发布时间】:2015-12-06 21:52:12
【问题描述】:

我正在为 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 吗?

【问题讨论】:

  • 这边? DateTime.TryParse(dtstring, new System.Globalization.CultureInfo("xxxx"), System.Globalization.DateTimeStyles.None, out dt)
  • usTime 的值是多少,你的CurrentCulture 到底是什么?

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


【解决方案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);

【讨论】:

  • @doctor : 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-08
  • 1970-01-01
  • 1970-01-01
  • 2010-12-07
  • 2011-11-26
相关资源
最近更新 更多