I've seen many approaches how to compute the difference between two dates in terms of a particular date component, e.g. in days, hours, months etc. (see this answer on Stackoverflow):
Calendar.current.dateComponents([.hour], from: fromDate, to: toDate).hour
Calendar.current.dateComponents([.day], from: fromDate, to: toDate).day
Calendar.current.dateComponents([.month], from: fromDate, to: toDate).month
What I haven't seen is how to make calculations with the actual Date
objects. Something like
func computeNewDate(from fromDate: Date, to toDate: Date) -> Date
let delta = toDate - fromDate
let today = Date()
if delta < 0 {
return today
} else {
return today + delta
}
}
I have seen the DateInterval
type introduced in iOS 10 but according to the documentation
[it] does not support reverse intervals i.e. intervals where the duration is less than 0 and the end date occurs earlier in time than the start date.
That makes it inherently difficult to calculate with dates – especially when you don't know which one is the earlier date.
Is there any clean and neat approach to compute time differences between Date
s directly (and adding them to Date
instances again) without computing with their timeIntervalSinceReferenceDate
?