Why does C# DateTime parse "01/05/2020" the same regardless of culture?

Viewed 98

I am looking for someone to help me understand why this unit test passes.

Essentially we want to support various date formats but en-CA should be treated as DD/MM/YYYY and if client is using en-us culture then we want to treat the date as MM/DD/YYYY. I don't understand why this isn't the default behavior with DateTime.Parse and DateTime.TryParse.

[Fact]
public void DateTimeParse()
{
   var cultureUs = CultureInfo.GetCultureInfoByIetfLanguageTag("en-us");
   DateTime.TryParse("01/05/2020", cultureUs.DateTimeFormat, DateTimeStyles.None, out var d);
    
   var cultureCa = CultureInfo.GetCultureInfoByIetfLanguageTag("en-ca");
   DateTime.TryParse("01/05/2020", cultureCa.DateTimeFormat, DateTimeStyles.None, out var c);
    
   Assert.Equal(d.Month,c.Month);
}
1 Answers

The formats of English (Canada) may be different from what you think. For example, the code:

    foreach (var code in new[] { "en-US", "en-CA", "en-GB", })
    {
        Console.WriteLine($"Code {code}");
        var dtf = CultureInfo.GetCultureInfo(code).DateTimeFormat;
        Console.WriteLine(dtf.ShortDatePattern);
        Console.WriteLine(dtf.DateSeparator);
        Console.WriteLine();
    }

writes:

Code en-US
M/d/yyyy
/

Code en-CA
yyyy-MM-dd
-

Code en-GB
dd/MM/yyyy
/

on my system.

When you use TryParse (and not TryParseExact) and none of the standard patterns of the date time format provider match, it is hard to know what happens(?).

Related