Search code examples
c#.netdatetimeparsingrfc822

How do I parse an RFC822 date in .NET?


I have the following datetime string as returned to me by the Twitter API:

"Thu Apr 26 11:38:36 +0000 2012"

I need to convert this to a DateTime object so I call ParseExact with a custom format specifier:

CultureInfo provider = CultureInfo.InvariantCulture;
DateTime publishDate = DateTime.ParseExact(tweet["created_at"].ToString(), "ddd MMM dd hh:mm:ss zzz yyyy", provider);

However, this raise a FormatException exception for any variant of z, zz or zzz for the time zone:

String was not recognized as a valid DateTime.

Looking at the MSDN documentation it's clear that that format specifier is expecting the time zone to be in the format zz:zz where there is a colon in the time zone to delimit the hours and minutes.

I've checked other questions on Stack Overflow like:

and none of them really help.

Is there a time zone specifier I can use that will correctly parse this format?


Solution

  • Really silly this one.

    The problem was the hour specifier. I'd used "hh" which is for 12 hour clock times. For 24 hour times I should have used "HH".

    Note the subtle difference.

    Changing that it all works as expected.