0

I have dates inside strings with this format:

2014-02-05T23:09:19.642Z
2014-02-05T23:09:54.645Z
...

I've tried to parse them to NSDate doing the following:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *date = [formatter dateFromString:dateString];

But date is ending up being null, so how this needs to be done?

I tried with:

[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.sssZ"];

And it works for

2014-02-05T23:13:51.000Z

But not with:

2014-02-05T23:23:44.420Z
2014-02-05T23:01:19.620Z
...
Daniel Romero
  • 1,581
  • 1
  • 20
  • 33
  • You're missing the fractional seconds in your format. – rmaddy Feb 05 '14 at 23:38
  • I don't think this deserves a down-vote – Madbreaks Feb 05 '14 at 23:39
  • do you mean like this: [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.sssZ"]; ? I tried this and it didn't work – Daniel Romero Feb 05 '14 at 23:40
  • 2
    @Madbreaks Yes it does. There are countless existing questions on this topic and a simple scan of the date format specification would answer it quickly. – rmaddy Feb 05 '14 at 23:46
  • Maybe you should actually consult [the documentation](http://www.unicode.org/reports/tr35/tr35-25.html#Date_Format_Patterns). – Hot Licks Feb 05 '14 at 23:47
  • 3
    This question appears to be off-topic because it can easily be answered by consulting the available documentation. – Hot Licks Feb 05 '14 at 23:48
  • possible duplicate of [Converting NSString to NSDate (and back again)](http://stackoverflow.com/questions/3917250/converting-nsstring-to-nsdate-and-back-again) – jww Apr 08 '14 at 09:24

1 Answers1

2

Simply change your formatter to

[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:sss.SSSZ"];

Since in your time string 2014-02-05T23:09:19.642Z you have milliseconds there, so you need to add SSS for those milliseconds

Xu Yin
  • 3,932
  • 1
  • 26
  • 46