Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# DateTime.Parse Error

Tags:

c#

datetime

Anyone have any idea why this fails? I was able to work around it with ParseExact, but I would like to understand why it is failing.

DateTime test = DateTime.Parse("Dec 24  17:45");

Dates < "Dec 24" work fine. Dates >= Dec 24 fail with this error:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.

EDIT: Thanks to Habib for noticing even when I didn't get an error it was not the result I was expecting. So be careful with the DateTime.Parse when not used with supported formats!

Here is what I did to fix the issue. I only have to handle two different formats. The current year would be "MMM dd HH:mm" otherwise it would be "MMM dd yyyy"

if (!DateTime.TryParseExact(inDateTime, "MMM dd HH:mm", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.AllowWhiteSpaces,out outDateTime))
{
    if (!DateTime.TryParseExact(inDateTime, "MMM dd yyyy", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.AllowWhiteSpaces, out outDateTime))
    {
        //Handle failure to Parse
    }
}
like image 276
wsware Avatar asked Feb 23 '15 18:02

wsware


1 Answers

Dates < "Dec 24" work fine. Dates >= Dec 24 fail with this error

DateTime.Parse uses the standard formats for parsing date and the reason it is failing for Day >= 24, is that it is considering that part as an hour part instead of day part as you assumed.

Since allowed hour part could be between 0 to 23, it works fine for those dates. (It is not considered a day part)

Also it is ignoring Dec part and considering current date for that part.

Consider the example below:

DateTime test = DateTime.Parse("Dec 22 17:45");

It returns:

test = {23/02/2015 10:17:00 PM}

Look at the time part it is set to 22:17 or 10:17 PM

like image 129
Habib Avatar answered Oct 11 '22 20:10

Habib