How to Parse DateTimes from the Twitter API

If you were wanting to interact with the Twitter API under .NET, you might find yourself trying to convert a date value from the XML results over to a DateTime in your code. Twitter uses a weird format for their dates—Thu Sep 04 11:09:28 +0000 2008—that doesn't get converted properly with just a good ol' DateTime.Parse. You could spend a lot of time iteratively trying to figure out the correct format to use. Or, you could just use the following (my free gift to you, dear Twitter-API-consuming reader):

DateTime.ParseExact((directMessage.SelectSingleNode("//created_at").InnerText), "ddd MMM dd HH:mm:ss zzzz yyyy", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);

directMessage here is an XmlNode representing a single direct message extracted from a list of direct messages. I found this out after many iterations since all of the .NET libraries for Twitter just punt on this conversion.

 
Trackbacks
  • Trackbacks are closed for this entry.
Comments

  • 9/11/2008 2:44 PM Dan wrote:
    Wow -- how much hair pulling did that require? I've never even HEARD of 'ParseExact'.

    -D
    Reply to this
    1. 9/12/2008 9:31 AM bbrown wrote:
      I knew about ParseExact. The big problem was figuring out the format stuff—I had never seen 'zzzz' before. It makes sense when you think about it, but I just couldn't get it right. And the way parsing works is completely binary, so there's no feedback about what part you got wrong. But now it's solved and I don't have to think about it any more.
      Reply to this
Leave a comment

 Enter the above security code (required)

 Name (required)

 Email (will not be published) (required)

 Website

Your comment is 0 characters limited to 3000 characters.