Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why NSDateFormatter can not parse date from ISO 8601 format [duplicate]

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?

like image 614
allenwei Avatar asked Oct 28 '11 04:10

allenwei


People also ask

How do I read the ISO 8601 date format?

ISO 8601 represents date and time by starting with the year, followed by the month, the day, the hour, the minutes, seconds and milliseconds. For example, 2020-07-10 15:00:00.000, represents the 10th of July 2020 at 3 p.m. (in local time as there is no time zone offset specified—more on that below).

Is ISO 8601 valid?

Yes it is a valid ISO 8601 date.

What is the Z in ISO 8601?

Z is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "T0930Z". "14:45:15 UTC" would be "14:45:15Z" or "T144515Z". The Z suffix in the ISO 8601 time representation is sometimes referred to as "Zulu time" because the same letter is used to designate the Zulu time zone.


1 Answers

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"]);
like image 180
gamozzii Avatar answered Sep 29 '22 01:09

gamozzii