问题描述
我知道如何使用 NSTimeZone 导出另一个时区中当前时间的偏移量.NSDate 总是相对于 GMT 返回,那么如何导出具有正确时区信息的字符串?即我采用我所在的当前时间(在 EST 中)并使用 NSTimeZone 最终减去表示 PST 时间所需的 3 小时.但我所做的只是从相对于我的时区仍然表示的时间中减去 3 小时.如何让 NSDateFormatter 使用目标时区吐出时间?
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.
一个相关的问题:
NSTimeZone *tz = [NSTimeZone timeZoneForSecondsFromGMT:(-8 * 3600)]; // for PST
NSString *abbreviation = [tz abbreviation];
NSString *name = [tz name];
abbreviation
和 name
最终都返回 GMT-0800
,而不是我期望的 PST.所以如果我想的话,我什至不能做上面的事情.我做错了什么?
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 只是封装了一个绝对的时刻(让我们暂时忘记相对论),它没有任何时区的概念.说 NSDate 时间相对于 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.
要输出特定时区的日期,您应该创建一个 NSDateFormatter
的实例并在其上调用 setTimeZone:
来设置时区.根据 Unicode docs,格式字符串 @"zzz"
应将时区值输出为PST".
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".
这篇关于NSDate 以不同时区表示,即本地时区 (GMT-400) 到 PST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!