4

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?

Jim G.
  • 15,141
  • 22
  • 103
  • 166
ChrisF
  • 134,786
  • 31
  • 255
  • 325

1 Answers1

4

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.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • I think the answer here is much better than your way of doing it: http://stackoverflow.com/questions/284775/how-do-i-parse-and-convert-datetime-s-to-the-rfc-822-date-time-format – DermFrench Jun 04 '15 at 10:00
  • @DermFrench - that question is a more general one. With this I had a very specific problem which had a very specific cause - albeit one that could be quite common to make. – ChrisF Jun 04 '15 at 10:03
  • I just assumed the parsing in the other answer would work in your case as well - didn't test it. – DermFrench Jun 04 '15 at 11:14