2

I get the following NSString from my web API: @"2013-12-03T19:13:56+00:00"

I want to take this NSString and create the corresponding NSDate by using NSDateFormatter. For the life of me I can not figure out the formatting string that will help me do this. I always get nil. Here is what I am trying:

+ (NSDate *)dateFromUTCFormattedDateString:(NSString *)dateString
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    [dateFormatter setTimeZone:timeZone];
    [dateFormatter setDateFormat:@"YYYY-MM-ddThh:mm:ssTZD"];
    // Apply the date formatter and return it.
    return [dateFormatter dateFromString:dateString];
}
ashutosh
  • 23
  • 1
  • 2
  • Possible duplicate of http://stackoverflow.com/questions/4999396/how-to-parse-a-date-string-into-an-nsdate-object-in-ios – rmaddy Dec 02 '13 at 22:54

1 Answers1

1

One problem is the timezone with the embedded ':'. Use the following date format:

@"yyyy-MM-dd'T'HH:mm:sszzz"

Notice that the 'zzz' in place of the 'TZD'.

See ICU User Guide: Formatting Dates and Times

enter image description here

Test:

NSString *dateString = @"2013-12-03T19:13:56+00:00";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:sszzz"];

NSDate *dateFromString = [dateFormatter dateFromString:dateString];
NSLog(@"dateFromString: %@", dateFromString);

NSLog output:

dateFromString: 2013-12-03 19:13:56 +0000
zaph
  • 111,848
  • 21
  • 189
  • 228
  • Thanks, the change in the string formatting you provided works correctly. – ashutosh Dec 03 '13 at 00:08
  • Thanks for the code snippet. I'm parsing a time-aware date returned from a Django-based backend, the string format that worked for this case is this: @"yyyy-MM-dd'T'HH:mm:ss.SSSZ" – Luis Artola Jan 06 '14 at 17:38