Search code examples
iosobjective-cdatetimensdateformatter

iOS DateFormat with milliseconds and timezone


I'm trying to format a date in objective-c for an ios app in this format:

2017-02-15T16:32:59.9725843+11:00 

with no luck. I've tried:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
formatter.dateFormat = @"yyyy-MM-dd'T'hh:mm:ss.SSSSSSSZZZZZ";

and

formatter.dateFormat = @"yyyy-MM-dd'T'hh:mm:ss.fffffffZZZZZ";

As well as a bunch of other formats for the milliseconds and timezone (I've varied the number of Ss and Zs with no luck. All I get is a nil NSString.

Any help would be appreciated.


Solution

  • Your your String Time format is 24 hour, so use HH:mm:ss. in this place hh:mm:ss.

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone localTimeZone]];
    formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSSSSSZZZZZ";
    NSDate *getDate  = [formatter dateFromString:@"2017-02-15T16:32:59.9725843+11:00"];
    
    NSLog(@"getDate == %@",getDate);
    

    output:

    xcode output