Friday, June 4, 2010

Converting the Twitter API "created_at" string into a .NET Date Object

If you have worked with the Twitter API in .NET, you will receive a string date representation back corresponding to a tweet in the following format:

"Tue Apr 07 22:52:51 +0000 2009"

If you are like me, you may prefer to have this converted into a .NET Date or DateTime object. This is easy enough to do with the .ParseExact method on a Date object. We just have to provide it a date format for which we are inputting. The magic date formula for the Twitter "created_at" date is as follows: "ddd MMM dd HH:mm:ss zzz yyyy"

The following code shows how to convert this string into a valid date:

Dim TwitterStringDate As String = "Tue Apr 07 22:52:51 +0000 2009"
Dim TwitterDate As Date = Date.ParseExact(TwitterStringDate, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture)
You might actually do this as part of a LINQ query, and in that case, you might have something within your query that looks similar to the code below:

.PublishDate = If(xe..Value IsNot Nothing, Date.ParseExact(xe..Value, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture), Date.MinValue)


Post a Comment