开发者

NSDateFormatter not working properly with UTC

I have the following date: 2011-04-29T14:54:00-04:00

When it runs through the following code to convert it to a date, the date is null for some reason:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *date = [dateFormatter da开发者_JAVA技巧teFromString:localDate];
[dateFormatter release];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-mm-dd"];
NSLog(@"%@", [formatter stringFromDate:date]);

Any help would be appreciated

SOLVED:

Ok, I figured it out. For some reason, this method doesn't work.

NSDate *date = [dateFormatter dateFromString:localDate];

This works instead. Hope it helps someone!

NSError *error = nil;
NSDate *date = nil;
[dateFormatter getObjectValue:&date forString:localDate range:nil error:&error];


Ok, I figured it out. For some reason, this method doesn't work.

NSDate *date = [dateFormatter dateFromString:localDate];

This works instead. Hope it helps someone!

NSError *error = nil;
NSDate *date = nil;
[dateFormatter getObjectValue:&date forString:localDate range:nil error:&error];


Try setting the timezone:

dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

and you might need to quote the -'s, :'s, and the Z in your format string (maybe not the -'s and :'s, but I think at least the Z):

[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];

Other than those, that is how my date formatter is configured and it works fine.


NSDateFormatter seems to only implement the canonical formats for timezones with 'Z' as described in UTS #35. With no leniency in parsing.

  1. TimeZoneID+/-offset with hours and minutes separated by colon, eg. 2011-04-29T14:54:00GMT-04:00
  2. +/-offset with no separation between hours and minutes, eg. 2011-04-29T14:54:00-0400

Try changing the format of the timezone in your localDate string.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜