Search code examples
iosswiftswift3

Compare only time difference in Date objects


I have two Date objects and I want to compare only the time difference between them, ignoring the date. Would be something like:

dt1 = (Date) 2016-09-22 20:05:01 UTC
dt2 = (Date) 2016-08-20 22:06:00 UTC

and the difference between dt1 and dt2 would be 2 hours or 121 minutes.

Is there a function in Swift that I could do that?


Solution

  • You can use Calendar to extract the DateComponents and then combine the day, month, and year from one with the hour, minute, and second of the other into another Date object. Then you can compare the two Date objects that share the same date using the well documented methods.

    For example, given date1 and date2, we can calculate date3 with date of date1, but time of date2. We can then compare date1 to this new date3:

    let calendar = Calendar.current
    let components2 = calendar.dateComponents([.hour, .minute, .second], from: date2)
    let date3 = calendar.date(bySettingHour: components2.hour!, minute: components2.minute!, second: components2.second!, of: date1)!
    

    Then, to get the number of minutes between date1 and date3:

    let minutes = calendar.dateComponents([.minute], from: date1, to: date3).minute!
    

    Or hours and minutes:

    let difference = calendar.dateComponents([.hour, .minute], from: date1, to: date3)
    let hours = difference.hour!
    let minutes = difference.minute!
    

    Or, if you want to show this to the user, you'd often use DateComponentsFormatter to get a nice, localized string representation:

    let formatter = DateComponentsFormatter()
    formatter.unitsStyle = .full
    formatter.allowedUnits = [.hour, .minute]  // or [.minute]
    let string = formatter.string(from: date1, to: date3)!