Search code examples
iosobjective-cnsdate

dateFormatter string for date type 2013-03-24T02:15:23-08:00 using Objective C


I want to convert 2013-03-24T02:15:23-08:00 string to NSDate object. I tried formatter string yyyy-MM-ddTHH:mm:ss-Z, but the NSDate object is coming as nil.

Below is my code for conversion:

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"yyyy-MM-ddTHH:mm:ss-Z"];
        NSDate* date = [dateFormatter dateFromString:image.dateTaken];

Solution

  • There are two errors in the date format string:

    • The (literal) T character in the date format must be quoted as 'T'.
    • The format for a "ISO8601 time zone" like -08:00 is ZZZZZ. Note that the minus sign is part of the time zone itself, not part of the format.

    This should work:

    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];