簡體   English   中英

Swift DateComponents 包含錯誤的小時值

[英]Swift DateComponents contains wrong hour value

我在 StackOverflow 上搜索了答案,但找不到與我的完全匹配的問題。

  • 我在 GMT+2 時區。

  • 我的 Mac 的時間和時區已正確設置並以 24 小時格式正確顯示。

  • 我的 iPhone 模擬器的時間與我的 Mac 的時間相匹配,但采用 12 小時格式,但這不是問題。

  • 這是我的 Swift 代碼。 代碼中的注釋是從調試控制台中的打印 output 復制而來的:

     let tzSecsFromGMT = TimeZone.current.secondsFromGMT() print(tzSecsFromGMT) // 7200 let nowDate = Date(timeIntervalSinceNow: TimeInterval(tzSecsFromGMT)) print(nowDate) // 2021-02-27 21:33:19 +0000 (21:33 matches my Mac's time) let triggerDate = nowDate + 30 // seconds print(triggerDate) // 2021-02-27 21:33:49 +0000 (30 seconds after nowDate, it's correct) let dateComponents = Calendar.current.dateComponents([.timeZone, .year, .month, .day, .hour, .minute, .second], from: triggerDate) print(dateComponents) // timeZone: Europe/Bucharest (current) year: 2021 month: 2 day: 27 hour: 23 minute: 33 second: 49 isLeapMonth: false // (NOTE THE HOUR is 23 instead of 21 !)
  • 現在日期的時間是 21。

  • triggerDate 的小時是 21。

  • 但是 dateComponent 的小時數是 23 而不是 21。

我究竟做錯了什么?

那里的問題是您將 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM