Search code examples
c#.netdatetimestring-parsing

DateTime.TryParse different results


As part of my unittests for an application I check a few datetime strings for their ability to get parsed. I recently noticed that on one machine the string "0-02-20 11:36" can get parsed to {2000-02-20 11:36:00} by DateTime.TryParse(dateString, out parsedTimeStamp) while on other machines it can't.

string dt = "0-02-20 11:36";
DateTime parsedTimeStamp;
DateTime.TryParse(dateString, out parsedTimeStamp);
Console.WriteLine(parsedTimeStamp);

Solution

  • Parsing a DateTime, like all parsing in the framework, is culture dependent.

    I would assume that on the exceptional machine, the culture settings use a yyyy-MM-dd format, while on the other machines, the date format was MM-dd-yyyy.

    To work around this, you can parse in a specific culture or using an invariant culture.

    DateTime.TryParse(dateString, CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedTimeStamp);
    

    It turns out there are quite a few of these cultures:

    foreach (var c in CultureInfo.GetCultures(CultureTypes.AllCultures))
    {
        if (c.DateTimeFormat.ShortDatePattern == "yyyy-MM-dd")
        {
            Console.WriteLine("{0}: {1}", c.DisplayName, c.DateTimeFormat.ShortDatePattern);
        }
    }
    

    Korean: yyyy-MM-dd  
    Polish: yyyy-MM-dd  
    Albanian: yyyy-MM-dd  
    Swedish: yyyy-MM-dd  
    Khmer: yyyy-MM-dd  
    Sinhala: yyyy-MM-dd  
    Korean (Korea): yyyy-MM-dd  
    Polish (Poland): yyyy-MM-dd  
    Albanian (Albania): yyyy-MM-dd  
    Swedish (Sweden): yyyy-MM-dd  
    Khmer (Cambodia): yyyy-MM-dd  
    Sinhala (Sri Lanka): yyyy-MM-dd  
    Sami, Northern (Sweden): yyyy-MM-dd  
    French (Canada): yyyy-MM-dd  
    Sami, Lule (Sweden): yyyy-MM-dd  
    Sami, Southern (Sweden): yyyy-MM-dd  
    Sami (Southern): yyyy-MM-dd  
    Sami (Lule): yyyy-MM-dd