Cocoa 中的日期和时区问题

发布于 2024-09-24 15:16:12 字数 513 浏览 0 评论 0原文

我有一个字符串,例如 2010-09-24。现在我希望这个字符串像我一样在另一个时区读取。因此,我创建一个 NSDateFormatter 并将其时区设置为 Europe/Berlin。我得到的是将 NSDate 对象调整为我的本地时区(例如 America/New_York)(2010-09-23 18:00:00)。

但我想要一个时区 Europe/BerlinNSDate ,时间值为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏末染殇 2024-10-01 15:16:12

我认为你的问题的答案是在它本身之上
处理 Cocoa 中的时区

I think answer to your question is in stack over it self
Handling time zones in Cocoa

山川志 2024-10-01 15:16:12

NSDate 只是一个 CFDate,它代表一个 CFAbsoluteTime,它只是具有不同纪元(2001 年而不是 1970 年)的 POSIX 时间(UTC-秒-自纪元)。 (我很确定 CFAbsoluteTimeGetCurrent() 只是调用 gettimeofday();它似乎只有微秒分辨率。)

或者,简而言之:NSDate 是一个时间戳,而不是日历日期。如果您想表示日历日期/时间,请使用 NSDateComponents。无论哪种情况,您都需要指定日历(可能是公历)和时区;请参阅 NSCalendar。

差异大约取决于更改时区偏移时发生的情况:

  • “金星凌日派对在我家”在各处同时发生,因此使用通用时间 (NSDate)
  • “吃午餐”发生在当地时间中午,因此使用 NSDateComponents。

如果您假设事件的时区偏移量不会更改,则指定 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:

  • "Transit of Venus Party at my house" happens simultaneously everywhere, so use universal time (NSDate)
  • "Have Lunch" happens at noonish local time, so use NSDateComponents.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文