davedelong / time

Robust and type-safe date and time calculations for Swift
MIT License
2.32k stars 77 forks source link

Add total unit values to TimeDifference #57

Closed Mordil closed 7 months ago

Mordil commented 3 years ago

Right now TimeDifference provides concrete Int properties of each unit component of a given difference, which leaves users to implement a way of getting a total of a specific unit.

For example, to find the total number of minutes between two TimePeriods (such as an event with a start/end), you need to do:

difference.hours * 60 + difference.minutes

I'd be appreciative to have an API like the following:

extension TimeDifference {
  func total(_ unit: Calendar.Component) -> Double
}

let diff = start - end // hour: 1 minute: 3

print(diff.total(.minute))
// 63
print(diff.total(.hour))
// 1.05

I understand this can get very problematic at higher & lower precision, maybe a first release could just be seconds/minutes/hours?

davedelong commented 3 years ago

I'm not sure this is entirely possible at the TimeDifference level… How would TimeDifference know if one of the intermediate hours was longer or shorter than normal?


Edit...

To give a concrete example: Let's say you ask for the number of days between two consecutive days. You get back a TimeDifference of 1 day. But if you then ask for how many hours that is, it can't tell you. It might be 23, 24, or 25 depending on which days they are and whether there's a daylight saving transition between them (or not). It gets worse if the days are further apart because there might be multiple transitions.

davedelong commented 3 years ago

I can see the appeal of something like this though. I'll think about it.

Mordil commented 3 years ago

That’s all one can ask! If it doesn’t make sense (or impossible to represent) I understand

davedelong commented 7 months ago

I think the solution here is to compute two differences:

let diff = start - end // hour: 1 minute: 3
let minuteDiff = start.differenceInWholeMinutes(to: end) // minute: 63

@Mordil is that sufficient for your use-cases?

Mordil commented 7 months ago

I think the 2nd API call is more of exactly what I was looking for, for the original use case