Search code examples
swift3nstimeinterval

Get time difference between two times in swift 3


I have 2 variables where I get 2 times from datePicker and I need to save on a variable the difference between them.

    let timeFormatter = DateFormatter()
    timeFormatter.dateFormat = "HHmm"

    time2 = timeFormatter.date(from: timeFormatter.string(from: datePicker.date))!

I have tried to get the timeIntervalSince1970 from both of them and them substract them and get the difference on milliseconds which I will turn back to hours and minutes, but I get a very big number which doesn't corresponds to the actual time.

let dateTest = time2.timeIntervalSince1970 - time1.timeIntervalSince1970

Then I have tried using time2.timeIntervalSince(date: time1), but again the result milliseconds are much much more than the actual time.

How I can get the correct time difference between 2 times and have the result as hours and minutes in format "0823" for 8 hours and 23 minutes?


Solution

  • The recommended way to do any date math is Calendar and DateComponents

    let difference = Calendar.current.dateComponents([.hour, .minute], from: time1, to: time2)
    let formattedString = String(format: "%02ld%02ld", difference.hour!, difference.minute!)
    print(formattedString)
    

    The format %02ld adds the padding zero.

    If you need a standard format with a colon between hours and minutes DateComponentsFormatter() could be a more convenient way

    let formatter = DateComponentsFormatter()
    formatter.allowedUnits = [.hour, .minute]
    print(formatter.string(from: time1, to: time2)!)