0

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.

Kunal Shah
  • 1,071
  • 9
  • 24
  • Please add how you are making startDate and endDate. – Asteroid Jul 27 '22 at 18:58
  • If you set let now = Date(); let startDate = now.addingTimeInterval(-3600); let endDate = now it gives 1 0 0 which is correct. – Asteroid Jul 27 '22 at 19:00
  • @Asteroid I've update the code to reflect how I'm making `startDate` and `endDate` – Kunal Shah Jul 27 '22 at 19:01
  • You should use `func dateComponents(_ components: Set, from start: Date, to end: Date) -> DateComponents` where `from`/`to` params are `Date`. Else, it's more "complicated" since you don't have really a "start point", but a "floating one", and I guess that's the issue... – Larme Jul 27 '22 at 19:44
  • @Larme That worked, thank you so much! Could you elaborate on what you mean by "you don't have really a "start point""? I'm trying to understand better what I was doing wrong. Also, do you know why it'd work in the Playground but not on Xcode? – Kunal Shah Jul 27 '22 at 19:59
  • Could you print `startDateComponents` & `endDateComponents`, and `Locale.current`, when it's not working? Since it's `01:39:41`, I'm wondering, if with your locale, when you get the components, it's not getting the day before, hence startDate if you only consider weekday fails... But if you date `startDateComponents` had `.day` instead of `.weekday`, which isn't clear why it's used for a comparison, then since you consider only these variables, `startDateComponents` is after `endDateComponents` – Larme Jul 27 '22 at 20:06

0 Answers0