Search code examples
iosswiftdateformatter

Difference between boarding time and current time in UTC in iOS , Swift


I am getting Boarding Time from service ( lets say BT- Boarding Time) I need to find out the differnce between Boarding Time and current time and then find out the difference in Hour , Min.

The condition is user may check the difference between these from any country in the world. so i used UTC to calculate but its giving correct result , kindly help me in this.

 func dayStringFromTime() -> String {
        let currentTimeUnix = Date().timeIntervalSince1970
        let date = NSDate(timeIntervalSince1970: currentTimeUnix)
        let dateFormatter = DateFormatter()
        //  dateFormatter.dateFormat = "HH:mm:ss"
        return date.description
    }

let CT  = dayStringFromTime() //time1
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-mm-dd HH:mm:ss"
let CTDate = formatter.date(from: CT)
let time1 = boardingDateTime//timeformatter.date(from: CT)
let time2 = CT_Date//timeformatter.date(from: ETD)
//You can directly use from here if you have two dates
let interval = time1.timeIntervalSince(time2! as Date)
let hour = (interval ) / 3600;
let minute = interval.truncatingRemainder(dividingBy: 3600) / 60
let intervalInt = Int(interval)
print("\(intervalInt < 0 ? "-" : "+") \(Int(hour)) Hours \(Int(Int(minute))) Minutes")
let minText = Int(minute) > 0 && Int(minute) != 0 ? " \(Int(minute)) min" : (Int(minute) < 0 ? " \(Int(abs(minute))) min" : "")
let hrText  = Int(hour) > 0 && Int(hour) != 0 ? " \(Int(hour)) hr" : (Int(hour) < 0 ? " \(Int(abs(hour))) hr" : "") 

this url https://stackoverflow.com/a/28608779/3400991 shows the exact problem about this result, kindly help


Solution

  • This is way easier that you have made it out to be:

    let boardingTime = Date().addingTimeInterval(3200) // the `addingTimeInterval` is for demonstration purposes only.
    let now = Date()
    let difference = Calendar.current.dateComponents([.hour, .minute, .second], from: now, to: boardingTime)
    print("Boarding will be in: \(difference.hour!):\(difference.minute!):\(difference.second!)")