Reputation: 4622
What's the easiest way to get number of hours between 2 dates with SwiftDate
lib?
In this case hours could be days / minutes or whatever I'll need next time.
I see I can probably do (date1 - date2) / 60 * 60
but that just does not feel right.
Upvotes: 2
Views: 309
Reputation: 285069
Calendar
can do that:
let calendar = Calendar.current
let components = calendar.dateComponents([.hour], from: date1, to: date2)
let hours = components.hour!
or as one-liner:
let hours = Calendar.current.dateComponents([.hour], from: date1, to: date2).hour!
or as Date
extension:
extension Date {
func hoursSince(date: Date) -> Int
{
return Calendar.current.dateComponents([.hour], from: date, to: self).hour!
}
}
Upvotes: 2