swiftdatensdatecomponents

Swift DateComponents contains wrong hour value


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

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