Anjali
Anjali

Reputation: 2698

string was not recognized as valid date time when CultureInfo is set to a different language

I am passing a valid datetime in string format from my front end aspx page to back end aspx.cs file. When I pass the date time string, I get an exception saying string was not recognized as a valid date time. Below is my code:

if (DOB != "")
{
    DateTime formatDate = 
        DateTime.ParseExact(DOB, "MM-dd-yyyy", 
            System.Globalization.CultureInfo.InvariantCulture);
    
    DOB = formatDate.ToString("yyyy-MM-dd");
}

when I am passing the date time, my culture is set to:

Thread.CurrentThread.CurrentCulture = new CultureInfo("es-MX");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-MX");

when I set the cultureInfo to "en-US" then I don't get the "string was not recognized as a valid date time" error, but as soon as I set the culture Info to "es-MX", I get this error.

Below is the screen shot of the date that I am passing to above code:

enter image description here

and this is the screen shot of the error that I am getting:

enter image description here

Instead of DateTime.ParseExact, I also tried DateTime.Convert and that is also throwing the same error.

Any help or hint will be greatly appreciated.

Upvotes: 3

Views: 852

Answers (1)

Anjali
Anjali

Reputation: 2698

This is what I did to fix above issue:

if (DOB != "")
{
    DOB = DOB.Replace("/", "-");

    DateTime formatDate =
         DateTime.ParseExact(DOB, 
            new string[] { "M-d-yyyy", "dd-MM-yyyy" },
            System.Globalization.CultureInfo.InvariantCulture, 
            System.Globalization.DateTimeStyles.None);

    DOB = formatDate.ToString("yyyy-MM-dd");

}

Upvotes: 4

Related Questions