简体   繁体   English

Swift DateComponents 包含错误的小时值

[英]Swift DateComponents contains wrong hour value

I have searched StackOverflow for answers but I couldn't find a question that quite matches mine.我在 StackOverflow 上搜索了答案,但找不到与我的完全匹配的问题。

  • I am in GMT+2 time zone.我在 GMT+2 时区。

  • My Mac's time and timezone are correctly set and correctly displayed in 24-hour format.我的 Mac 的时间和时区已正确设置并以 24 小时格式正确显示。

  • My iPhone simulator's time matches my Mac's time but in 12-hour format, but that's not a problem.我的 iPhone 模拟器的时间与我的 Mac 的时间相匹配,但采用 12 小时格式,但这不是问题。

  • Here's my Swift code.这是我的 Swift 代码。 Comments in the code were copied from the print output in the Debug console:代码中的注释是从调试控制台中的打印 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 !)
  • nowDate's hour is 21.现在日期的时间是 21。

  • triggerDate's hour is 21. triggerDate 的小时是 21。

  • But dateComponent's hour is 23 instead of 21.但是 dateComponent 的小时数是 23 而不是 21。

What am I doing wrong?我究竟做错了什么?

The issue there is that you are adding the secondsFromGMT to your current timeZone.那里的问题是您将 secondsFromGMT 添加到当前时区。 A date is just a point in time.日期只是一个时间点。 The date (now) is the same anywhere in the world.日期(现在)在世界任何地方都是一样的。

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