Dec
26th
Sat
26th
Parse a Rails timestamp in Cocoa
A quick snippet to parse a timestamp string that might be emitted from a Rails application.
Cocoa is very good at producing human-readable dates according to a user’s preferences and locale, but I was not impressed with the default parsing. And the documentation from Apple doesn’t come out and list the format rules. I was going to resort to class-dumping NSDateTimeFormatter but someone beat me to it.
NSString * dateAddeddString = [entryDictionary objectForKey:kTimestamp];
if (dateAddeddString != nil)
{
NSLog(@"dateAddeddString : %@", dateAddeddString);
// TODO find new home for date utilities in Workout
NSDateFormatter *inputFormatter = [[[NSDateFormatter alloc] init] autorelease];
// 2009-12-19T21:52:07-06:00
// http://www.stepcase.com/blog/2008/12/02/format-string-for-the-iphone-nsdateformatter/
[inputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
self.timestamp = [inputFormatter dateFromString:dateAddeddString];
NSLog(@"timestamp : %@", self.timestamp);
}
The result looks like this. Victory!
2009-12-26 20:40:56.355 redacted[18244:207] dateAddeddString : 2009-12-19T21:34:40-06:00 2009-12-26 20:40:56.356 redacted[18244:207] timestamp : 2009-12-19 21:34:40 -0600
Please hit me in the comments if this code smells bad to you.
Update: Now I’ve found http://stackoverflow.com/questions/399527/parsing-unsupported-date-formats-in-via-cocoas-nsdate