Search code examples
iphoneobjective-ccocoa-touchnsdatensdateformatter

Unable to format UTC date with NSDateFormatter


I have the following date:

2011-10-20T01:10:50Z

I would like it to be formatted to

"M/d/yy 'at' h:mma"

Here is my code:

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    //The Z at the end of your string represents Zulu which is UTC
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [dateFormatter setDateFormat:@"yyyy-dd-MM'T'HH:mm:ss'Z'"];
    NSDate* newTime = [dateFormatter dateFromString:[message valueForKey:@"created_at"]];

    //Add the following line to display the time in the local time zone
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    [dateFormatter setDateFormat:@"M/d/yy 'at' h:mma"];
    NSString* finalTime = [dateFormatter stringFromDate:newTime];
    [dateFormatter release];
    NSLog(@"%@", finalTime);    

Unfortunately the finalTime is NULL here.


Solution

  • You have dd-MM backwards. You have 10 for dd and 20 MM. There is no month 20.

    2011-10-20T01:10:50Z
    @"yyyy-dd-MM'T'HH:mm:ss'Z'"
    

    Because of that, the newTime was null and the finalTime was null.

    Here's with the fix. This:

    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    
    //The Z at the end of your string represents Zulu which is UTC
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
    
    NSDate* newTime = [dateFormatter dateFromString:@"2011-10-20T01:10:50Z"];
    NSLog(@"original time: %@", newTime);
    
    //Add the following line to display the time in the local time zone
    [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
    [dateFormatter setDateFormat:@"M/d/yy 'at' h:mma"];
    NSString* finalTime = [dateFormatter stringFromDate:newTime];
    NSLog(@"%@", finalTime);    
    
    [dateFormatter release];
    

    Outputs:

    2011-10-19 22:05:15.107 Craplet[4231:707] original time: 2011-10-20 01:10:50 +0000
    2011-10-19 22:05:15.116 Craplet[4231:707] 10/19/11 at 9:10PM