0

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

Shobhakar Tiwari
  • 7,862
  • 4
  • 36
  • 71
  • 1
    What version of Swift are you working in? – Daniel T. Nov 25 '18 at 20:54
  • i am using Swift 4 – Shobhakar Tiwari Nov 25 '18 at 20:57
  • 1
    Take a look at [DateComponentsFormatter](https://developer.apple.com/documentation/foundation/datecomponentsformatter) to get rid of the weird date math. – vadian Nov 25 '18 at 20:59
  • @DanielT.'s answer will get you the right result **IF** you have formatted your boarding time correctly. Can you provide the code where you format it? Do you provide it with the correct TimeZone? – fguchelaar Nov 25 '18 at 22:13
  • 1
    @fguchelaar There's no formatting a `Date` object. As long as he created it properly (presumably from a network response?) my answer will work. I like @MadProgrammer's reference to `DateComponentsFormatter` though. – Daniel T. Nov 25 '18 at 22:18
  • @DanielT.that's what I meant: how did he 'format' (wording is incorrect, now that I'm reading it back, parsing was the word I meant) the string to a Date. What's the `dateFormat` of the `DateFormatter` when parsing the input. – fguchelaar Nov 25 '18 at 22:22

2 Answers2

2

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!)")
Daniel T.
  • 32,821
  • 6
  • 50
  • 72
1

First of all, be very careful with date/time mathematics, it's not a straight linear conversion, there are lots and lots of rules which go around it and make it ... complicated.

The first thing you need is to calculate the difference between the two times, lucky for you, this is relatively easy...

var boardingTime = Date()
boardingTime = bordingTime.addingTimeInterval(Double.random(in: 0.0..<86400.0))
let now = Date()
let difference = boardingTime.timeIntervalSince(now)

This gives you the number of seconds between these two values (a positive value been the time till, a negative value been the time after)

Next, you need the hours/minutes in some form of human readable notation. It might seem tempting to just start by multiplying and dividing everything by 60, but that would be a mistake and lead you into bad habits (sure over a short range it's not bad, but you need to be very careful)

A better solution would be to use a DateComponentsFormatter...

let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute]
formatter.unitsStyle = .abbreviated

formatter.string(from: difference)

Which will take care of all the "rules" for you, but, it will also localise the results, always a bonus.

The above example will print something like...

10h 28m
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366