Reputation: 43
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"));
Upvotes: 1
Views: 1656
Reputation: 4913
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.)
Upvotes: 0
Reputation: 1062905
/
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.
Upvotes: 1