开发者

NSDate expressed in different time zones, i.e. local time zone (GMT-400) to PST

开发者 https://www.devze.com 2022-12-24 22:33 出处:网络
I know how to use NSTimeZone to derive the offset for the current time in another time zone. NSDate always returns relative to GMT, so how do I derive a string with the proper time zone information? i

I know how to use NSTimeZone to derive the offset for the current time in another time zone. NSDate always returns relative to GMT, so how do I derive a string with the proper time zone information? i.e. I take the current time where I am (in EST) and using NSTimeZone end up subtracting the 3 hours necessary to represent the time in PST. But all I've done is subtract 3 hours from the time which is still represented relative to my time zone. How do I get NSDateFormatter to spit out the time using the destination time zone?

One tack I tried was:

NSCalen开发者_开发知识库dar *cal = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSTimeZone *tz = [NSTimeZone timeZoneForSecondsFromGMT:(-8 * 3600)]; // for PST
NSDateComponents *dc = [cal components: NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:now];
[cal setTimeZone:tz];
NSDate *newDate = [cal dateFromComponents:dc];

No love. I could take the individual date components and compose a string, but it wouldn't be localizable.

A related problem:

NSTimeZone *tz = [NSTimeZone timeZoneForSecondsFromGMT:(-8 * 3600)]; // for PST
NSString *abbreviation = [tz abbreviation];
NSString *name = [tz name];

Both abbreviation and name end up returning GMT-0800, not PST as I'd expect. So I couldn't even do the above if I wanted to. What am I doing wrong?


NSDate always returns relative to GMT

This doesn't make sense. NSDate just encapsulates an absolute moment in time (let's forget about relativity for a second) and it has no concept of time zones whatsoever. To say that NSDate times are relative to GMT is wrong.

To output a date in a specific time zone, you should create an instance of NSDateFormatter and call setTimeZone: on it to set the time zone. According to the Unicode docs, the format string @"zzz" should output the time zone value as "PST".

0

精彩评论

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

关注公众号