Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting ex. 2010-09-11T00:00:00+01:00 format to NSDate

I have spent way too much time (over an hour) on what I though would be a two minute task. On the iPhone:

NSString * dateString = @"2010-09-11T00:00:00+01:00";
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-dd'T'HH:mm:ssTZD"];
NSDate  *date = [formatter dateFromString:dateString];

RESULT: date == nil

What am I missing!! (Besides my deadline)

Regards,

Ken

like image 416
gnasher Avatar asked Nov 14 '10 22:11

gnasher


2 Answers

TZD isn't a defined formatter per the unicode spec. The document you've linked to elsewhere was a suggestion someone made to W3C, for discussion only. The unicode standard followed by Apple is a finished standard, from a different body.

The closest thing to what you want would be ZZZ (ie, @"YYYY-MM-dd'T'HH:mm:ssZZZ"), but that doesn't have a colon in the middle. So you'd need to use the string:

2010-09-11T00:00:00+0100

Rather than the one you currently have that ends in +01:00.

E.g. the following:

NSString * dateString = @"2010-09-11T00:00:00+0100";
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-dd'T'HH:mm:ssZZZ"];
NSDate  *date = [formatter dateFromString:dateString];
NSLog(@"%@", date);

Logs a valid date object, of 2010-09-10 23:00:00 GMT.

like image 193
Tommy Avatar answered Oct 21 '22 16:10

Tommy


Tip: try using your formatter to convert from an NSDate object to a string, then see what you get. It's often easier to debug in that direction than the other.

Have you read this?

http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns

That TZD at the end of your format string looks a bit dodgy.

like image 29
Simon Whitaker Avatar answered Oct 21 '22 17:10

Simon Whitaker