SWIFT3 – Get two time differences in SWIFT 3

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

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

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

I tried to get timeIntervalSince1970 from both of them and they subtracted them and got the difference in milliseconds, I will go back to hours and minutes, but I get a very large number, which does not correspond to the actual time.

let dateTest = time2.timeIntervalSince1970-time1.timeIntervalSince1970

Then I tried to use time2.timeIntervalSince(date: time1), but the result milliseconds again far exceeded the actual Time.

How can I get the correct time difference twice and get the hour and minute results in the format "0823" of 8 hours and 23 minutes?

The recommended method for 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)

Format? ld adds padding with zeros.

If you need a standard format, use a colon between hours and minutes, DateComponentsFormatter() may be a more convenient way

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

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

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

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

I tried to get timeIntervalSince1970 from both of them and they subtracted them and got the difference in milliseconds, I will go back to hours and minutes, but I get a very large number, which does not correspond to the actual time.

let dateTest = time2.timeIntervalSince1970-time1.timeIntervalSince1970

Then I tried to use time2.timeIntervalSince(date: time1), but the milliseconds again far exceeded the actual time.

How can I get the correct time difference twice and get the hour and minute results in the format "0823" of 8 hours and 23 minutes?

The recommended method for 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)

Format? ld adds padding with zeros.

If you need a standard format, use a colon between hours and minutes, DateComponentsFormatter() may be a more convenient way

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

Leave a Comment

Your email address will not be published.