Swift DateComponents 包含错误的小时值

Swift DateComponents contains wrong hour value

我在 Whosebug 上搜索了答案,但找不到与我的问题完全匹配的问题。

我做错了什么?

问题是您将 secondsFromGMT 添加到当前时区。日期只是一个时间点。日期(现在)在世界任何地方都是相同的。

let nowDate = Date()
print(nowDate.description(with: .current))       // Saturday, February 27, 2021 at 4:51:10 PM Brasilia Standard Time
print(nowDate)   // 2021-02-27 19:51:10 +0000   (+0000 means UTC time / zero seconds offset from GMT)

let triggerDate = nowDate + 30 // seconds
print(triggerDate)   // 2021-02-27 19:51:40 +0000 (30 seconds after nowDate at UTC (GMT)

let dateFromTriggerDate = Calendar.current.dateComponents([.calendar, .year, .month, .day, .hour, .minute, .second], from: triggerDate).date!
print(dateFromTriggerDate.description(with: .current))  // Saturday, February 27, 2021 at 4:51:40 PM Brasilia Standard Time