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

  • Question

  • User351619809 posted

     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.

    Thursday, July 30, 2020 8:15 PM


  • User-1330468790 posted

    Hi anjaliagarwal5@yahoo.com,


    There is nothing to do with the CultureInfo for this error.

    The error message tells that you input a date time string which can not be identified from the given date time format.

    DateTime.ParseExact(DOB, "MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture);

    As you can see, you set the format as "MM-dd-yyyy". However, the input you provide is "7/30/1949".

    If you change the input to "07-30-1949", the exception message will go away.


    More details, you could refer to this: DateTime.ParseExact Method Definition 

    AND there is another option: DateTime.Parse Method

    You may be confused which method you should call, see this:  Which method do I call?


    Hope this can help you.

    Best regards,


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, July 31, 2020 2:58 AM