NSDate在不同的时区,即当地时区(GMT-400)到PST [英] NSDate expressed in different time zones, i.e. local time zone (GMT-400) to PST

查看:166
本文介绍了NSDate在不同的时区,即当地时区(GMT-400)到PST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何使用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];

缩写名称最终返回 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总是返回相对于GMT

NSDate always returns relative to GMT

这没有意义。 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文档,格式字符串 @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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆