Converting twitter <created_at> date to Sitecore date format
June 22, 2010 4 Comments
I wanted to pull down some twits from my twitter account and show them with Sitecore CMS. When i looked at the http://api.twitter.com/1/statuses/user_timeline/maanehunden.xml
feed, i realized that i had to convert this Wed Jun 16 19:59:33 +0000 2010 wired date-format in to something mere Sitecoreish in order to save this value in a date field,..
this is what i did:
protected string DateFormat(string twitterDate) { DateTime itemDate = DateTime.ParseExact(twitterDate, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture); //this is an example of sitecore date format 20100621T194455 return itemDate.ToString("yyyyMMddTHHmmss", CultureInfo.InvariantCulture); }
Now I can use this method to format twitter date the way i wanted, end of story (c:
A good idea is to use the TryParseExact method instead and a if statement to check if the parse is successful. In the (unlikely) event that the date format is changed, or in a different format, it won’t throw an exception.
And why not return a DateTime to make the method even more useful? 🙂
Hay Andreas, .. welcome to my blog,..
it’s a good idea, in other words you propose something like this (c:
protected DateTime DateFormat(string twitterDate)
{
DateTime itemDate = null;
if (!DateTime.TryParseExact(twitterDate, “ddd MMM dd HH:mm:ss zzz yyyy”, CultureInfo.InvariantCulture, DateTimeStyles.None, out itemDate))
throw new FormatException(string.Format(“Unable to format twitter date:{0}”, twitterDate));
return itemDate;
}
i had actually thought about returning a DateTime, but decided not to ,. because i needed a string formated in a sortan way so could feed it to a Sitecore item field (c:
Yeah, that what I meant!
And, while we’re at it. Why not make it an extension method to the string class? That way, you’ll get elegant code aswell 🙂
public static class StringExtensions
{
public static DateTime FromTwitterFormat(this string twitterDate)
{
DateTime parsedDate;
string dateFormatString = "ddd MMM dd HH:mm:ss zzz yyyy";
if (!DateTime.TryParseExact(twitterDate, dateFormatString, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out parsedDate))
{
throw new FormatException(String.Format("Error parsing twitter date '{0}'", twitterDate));
}
return parsedDate;
}
}
// call with
string created_at = "Wed Jun 16 19:59:33 +0000 2010";
DateTime parsedDate = created_at.FromTwitterFormat();
sweat U rock, (c: well i only needed it ones, but still it’s a good thing for a bigger app. .. (c: