A Little More on NSDateFormatter

A Little More on NSDateFormatter

NSDateFormatter (as mentioned previously) is tremendously handy.

Unfortunately, it is rather sparsely documented.

I’ve had the opportunity to use it in a number of different projects; however, in each one, I’ve had to use a bit of trial and effort to actually get strings to decode into a valid NSDate object.  All the while wishing for better documentation.

Today, I ran across this blog post that does a good job of consolidating format strings for NSDateFormatter in one place.  I thought about adding my own comments to this post, but I believe the original does the topic enough justice.  Check it out, then see my version of a helper function which I use in the TweetPhoto iPhone App.

If you plan on writing an iPhone interface to any of the Social Media APIs (Twitter, FriendFeed, etc.), you’re gonna wind up (at some point) needing to implement some helper function for NSDateFormatter.

NSDateFormatter and Twitter

NSDateFormatter and Twitter

The NSDateFormatter class is super handy for scanning incoming text dates in order to create a NSDate object, so that you can then use for other date manipulation.

As handy as it is, it is not as well documented as one would hope.

As a bit of a teaser, I’ll list a version of a NSDateFormatter helper function that will take dates from the Twitter API and convert them into NSDate objects. I will flesh out the details behind the function in a post to come Thursday or Friday.

NSDateFormatter Helper:

-(NSDate*)dateFromTwitter:(NSString*)str {
static NSDateFormatter* sTwitter = nil;

if (str == nil) {
NSDate * today = [[[NSDate alloc] init] autorelease];
return today;

if (!sTwitter) {
sTwitter = [[NSDateFormatter alloc] init];
[sTwitter setTimeStyle:NSDateFormatterFullStyle];
[sTwitter setFormatterBehavior:NSDateFormatterBehavior10_4];
[sTwitter setDateFormat:@”EEE LLL dd HH:mm:ss Z yyyy”];
return [sTwitter dateFromString:str];