Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 366
ToroLoco Avatar asked Dec 25 '17 08:12

ToroLoco


People also ask

How do I find the difference between two times in Swift?

To calculate the time difference between two Date objects in seconds in Swift, use the Date. timeIntervalSinceReferenceDate method.

Can you subtract dates in Swift?

To subtract hours from a date in swift we need to create a date first. Once that date is created we have to subtract hours from that, though swift does not provide a way to subtract date or time, but it provides us a way to add date or date component in negative value.


Video Answer


2 Answers

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)!)
like image 134
vadian Avatar answered Sep 18 '22 15:09

vadian


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
like image 42
Gereon Avatar answered Sep 22 '22 15:09

Gereon