开发者

Keep original time zone with NSDateFormatter

I have strings like 2011-01-19T20:30:00-5:00 and I'd like to parse them into an NSDate but I want to keep the original time zone.

NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormat开发者_运维知识库ter setDateFormat: @"yyyy-MM-dd'T'HH:mm:ssZ"];
NSLog(@"%@", [dateFormatter dateFromString: dateString]);
[dateFormatter release];

That snippet gives me 2011-01-20 02:30:00 +0100 which is also correct but I wish to keep the original time zone -0500 instead of my local time zone +0100 in the NSDate.


First of all, you should be aware that NSDate objects don't store anything related to their locales or timezones, and internally they're essentially represented as a number of seconds since the first instant of 1 January 2001, GMT.

If you are able to the timezone for the string in an NSTimezone object, just do the following before doing dateFromString:

[dateFormatter setTimeZone:timezoneForString];

and you'll be set.

If you're unable to get an NSTimezone and all you have is a string "2011-01-19T20:30:00-5:00", there isn't a very good way to get to an NSTimezone from the -5:00, since there isn't always an unambiguous way to get a timezone ID (e.g., "America/Los_Angeles") or timezone name (e.g., "Pacific Daylight Time") from an UTC offset. So you'd have to write your own code to manually extract the offset, store it, and add it to the time before displaying it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜