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

2020-05-24 02:34发布

问题:

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

回答1:

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.



回答2:

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.



回答3:

I solved this issue using this code.