Cocoa 中的日期和时区问题
我有一个字符串,例如 2010-09-24
。现在我希望这个字符串像我一样在另一个时区读取。因此,我创建一个 NSDateFormatter
并将其时区设置为 Europe/Berlin
。我得到的是将 NSDate 对象调整为我的本地时区(例如 America/New_York
)(2010-09-23 18:00:00
)。
但我想要一个时区 Europe/Berlin
的 NSDate
,时间值为 2010-09-24 00:00:00
。我该怎么做?
我尝试在 [dateFormatter dateFromString:@"2010-09-24"]
期间将 defaultTimeZone 设置为 Europe/Berlin
但当我将时区改回本地时间时NSDate
对象的区域也会发生变化。
I hav a string e.g. 2010-09-24
. Now I want this string read as it is in an other timezone as I am. So I create an NSDateFormatter
and set it's time zone e.g. to Europe/Berlin
. What I get back is an NSDate object adjusted (2010-09-23 18:00:00
) to my local time zone (e.g. America/New_York
).
But I want an NSDate
in the time zone Europe/Berlin
with the time value 2010-09-24 00:00:00
. How can I do this?
I tried to set the defaultTimeZone to Europe/Berlin
during the [dateFormatter dateFromString:@"2010-09-24"]
but when I change back the timeZone to my local time zone the NSDate
object changes too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你的问题的答案是在它本身之上
处理 Cocoa 中的时区
I think answer to your question is in stack over it self
Handling time zones in Cocoa
NSDate 只是一个 CFDate,它代表一个 CFAbsoluteTime,它只是具有不同纪元(2001 年而不是 1970 年)的 POSIX 时间(UTC-秒-自纪元)。 (我很确定 CFAbsoluteTimeGetCurrent() 只是调用 gettimeofday();它似乎只有微秒分辨率。)
或者,简而言之:NSDate 是一个时间戳,而不是日历日期。如果您想表示日历日期/时间,请使用 NSDateComponents。无论哪种情况,您都需要指定日历(可能是公历)和时区;请参阅 NSCalendar。
差异大约取决于更改时区偏移时发生的情况:
如果您假设事件的时区偏移量不会更改,则指定 NSDate 和 NSTimeZone 名称会很方便。许多日历应用程序都会这样做,当美国决定更改夏令时规则时,(几乎)一切都会出错。
NSDate is just a CFDate, which represents a CFAbsoluteTime, which is just POSIX time (UTC-seconds-since-epoch) with a different epoch (2001 instead of 1970). (I'm pretty sure that CFAbsoluteTimeGetCurrent() just calls gettimeofday(); it only seems to have microsecond resolution.)
Or, in short: NSDate is a timestamp, not a calendar date. If you want to represent a calendar date/time, use NSDateComponents. In either case, you'll need to specify a calendar (probably Gregorian) and a time zone; see NSCalendar.
The difference depends approximately on what happens when you change time zone offset:
If you assume that the time zone offset of an event doesn't change, it's convenient to specify an NSDate and NSTimeZone name. Many calendar apps do this, and (almost) everything goes wrong when the US decides to change DST rules.