开发者

Time zone added to hour after using nsdateformatter

I'm trying to convert a string date (2011-06-08T08:05:00.000-08:00) into a NSDate using the following code:

NSDateFormatter *dateFormatter = [[[NSDateFormatte开发者_如何学Pythonr alloc] init] autorelease];
//Translate 2011-06-08T08:05:00.000-08:00 into 2011-06-08T08:05:00.000-0800
stringDate = [stringDate stringByReplacingOccurrencesOfString:@":" withString:@"" options:0 range:NSMakeRange([aDate length] - 5, 5)];
[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSZZZ"];  
NSDate *dateFromString = [dateFormatter dateFromString:stringDate];

At this point, dateFromString is 2011-06-08 16:05:00 +0000. What I actually wanted was for dateFromString to be 2011-06-08 08:05:00 -0800. What am I doing wrong?

Thanks!


So this will not have a direct answer and will assume that your string format will be the same. What we are going to extract the timezone part (last 5 characters) and then calculate how many seconds we are off from GMT. NSTimeZone has a convenience method timeZoneForSecondsFromGMT: that will help us get what we need. This is what you need to add to the code in the question.

NSString * zoneString = [stringDate substringFromIndex:([stringDate length] - 5)];
NSTimeInterval timeInterval = [[zoneString substringToIndex:3] intValue] * 3600;
timeInterval += [[zoneString substringFromIndex:3] intValue] * 60;

NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:timeInterval]];
[formatter setDateFormat:@"yyyy'-'MM'-'dd' 'HH':'mm':'ss ZZZ"];
NSLog(@"%@", [formatter stringFromDate:dateFromString]);

Hopefully this helps you. If you've found a better answer already, let us know.

Original Answer
One thing about the NSDate is that the time returned is always in GMT. You can't change that. You will have to use an NSDateFormatter to print it right. Something like this,

NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"PST"]];
[formatter setTimeStyle:NSDateFormatterFullStyle];
[formatter setDateStyle:NSDateFormatterFullStyle];
NSLog(@"%@", [formatter stringFromDate:[NSDate date]]);

So setting the timezone for the formatter that does dateForString: won't help. You will need to create a new one when you want them with a different timezone.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜