2

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.

Dannie P
  • 4,464
  • 3
  • 29
  • 48
  • As vadian says, you can do `let value = Calendar.current.dateComponents([.hour], from: date1, to: date2).hour!`. But if this was for displaying elapsed time in the UI, I'd just get the `DateComponents` you needed and use `DateComponentsFormatter` for a nice localized string with tons of great customization options. – Rob Jun 14 '17 at 16:45
  • @Rob that's for quick check in logic check. I'm used to `MTDates`, but in swift you always need to cast `Date` to `NSDate` for it to work. In `MTDates` there would be `mt_hoursSinceDate` func for exactly that purpose. `SwiftDate` seems quite a big lib, I'm surprised I could not find what I need easily. – Dannie P Jun 14 '17 at 18:13

2 Answers2

4

In SwiftDate you can easily do

(date1 - date2).in(.hour)
Kappei
  • 714
  • 2
  • 15
  • 34
2

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!
    }
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • Thanks for your answer; that definitely would work, but that also does not feel right... I was looking for a 1-liner, similar to one in MTDates's `date1. mt_hoursSinceDate(date2)` but for `SwiftDate` lib (or similar). – Dannie P Jun 14 '17 at 18:12
  • I updated the answer with an one-liner and a `Date` extension. – vadian Jun 14 '17 at 18:15