Skip to main content
 首页 » 编程设计

c#之无法在 Windows Phone 7 中将字符串解析为 DateTime

2024年02月06日19java哥

我正在尝试将 string 转换为 DateTime。但我无法转换。

DateTime dt = DateTime.Parse("16/11/2014", CultureInfo.InvariantCulture); 
Console.WriteLine("Date==> " + dt); 

错误是FormatException。

我输入的时间格式是"dd/MM/yyyy"。

请让我知道如何解决我的问题。

请您参考如下方法:

鉴于您知道输入格式,您应该使用 `ParseExact:

指定它
DateTime dt = DateTime.ParseExact(text, "dd/MM/yyyy", 
                                  CultureInfo.InvariantCulture); 

我总是建议您对日期/时间格式尽可能明确。它使您的意图非常明确,并避免了以错误的方式度过几个月和几天的可能性。

正如 Soner 所说,CultureInfo.InvariantCulture 使用 MM/dd/yyyy 作为其短日期模式,您可以通过以下方式验证:

Console.WriteLine(CultureInfo.InvariantCulture.DateTimeFormat.ShortDatePattern) 

作为温和的插头,您可能想考虑使用我的 Noda Time用于日期/时间处理的项目 - 除其他外,它允许您将日期视为日期,而不是日期和时间...