Alastair Pitts
Alastair Pitts

Reputation: 19601

DateTime.Parse issue, not support in System.Globalization.GregorianCalendar

I'm having an issue where a specific time string, contained in the Gmail Atom feed isn't parsing using DateTime.Parse(). I understand I could use DateTime.TryParse(), but I'm curious to why these two don't work, where as all of the rest do.

2009-12-28T24:11:48Z
2009-12-30T24:16:20Z

the specific exception is:

System.FormatException: The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.

My suspicion is that it's because of the hour 24... rather than 00, but I'm not sure how I would rectify that.

Upvotes: 7

Views: 37477

Answers (5)

Martin Brown
Martin Brown

Reputation: 25310

private static DateTime ParseDate(string s)
{
    DateTime result;
    if (!DateTime.TryParse(s, out result))
    {                
        result = DateTime.ParseExact(s, "yyyy-MM-ddT24:mm:ssK", System.Globalization.CultureInfo.InvariantCulture);
        result = result.AddDays(1);
    }
    return result;
}

Upvotes: 16

Nathan Wheeler
Nathan Wheeler

Reputation: 5932

If it IS just the 24 instead of 00, you can simply replace it and add a day:

String s = "2009-12-28T24:11:48Z";
DateTime dt;
if (s.Contains("T24:")
{
    s = s.Replace("T24:", "T00:");

    if (DateTime.TryParse(s, out dt))
        dt.AddDays(1);
}
else
{
    DateTime.TryParse(s, out dt);
}

Upvotes: 2

Oren Mazor
Oren Mazor

Reputation: 4477

turns out google's using the w3c date and time standard: http://www.w3.org/TR/NOTE-datetime, which c# doesnt support? weird, but not that weird.

this project appears to implement that for you.

http://www.codeproject.com/KB/cs/w3cdate.aspx

edit: yes, I see now that google's not doing it right, but there's an exception for that in the w3cdate c# structure.

Upvotes: 1

Benjamin Podszun
Benjamin Podszun

Reputation: 9827

Same idea as md5sum, but a different way:

 DateTime.ParseExact(
  "2009-12-28T24:11:48Z",
  new []{ "yyyy-MM-ddTHH:mm:ssK", "yyyy-MM-ddT24:mm:ssK" }, 
  System.Globalization.CultureInfo.InvariantCulture,
  System.Globalization.DateTimeStyles.None
)

You'd still need to check if the date is correct though.

Upvotes: 1

James Bloomer
James Bloomer

Reputation: 5322

The DateTime entry in MSDN says that it supports ISO 8601 which allows both 24 and 00. It should allow the format of type [YYYY][MM][DD]T[hh][mm]Z eg. 2010-01-04T14:04Z.

Midnight is a special case and can be referred to as both "00:00" and "24:00". The notation "00:00" is used at the beginning of a calendar day and is the more frequently used. At the end of a day use "24:00". Note that "2007-04-05T24:00" is the same instant as "2007-04-06T00:00" (see Combined date and time representations below).

Upvotes: 1

Related Questions