Search code examples
iosnsdatensdateformatteriso8601

How do I get an ISO 8601 date on iOS?


It's easy enough to get the ISO 8601 date string (for example, 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

It seems an awful lot of rigmarole for something so central.


Solution

  • 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"];
    [dateFormatter setCalendar:[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]];
    
    NSDate *now = [NSDate date];
    NSString *iso8601String = [dateFormatter stringFromDate:now];
    

    And in Swift:

    let dateFormatter = DateFormatter()
    let enUSPosixLocale = Locale(identifier: "en_US_POSIX")
    dateFormatter.locale = enUSPosixLocale
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
    dateFormatter.calendar = Calendar(identifier: .gregorian)
    
    let iso8601String = dateFormatter.string(from: Date())