[英]String was not recognized as a valid DateTime. using ParseExact on Windows Server 2012
I am trying to parse a string to a date using "en-CA" culture info. 我正在尝试使用“ en-CA”文化信息将字符串解析为一个日期。 It works fine on Windows Server 2008 R2 but shows exception in Windows Server 2012 :- String was not recognized as a valid DateTime. 它在Windows Server 2008 R2上运行良好,但在Windows Server 2012中显示异常:-无法将字符串识别为有效的DateTime。
Below is the code segment :- 以下是代码段:-
DateTime tvDefaultDate = DateTime.ParseExact("31/12/9999", "dd/MM/yyyy",
new CultureInfo("en-CA"));
/
here simply represents "date separator" ( DateTimeFormatInfo.DateSeparator
), in the same way that with numbers ,
represents "thousands separator" (not comma), and .
/
与数字一样,仅表示“日期分隔符”( DateTimeFormatInfo.DateSeparator
),与表示数字的方式相同,
表示“千分隔符”(不是逗号),和.
represents "decimal separator" (not period). 代表“十进制分隔符”(不是句点)。
In en-CA, the separator character is mapped to -
; 在en-CA中,分隔符映射到-
; the date would need to be 31-12-9999
. 日期将需要为31-12-9999
。 To use the literal /
rather than the date separator, you need to escape it: 要使用文字/
而不是日期分隔符,您需要对其进行转义:
DateTime tvDefaultDate = DateTime.ParseExact("31/12/9999", @"dd\/MM\/yyyy",
new CultureInfo("en-CA"));
Alternatively, use the invariant culture instead; 另外,也可以使用不变文化。 the invariant culture uses /
for the date separator. 不变区域性将/
用作日期分隔符。
The culture is not needed in the IFormatProvider
, simply pass null
. IFormatProvider
不需要IFormatProvider
,只需传递null
。
DateTime tvDefaultDate = DateTime.ParseExact("31/12/9999", "dd/MM/yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(tvDefaultDate);
Outputs: 输出:
12/31/9999 12:00:00 AM
(Sorry for the US formatting of the final date.) (对不起,最后一天的美国格式。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.