Search code examples
c#datetimeasp.net-mvc-5datetime-formattryparse

TryParseExact failing with DateTime


I am coding an MVC 5 internet application and I have a Bootstrap DateTimePicker control (https://github.com/Eonasdan/bootstrap-datetimepicker) to select a DateTime. Before I add the DateTime value to a model object, I use the TryParseExact function to check that the DateTime is valid.

I am getting an error with the TryParseExact code.

Here is an example:

The selected DateTime is 30 December 2015 with the DateTimePicker. This is displayed as:

12/30/2015 3:09:32 PM

My TryParseExact code is as follows:

DateTime mapLocationStartDate;
string format = "MM-dd-yyyy h:mm:ss tt";
if (!DateTime.TryParseExact(iMapLocationDate.displayMapLocationStartDate, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out mapLocationStartDate))
{

}

12/30/2015 3:09:32 PM fails the TryParseExact code.

Can I please have some help with this?

Thanks in advance.


Solution

  • If your iMapLocationDate.displayMapLocationStartDate value is "12/30/2015 3:09:32 PM" and you expect it to be always in this format, then use a format that exactly match it.

    Please try this format instead:

    string format = "MM/dd/yyyy h:mm:ss tt";