I’m trying to parse dates with a given format and I’ve found this which I cannot explain:
var date = new DateTime(2001, 01, 10);
var cultureInfo1 = CultureInfo.GetCultureInfo(CultureInfo.CurrentCulture.Name);
var cultureInfo2 = new CultureInfo(CultureInfo.CurrentCulture.Name);
Assert.AreEqual(date, DateTime.ParseExact("10/01/01", "dd/MM/yy", cultureInfo1));
Assert.Throws<FormatException>(() => DateTime.ParseExact("10/01/01", "dd/MM/yy", CultureInfo.CurrentCulture));
Assert.Throws<FormatException>(() => DateTime.ParseExact("10/01/01", "dd/MM/yy", cultureInfo2));
Why would this call fail with the CurrentCulture, fail with a new instance created using the Culture name but not fail with a Culture obtained using GetCultureInfo(). The current culture is en-US and Windows is configured with this two changes (done in intl.cpl): use the Metric system, and short date format ‘dd-MMM-yyyy’.
Update:
The original question was correctly answered, but I want to add that both cultures are able to parse the date. The problem seems to lie with the date separator specified in CultureInfo.DateTimeFormat.DateSeparator.
The cultureInfo which has my overrides, has ‘-‘ as separator, while the original culture has ‘/’.
To make ParseExact parse the date irrespective of the culture specified separator, the format spec should be changed from “dd/MM/yy” to “dd’/’MM’/’yy”.
From the MSDN for
CultureInfo.GetCultureInfo(string)The MSDN for
CultureInfo(string)This means the static
GetCultureInfo(string)will not use any settings the user has overridden, whereas the constructor version will.