17

Possible Duplicate:
Converting an ISO 8601 timestamp into an NSDate: How does one deal with the UTC time offset?

I use rails as backend, the default date output is 2008-12-29T00:27:42-08:00

But after my research NSDateFormatter can not support it, except I change date out to 2008-12-29T00:27:42-0800

Here is the code I used to parse ISO 8601 date, but it's not work

NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSLog(@"%@", [dateFormatter dateFromString:@"2008-12-29T00:27:42-08:00"]);

Any ideas?

Community
  • 1
  • 1
allenwei
  • 4,047
  • 5
  • 23
  • 26
  • @Ryan It know this link, I just want to get a better solution. – allenwei Oct 28 '11 at 07:06
  • Did you find a solution for this? I'm looking for a solution that can provide NSDate or NSString for a date formatted as "2008-12-29T00:27:42-08:00". The accepted answer isn't working for me. The problematic part is timezone i.e. "-08:00". – Mustafa Jun 06 '13 at 11:41

1 Answers1

47

The problem is with the timezone on the end.

You need to either have it as: GMT-0X:00 or as -0X00 with no separate between hours and minutes.

The following two combinations work:

Combo 1 - use GMT format (GMT-0X:00) and ZZZZ

NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZ"];
NSLog(@"DATE FORMAT:%@", [dateFormatter dateFromString:@"2008-12-29T00:27:42GMT-08:00"]);

Combo 2 - use RFC 822 format (-0X00) and ZZZ

dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
NSLog(@"DATE FORMAT:%@", [dateFormatter dateFromString:@"2008-12-29T00:27:42-0800"]);
gamozzii
  • 3,911
  • 1
  • 30
  • 34
  • 1
    According to http://www.w3.org/TR/NOTE-datetime 2008-12-29T00:27:42-08:00 is a valid date format. I can change default format from Rails backend, but I think it's not good solution. – allenwei Oct 28 '11 at 05:39
  • I tried the second solution but there is smth wrong with time zone: "DATE FORMAT:2008-12-29 08:27:42 +0000". "-0800" turned into "+0000" – JastinBall Dec 22 '11 at 08:44
  • 1
    this returns nil when used with 2008-12-29T00:27:42Z and this is also ISO8601 http://en.wikipedia.org/wiki/ISO_8601 – AmineG Jun 14 '12 at 18:24
  • 2
    In my case I received something like that: "2015-05-07T16:16:47.054403Z" And I had to use: "yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSZ" – diegomen May 12 '15 at 11:38
  • swift version: `code` let date = "2008-12-29T00:27:42-0800" let formatter = NSDateFormatter() formatter.setLocalizedDateFormatFromTemplate("yyyy-MM-dd'T'HH:mm:ssZZZ") let final = formatter.dateFromString(date) `code` – fatihyildizhan Jun 11 '15 at 14:29
  • 2
    to decode iso 8601 formatted date just set the date format to "yyyy-MM-dd'T'HH:mm:ss.SSSZ", the big "S" stands for milliseconds – Julio Garcia Feb 08 '16 at 20:39