time icon indicating copy to clipboard operation
time copied to clipboard

Add total unit values to TimeDifference

Open Mordil opened this issue 4 years ago • 3 comments

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?

Mordil avatar Oct 12 '21 20:10 Mordil

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 avatar Oct 12 '21 22:10 davedelong

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

davedelong avatar Oct 12 '21 23:10 davedelong

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

Mordil avatar Oct 13 '21 00:10 Mordil

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?

davedelong avatar Apr 07 '24 02:04 davedelong

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

Mordil avatar Apr 07 '24 12:04 Mordil