DateTime ParseExact 在其他服务器上的不同行为
DateTime ParseExact different behaviour on other server
我有一段代码在我的测试服务器上崩溃,而不是在我的开发服务器上。我有 2 Windows 2012R2 服务器用于开发和测试。两者都在相同的补丁级别,相同的 .NET FrameWork 版本。对于当前用户和本地系统,两者都具有相同的区域设置(荷兰语)。此荷兰语设置使用 - 作为日期分隔符。以下代码片段在开发服务器上有效,但在测试服务器上崩溃。我在控制台应用程序中添加了带有 2 行代码的代码片段,然后我可以重现错误。
这段代码(针对演示控制台应用程序进行了简化)是:
string date = "28/02/2017";
DateTime dateDate = DateTime.ParseExact(date, "dd/MM/yyyy", null);
所以这在我的开发服务器上工作并在测试时崩溃
我得到这个例外
Unhandled Exception: System.FormatException: String was not recognized as a vali
d DateTime.
at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInf
o dtfi, DateTimeStyles style)
at System.DateTime.ParseExact(String s, String format, IFormatProvider provid
er)
当我将代码更改为
string date = "28/02/2017";
DateTime dateDate = DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
它适用于两台服务器。当我在控制台应用程序中输出 CurrentCultue 和 CurrentUiCulture 时,它们在两台服务器上是相同的。
知道我的测试服务器上会出现什么问题吗?当我在 ParseExact 方法中传递 null 时,我预计代码也会在我的开发服务器上崩溃,因为然后应该使用 CurrentCulture,然后日期分隔符 / 应该会导致错误。
问候
丹尼
null
指定您要改用当前文化,而不是传递 CultureInfo.InvariantCulture
.
MSDN:
If provider is null
, the CultureInfo
object that corresponds to the
current culture is used.
/
在解析日期时间时有特殊意义。它们将替换为当前文化的 DateSeparator
。 (The "/" custom format specifier)
您也可以屏蔽它们:
DateTime dateDate = DateTime.ParseExact(date, "dd'/'MM'/'yyyy", null);
/
字符在日期格式字符串中不按字面解释。根据使用的格式提供程序,它被替换为日期分隔符。
您需要将 /
括在单引号中,使其成为格式字符串中的文字字符:
"dd'/'MM'/'yyyy"
我有一段代码在我的测试服务器上崩溃,而不是在我的开发服务器上。我有 2 Windows 2012R2 服务器用于开发和测试。两者都在相同的补丁级别,相同的 .NET FrameWork 版本。对于当前用户和本地系统,两者都具有相同的区域设置(荷兰语)。此荷兰语设置使用 - 作为日期分隔符。以下代码片段在开发服务器上有效,但在测试服务器上崩溃。我在控制台应用程序中添加了带有 2 行代码的代码片段,然后我可以重现错误。
这段代码(针对演示控制台应用程序进行了简化)是:
string date = "28/02/2017";
DateTime dateDate = DateTime.ParseExact(date, "dd/MM/yyyy", null);
所以这在我的开发服务器上工作并在测试时崩溃 我得到这个例外
Unhandled Exception: System.FormatException: String was not recognized as a vali
d DateTime.
at System.DateTimeParse.ParseExact(String s, String format, DateTimeFormatInf
o dtfi, DateTimeStyles style)
at System.DateTime.ParseExact(String s, String format, IFormatProvider provid
er)
当我将代码更改为
string date = "28/02/2017";
DateTime dateDate = DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.InvariantCulture);
它适用于两台服务器。当我在控制台应用程序中输出 CurrentCultue 和 CurrentUiCulture 时,它们在两台服务器上是相同的。
知道我的测试服务器上会出现什么问题吗?当我在 ParseExact 方法中传递 null 时,我预计代码也会在我的开发服务器上崩溃,因为然后应该使用 CurrentCulture,然后日期分隔符 / 应该会导致错误。
问候 丹尼
null
指定您要改用当前文化,而不是传递 CultureInfo.InvariantCulture
.
MSDN:
If provider is
null
, theCultureInfo
object that corresponds to the current culture is used.
/
在解析日期时间时有特殊意义。它们将替换为当前文化的 DateSeparator
。 (The "/" custom format specifier)
您也可以屏蔽它们:
DateTime dateDate = DateTime.ParseExact(date, "dd'/'MM'/'yyyy", null);
/
字符在日期格式字符串中不按字面解释。根据使用的格式提供程序,它被替换为日期分隔符。
您需要将 /
括在单引号中,使其成为格式字符串中的文字字符:
"dd'/'MM'/'yyyy"