Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

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

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:

NSCalendar *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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...