DateTime.TryParse with different culture

369 views Asked by At

I have two dates as per below and have my local culture is "en-IN"

string enInDateValue = "13-12-2021 12:00:00"; // dd/mm/yyyy
string enUSDateValue = "12-13-2021 12:00:00"; // mm/dd/yyyy

If I run the below code with Invariant Culture it date gets parsed with enUSDate.

DateTime.TryParse(enInDateValue, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out result)
DateTime.TryParse(enUSDateValue, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out result)

To solve the problem below is the code I am using and it is parsing the dates per culture.

public static bool DateTimeTryParse(string date, out DateTime result)
    {
        return (
            DateTime.TryParse(date, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out result) ||
              DateTime.TryParse(date, CultureInfo.CurrentCulture, DateTimeStyles.NoCurrentDateDefault, out result) ||
              DateTime.TryParse(date, CultureInfo.CurrentUICulture, DateTimeStyles.NoCurrentDateDefault, out result)
        );
    }

If it fails with only Invariant Culture it goes to Current and same for UI Culture

So wanted to ask if that is the right to do? Or is there any other way around?

1

There are 1 answers

1
Gec On

You need to specify the expected format explicitly. This small sample may be helpful:

        string date1 = "12-13-2021";
        string date2 = "13-12-2021";

        string format1 = "MM-dd-yyyy";
        string format2 = "dd-MM-yyyy";

        DateTime parsedDate1, parsedDate2;

        bool success1 = DateTime.TryParseExact(date1, format1, null, DateTimeStyles.None, out parsedDate1);
        bool success2 = DateTime.TryParseExact(date2, format2, null, DateTimeStyles.None, out parsedDate2);

        if (success1)
            Console.WriteLine($"First date parsed successfully: {parsedDate1.ToString("yyyy,MMM,dd,ddd")}");
        else
            Console.WriteLine("First date failed to parse");

        if (success2)
            Console.WriteLine($"Second date parsed successfully: {parsedDate2.ToString("yyyy,MMM,dd,ddd")}");
        else
            Console.WriteLine("Second date failed to parse");