Dannie P
Dannie P

Reputation: 4622

Hours between dates with SwiftDate

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

Answers (2)

Kappei
Kappei

Reputation: 714

In SwiftDate you can easily do

(date1 - date2).in(.hour)

Upvotes: 4

vadian
vadian

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

Related Questions