Dia Dia - 11 days ago 7
Swift Question

Difference between two dateTimes in seconds vary due to different time zones - Swift 3

I need to find difference between current time (in seconds) and future start time (fetched from my web service in seconds).
I have coded the following :

let currentTime = Int64(Date().timeIntervalSince1970)
var time = Int64(timeArr[indexPath.row])

print("\(currentTime) vs \(time)")
time = time - currentTime
print("difference in time : \(time)")

let seconds = time % 60
let minutes = (time / 60) % 60
let hours = (time / 3600)


My console shows me this output:

1480400929 vs 1480552620
difference in time : 151691


The problem is that my current time is
Tue Nov 29 2016 11:58:49
and the start time is
2016-11-30 17:37:00
so the difference in hours should come to around 30 hours whereas it takes the times in different time zones due to which it comes to around 42 hours. How do I fix this? I have gone through many questions for the same but nothing works. Any help would be appreciated.

Answer

If you want the difference between two date in Hours, Minutes and seconds you can use DateComponent like this.

let component = Calendar.current.dateComponents([.hour, .minute, .second], from: Date(), to: startDate)
let hours = component.hour ?? 0
let minutes = component.minute ?? 0
let seconds = component.second ?? 0

Edit: To get date from miliseconds use Date(timeIntervalSince1970:) like this.

let startDate = Date(timeIntervalSince1970: miliSeconds / 1000)

Also you can convert string to Date using DateFormatter like this.

let stringDate = "2016-11-30 17:37:00"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
if let startDate = dateFormatter.date(from: stringDate) {
    print(startDate)
}