0xSina
0xSina

Reputation: 21563

NSDateFormatter not formatting (returning nil)

I have a date string, for example:

2012-04-09T23:57:44.070Z

My date format is:

[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];

But it's returning nil. What's wrong with my date format? Thanks

Upvotes: 0

Views: 721

Answers (1)

Dave DeLong
Dave DeLong

Reputation: 243156

You don't need to be so aggressive about escaping - and :. Also, your seconds characters are wrong. You should be using:

NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
[f setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];

NSLog(@"%@", [f dateFromString:@"2012-04-09T23:57:44.070Z"]);

This logs:

2012-04-09 23:57:44 +0000

If you don't set the timezone on the date formatter, it's going to assume you mean whatever time zone the device is in right now, and not the GMT timezone (which is what the Z is implying).

Upvotes: 5

Related Questions