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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…