Search code examples
swiftdatensdatecomponents

Swift DateComponents contains wrong hour value


I have searched StackOverflow for answers but I couldn't find a question that quite matches mine.

  • I am in GMT+2 time zone.

  • My Mac's time and timezone are correctly set and correctly displayed in 24-hour format.

  • My iPhone simulator's time matches my Mac's time but in 12-hour format, but that's not a problem.

  • Here's my Swift code. Comments in the code were copied from the print output in the Debug console:

      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.

  • triggerDate's hour is 21.

  • But dateComponent's hour is 23 instead of 21.

What am I doing wrong?


Solution

  • The issue there is that you are adding the secondsFromGMT to your current timeZone. 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