【发布时间】:2017-03-13 10:16:20
【问题描述】:
这应该是一个非常简单的问题,但我似乎无法理解它。
鉴于我的时区是 EDT (GMT-4),为什么 GMT 的 04:00 变成 23:00 而不是 00:00?
// The offset is -4 hours
let offsetFromGMT = Calendar.current.timeZone.secondsFromGMT() / 60 / 60
// 2017-03-12 04:00
var destinationComponents = DateComponents()
destinationComponents.timeZone = TimeZone(secondsFromGMT: 0)
destinationComponents.year = 2017
destinationComponents.month = 03
destinationComponents.day = 12
destinationComponents.hour = -offsetFromGMT // 4 hours
// Why is this 2017-03-11 23:00 and not 2017-03-12 00:00?
let date = Calendar.current.date(from: destinationComponents)!
// Outputs 23
Calendar.current.dateComponents([.hour], from: date).hour
【问题讨论】:
-
print(date)应该显示2017-03-12 04:00:00 +0000。 – 根据您所在位置的该日期是否启用夏令时,在您当地的时区中可能是2017-03-12 00:00或2017-03-11 23:00。 –Calendar.current.timeZone.identifier打印什么? -
它打印“America/New_York”并且 print(date) 显示 2017-03-12 04:00:00 +0000。是的,但在这种情况下,为什么 secondsFromGMT() 中不包含夏令时?
-
secondsFromGMT()是当前的 GMT 偏移量。还有另一个函数secondsFromGMT(for: date)返回指定日期的 GMT 偏移量,其中包括 DST。 – 你到底想达到什么目标? -
是的,我看过那个,但如果我执行 Calendar.current.timeZone.secondsFromGMT(for: Date()),它仍然是 -14400(-4 小时)。如果我传入日期而不是 Date() 则为 -18000,但这对我来说毫无意义。作为背景,我有一个适用于 GMT 日期的应用程序,但是从 EDT 到 GMT 的翻译在某个地方出错了。当我注意到这一点时,我正在尝试调试代码。上面的示例代码只是说明了问题。
标签: ios swift calendar timezone