Kunal Shah
Kunal Shah

Reputation: 1121

calendar.dateComponents returning negative value even though resultDate is after startDate

I have the following code:

let utime = 1658885981959026
let utimeInSeconds = Double(utime/1000000)
let startDate = Date(timeIntervalSince1970: utimeInSeconds) // Start date - 2022-07-27 01:39:41 +0000 
let endDate = Date() // End date - 2022-07-27 18:33:14 +0000

let calendar = Calendar.current
let startDateComponents = calendar.dateComponents([.weekday, .hour, .minute, .second], from: startDate)
let endDateComponents = calendar.dateComponents([.weekday, .hour, .minute, .second], from: endDate)
let differenceDateComponents = calendar.dateComponents([.weekday, .hour, .minute, .second], from: startDateComponents, to: endDateComponents)

print(differenceDateComponents.hour!, differenceDateComponents.minute!, differenceDateComponents.second!) // Prints -7 -6 -27

I'd expect the .hour value to be 16, but I get a value of -7 instead. Could someone help me understand why?

Note: Weirdly enough, if I run this in Swift playground, it gives me the correct values.

Upvotes: 0

Views: 166

Answers (0)

Related Questions