异步过程中的 DateTime 转换

DateTime conversion during asynchronous process

我正在用 C# 做一组异步进程。当我尝试将字符串 ("12/02/2015") 转换为日期时间类型时,它显示错误,称为 String is not in the correct format to convert。但是相同的代码在作为异步过程之前工作。

DateTime.Parse("12/02/2015 00:00:00")

当您启动一个新线程时,默认情况下其区域设置将设置为操作系统的默认区域设置。它将不一定设置为在Windows区域设置中选择的文化。

您可以通过将以下代码行添加到线程函数的开头来解决此问题:

System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture;

或者,您可以使用 DateTime.ParseExact() 并准确指定要解析的格式,例如:

DateTime.ParseExact("12/02/2015 00:00:00", "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

请注意,格式字符串中的“/”和“:”字符不是逐字字符;它们分别指定日期和时间分隔符。它们恰好映射到不变文化中的相同字符,但它们可能映射到其他文化中的不同字符。

要准确指定应使用那些“/”和“:”字符,您必须像这样对它们进行转义:

DateTime.ParseExact("12/02/2015 00:00:00", "dd\/MM\/yyyy HH\:mm\:ss", CultureInfo.InvariantCulture);