简体   繁体   中英

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. It works fine on Windows Server 2008 R2 but shows exception in Windows Server 2012 :- String was not recognized as a valid 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 . represents "decimal separator" (not period).

In en-CA, the separator character is mapped to - ; the date would need to be 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 .

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM