Swift - 时区关闭一小时/秒FromGMT 不正确

Rob*_*son 2 timezone calendar ios swift

这应该是一个非常简单的问题,但我似乎无法理解它。

鉴于我的时区是 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
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 5

Calendar.current.timeZone.secondsFromGMT()
Run Code Online (Sandbox Code Playgroud)

是您所在时区的当前GMT 偏移量。在您的情况下是 4 小时,因为纽约的当前时区是 EDT = GMT-4,夏令时处于活动状态。

所以你destinationComponentsdate格林威治时间凌晨四点:

2017-03-12 04:00:00 +0000
Run Code Online (Sandbox Code Playgroud)

那时,纽约的时区是 EST = GMT-5,并且夏令时未激活。因此,该日期2017-03-11 23:00在您当地的时区。


我会以不同的方式进行,避免“secondsFromGMT”。

示例: “2017-03-12 00:00:00” 纽约时间为“2017-03-12 05:00:00”格林威治标准时间。

var srcComponents = DateComponents()
srcComponents.timeZone = TimeZone(identifier: "America/New_York")!
srcComponents.year = 2017
srcComponents.month = 3
srcComponents.day = 12
srcComponents.hour = 0
srcComponents.minute = 0

let date = Calendar.current.date(from: srcComponents)!
print(date) // 2017-03-12 05:00:00 +0000
Run Code Online (Sandbox Code Playgroud)