开发者

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

开发者 https://www.devze.com 2023-01-25 15:53 出处:网络
I have spent way too much time (over an hour) on what I though would be a two minute task. On the iPhone:

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-11开发者_JAVA百科T00: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


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.


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.


I solved this issue using this code.

0

精彩评论

暂无评论...
验证码 换一张
取 消