OmniOwl
OmniOwl

Reputation: 5709

One DateTime parses fine but the other doesn't?

I have an ASP site where I read two dates from two fields.

The dates are generated using JavaScript and one of the two dates I need to read pass but the other doesn't. Even though they are made the exact same way.

So as you see here from my Immediate Window:

datepicker_start.Value
"03/10/2016"

datepicker_end.Value
"03/23/2016"

The first one parses fine, the second one does not:

DateTime start = DateTime.Parse(datepicker_start.Value);
DateTime end = DateTime.Parse(datepicker_end.Value);

It throws a FormatException on the end date:

DateTime.Parse(datepicker_end.Value)

threw an exception of type

System.FormatException: The String wasn't recognized as a valid DateTime.

I cannot understand why this is happening. If you need anything other than what I gave already please let me know as this is truly puzzling.

Upvotes: 0

Views: 43

Answers (1)

Soner Gönül
Soner Gönül

Reputation: 98740

DateTime.Parse uses standard date and time format of your current culture settings.

Probably your culture setting has dd/MM/yyyy as a standard format and since there is no 23rd month, your second line throws FormatException.

I would suggest to use DateTime.ParseExact with a custom format like;

DateTime end = DateTime.ParseExact(datepicker_end.Value,
                                   "MM/dd/yyyy",
                                   CultureInfo.InvariantCulture);

For example; if you debug your code, your start will be 3rd of October, not 10th of March.

Upvotes: 3

Related Questions