JohnK JohnK - 3 months ago 21
iOS Question

How do I get ISO 8601 date in iOS?

It's easy enough to get the ISO 8601 date string (e.g.,

2004-02-12T15:19:21+00:00
) in PHP via
date('c')
, but how does one get it in Objective-C (iPhone)? Is there a similarly short way to do it?

Here's the long way I found to do it:

NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ";

NSDate *now = [NSDate date];
NSString *formattedDateString = [dateFormatter stringFromDate:now];
NSLog(@"ISO-8601 date: %@", formattedDateString);

// Output: ISO-8601 date: 2013-04-27T13:27:50-0700


Seems an awful lot of rigamarole for something so central.

Answer

Use NSDateFormatter:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];   
NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:enUSPOSIXLocale];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];

NSDate *now = [NSDate date];
NSString *iso8601String = [dateFormatter stringFromDate:now];

And for the lazy ones in Swift:

let dateFormatter = NSDateFormatter()
let enUSPosixLocale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.locale = enUSPosixLocale
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"

let iso8601String = dateFormatter.stringFromDate(NSDate())