iPhone NSDateFormatter Timezone Conversion

John Muchow picture John Muchow · Jun 22, 2010 · Viewed 33.5k times · Source

I am trying to create a formatter that will convert the date format shown to an NSDate object:

NSString *dateStr = @"2010-06-21T19:00:00-05:00";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
NSDate *date = [dateFormat dateFromString:dateStr];  

The issue is the timezone -05:00, which is not parsed properly with the format above. Any suggestions?

Answer

brynbodayle picture brynbodayle · Dec 19, 2012

To process the time zone with the colon in it, you just need to use 5 'Z's. This is a pretty common date format, the ISO-8601 format. This will only work on iOS 6.x+

-(NSDate *) dateFromString:(NSString *)string {

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];

    return [formatter dateFromString:string];
}