【发布时间】:2015-09-05 17:57:31
【问题描述】:
我们有一个大型应用程序(不幸的是)大量使用 DateTime.Parse(text)。用更好的东西替换 DateTime.Parse 现在不是一种选择。
最近我升级了 Windows(到 Windows 10)并开始出现问题。根据https://msdn.microsoft.com/en-us/library/system.datetime.parse(v=vs.110).aspx 的文档,该方法应使用 CultureInfo.CurrentCulture 作为默认格式提供程序。在我的电脑上似乎不是这种情况,除非我遗漏了一些明显的东西。
以下代码调用函数两次,第一次不更改任何文化设置,然后在文化和 ui-culture 上设置挪威文化。 由于某种原因,它能够在这两种情况下解析以 en-US 格式 (M/d/yyyy) 给出的文本,但无法解析 CultureInfo 预期格式的日期。
这里发生了什么?我希望我遗漏了一些明显的东西..
class Program
{
static void Main(string[] args)
{
var norwegianCulture = new CultureInfo("nb-NO");
Console.WriteLine("First");
ParseDates();
Console.WriteLine("\nSecond");
Thread.CurrentThread.CurrentUICulture = norwegianCulture;
ParseDates();
Console.ReadKey();
}
private static void ParseDates()
{
Console.WriteLine($"CultureInfo.CurrentCulture: {CultureInfo.CurrentCulture}");
Console.WriteLine($"CultureInfo.CurrentUICulture: {CultureInfo.CurrentUICulture}");
Console.WriteLine($"{Thread.CurrentThread.CurrentCulture} - CurrentCulture - {Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern}");
Console.WriteLine($"{Thread.CurrentThread.CurrentUICulture} - CurrentUICulture - {Thread.CurrentThread.CurrentUICulture.DateTimeFormat.ShortDatePattern}");
var shortDateString = new DateTime(2015, 9, 5).ToShortDateString();
WriteParsedDate(shortDateString);
WriteParsedDate("1/2/2015");
Console.WriteLine();
}
private static void WriteParsedDate(string shortDateString)
{
try
{
var d = DateTime.Parse(shortDateString, CultureInfo.CurrentCulture);
Console.WriteLine($"The text {shortDateString} parsed to Year: {d.Year}, Month: {d.Month}, Day: {d.Day}");
}
catch (Exception e)
{
Console.WriteLine($"The text {shortDateString} could not be parsed.");
Console.WriteLine($"Error: {e.Message}");
}
}
}
将此写入控制台:
First
CultureInfo.CurrentCulture: nb-NO
CultureInfo.CurrentUICulture: en-US
nb-NO - CurrentCulture - dd.MM.yyyy
en-US - CurrentUICulture - M/d/yyyy
The text 05.09.2015 could not be parsed.
Error: String was not recognized as a valid DateTime.
The text 1/2/2015 parsed to Year: 2015, Month: 2, Day: 1
Second
CultureInfo.CurrentCulture: nb-NO
CultureInfo.CurrentUICulture: nb-NO
nb-NO - CurrentCulture - dd.MM.yyyy
nb-NO - CurrentUICulture - dd.MM.yyyy
The text 05.09.2015 could not be parsed.
Error: Strengen ble ikke gjenkjent som en gyldig DateTime.
The text 1/2/2015 parsed to Year: 2015, Month: 2, Day: 1
部分解决方法
正如 shf301 所写,这是由于 Windows 10 中的一个错误造成的。
我设法通过更改“。”的时间分隔符来使其工作。 to ":" - 与旧版本的 Windows 一样。我猜它正在处理该更改,因为我们只使用用户设置,而不是手动加载/指定它们。
【问题讨论】:
-
这似乎也没有使用 en-US,因为如果是这样,那么月份应该是 1 和第 2 天,但你正在反过来。