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

I know how to use NSTimeZone to get the offset for the current time in another time zone. NSDate always returns relative to GMT, so how can I get a string with time zone information? those. I take the current time where I am (in EST), and using NSTimeZone, I subtract 3 hours needed to represent the time in PST. But all I did is subtract 3 hours from the time that is still presented relative to my time zone. How to get NSDateFormatter to spit out time using destination time zone?

One trick 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 individual date components and compose a string, but that would not be localizable.

Related problem:

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

Both abbreviation and name return GMT-0800 , not PST, as I expected. Therefore, I could not even do higher if I wanted to. What am I doing wrong?

+3
date timezone formatting iphone nsdate
Mar 23 '10 at 20:34
source share
1 answer

NSDate always returns relative to GMT

It does not make sense. NSDate simply encapsulates an absolute point in time (let it forget about relativity for a second), and it has no idea about time zones at all. Say that the NSDate time relative to GMT is not true.

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

+12
Mar 23 '10 at 22:55
source share



All Articles