在我的应用程序中,我在 SharedCalendar
类中有一个静态的 gregorian
属性,其定义如下:
static let gregorian: Calendar = {
var calendar = Foundation.Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone.autoupdatingCurrent
return calendar
}()
当我想访问特定时区中某个日期的某一天时,我会调用:
SharedCalendar.gregorian.dateComponents([ .day ], from: someDate).day!
假设 someDate
是 Date(timeIntervalSinceReferenceDate: 512658000.0)
即 2017-03-31 13:00:00 +0000
。
当我在温哥华时区启动应用程序时,SharedCalendar.gregorian.timeZone
属性具有值 America/Vancouver (autoupdatingCurrent)
和 SharedCalendar 的结果。 gregorian.dateComponents([ .day ], from: someDate).day!
是 31
这是正确的。
当我将应用程序置于后台并将时区切换到悉尼并再次运行应用程序时,SharedCalendar.gregorian.timeZone
属性具有值 Australia/Sydney (autoupdatingCurrent)
(这是正确的),但是 SharedCalendar.gregorian.dateComponents([ .day ], from: someDate).day!
的结果是 31
错误(应为 1
)。
当我将 gregorian
属性的定义更改为 var
时:
var gregorian: Calendar {
var calendar = Foundation.Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone.autoupdatingCurrent
return calendar
}
一切正常,对于 America/Vancouver (autoupdatingCurrent)
我得到 31
,对于 Australia/Sydney (autoupdatingCurrent)
我得到 1
。
现在我不太明白 TimeZone.autoupdatingCurrent
是如何工作的。当设备的时区发生变化时,SharedCalendar.gregorian.timeZone
反射(reflect)了设备的时区,但看起来 SharedCalendar.gregorian
以某种方式使用旧时区。
有人对这种行为有解释吗?
最佳答案
我报告了radar关于这个问题,今天 Apple 回应:
The reason that your
static let
calendar’s time zone doesn’t update is that you need to issue a call toNSTimeZone.resetSystemTimeZone()
to sync up with the system time zone. See the documentation forNSTimeZone.resetSystemTimeZone()
for more info: https://developer.apple.com/documentation/foundation/nstimezone/1387189-resetsystemtimezone?language=objcThe reason your
var
calendar works is because every call to the calendar property actually creates a new computed calendar, which happens to be set to a new time zone representing the current system time zone.
这是有道理的,因为 static let
缓存了系统的时区,并且从 NSTimeZone.resetSystemTimeZone
的文档中我们可以读到:
If the application has cached the system time zone, this method clears that cached object. If you subsequently invoke systemTimeZone, NSTimeZone will attempt to redetermine the system time zone and a new object will be created and cached (see systemTimeZone).
关于ios - 具有自动更新当前时区的静态让日历不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44190763/