7

I need to create an NSDate from json, and the date in in a format I have never used. The date string I'm getting back is 2014-02-07T03:10:43.824Z. Does anyone know the correct date format string I need to use for the date formatter?

Chandler De Angelis
  • 2,646
  • 6
  • 32
  • 45

1 Answers1

16
 NSDateFormatter *dateFormat = [NSDateFormatter new];
 //correcting format to include seconds and decimal place
 NSString* input = @"2014-02-07T03:10:59:434Z";
 dateFormat.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
 // Always use this locale when parsing fixed format date strings
 NSLocale* posix = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
 dateFormat.locale = posix;
 NSDate* output = [dateFormat dateFromString:input];
AmyNguyen
  • 437
  • 6
  • 10
Valentin Shamardin
  • 3,569
  • 4
  • 34
  • 51
  • @Rob, thanks, I've made edits – Valentin Shamardin Feb 07 '14 at 07:28
  • 2
    This did not work for me. The date format string that worked for me was `yyyy-MM-dd'T'HH:mm:ss.SSSZ` – Richard Shin Oct 27 '14 at 18:23
  • Try `'Z'` instead of `Z` – Valentin Shamardin Oct 27 '14 at 19:37
  • 4
    No, 'Z' would escape the Z character, which is not what we want. The Z in the timestamp is a valid character which indicates the UTC timezone (see [the UTC section here](http://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators)). This is why [the answers on this SO post](http://stackoverflow.com/questions/5185230/converting-an-iso-8601-timestamp-into-an-nsdate-how-does-one-deal-with-the-utc?lq=1) use Z, not 'Z'. – Richard Shin Oct 27 '14 at 20:14
  • 1
    The answer contains an error, the 'Z' should have been Z. – Tom Vos Jun 18 '20 at 06:49