Search code examples
iosobjective-cnsdateformatterrfc3339

How do I parse an ISO 8601/RFC 3339 timezone with NSDateFormatter?


I have a date string like this (ISO 8601 combined date and time representation or RFC 3339):

2010-09-04T19:13:00Z

But how do I configure the NSDateFormatter to accept this timezone format?


Solution

  • Have a look here about what Apple recommends:

    // Convert the RFC 3339 date time string to an NSDate.
    
    NSDateFormatter *rfc3339DateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    
    NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    
    [rfc3339DateFormatter setLocale:enUSPOSIXLocale];
    [rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
    [rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    
    NSDate *date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];