How can I calculate Difference from two times in swift 3?

Use timeIntervalSince(_ anotherDate: Date) function to get difference between two dates.

func findDateDiff(time1Str: String, time2Str: String) -> String {
    let timeformatter = DateFormatter()
    timeformatter.dateFormat = "hh:mm a"

    guard let time1 = timeformatter.date(from: time1Str),
        let time2 = timeformatter.date(from: time2Str) else { return "" }

    //You can directly use from here if you have two dates

    let interval = time2.timeIntervalSince(time1)
    let hour = interval / 3600;
    let minute = interval.truncatingRemainder(dividingBy: 3600) / 60
    let intervalInt = Int(interval)
    return "\(intervalInt < 0 ? "-" : "+") \(Int(hour)) Hours \(Int(minute)) Minutes"
}

Call the function with two times to find the difference.

let dateDiff = findDateDiff(time1Str: "09:54 AM", time2Str: "12:59 PM")
print(dateDiff)

If you have 2 Date objects, you can get the TimeInterval (aka Double) difference using:

let difference = date1.timeIntervalSince(date2)

If you want to display the difference between the dates you should use DateComponentsFormatter, either like this:

let differenceDescription = dateComponentsFormatter.string(from: difference)

Or you can skip getting the time interval directly and just call:

let differenceDescription = dateComponentsFormatter.string(from: date1, to: date2)

As with all formatters, don't create them every time you need to use them. They're very heavy objects to create and should be stored for re-use.


Here is the two steps you can follow to solve this -

No.1

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

No.2

TimeInterval measures seconds, not milliseconds:

let date1 = Date()
let date2 = Date(timeIntervalSinceNow: 12600) // 3:30
let diff = Int(date2.timeIntervalSince1970 - date1.timeIntervalSince1970)
let hours = diff / 3600
let minutes = (diff - hours * 3600) / 60

Tags:

Ios

Swift