Calculate time difference in Swift 4

11,403

First, your math is wrong. 10:30 -> 1:20 is actually 2 hr 50 min. Second, you need to specify AM or PM, or use a 24-hour (military-style) clock. Finally, the solution is to use DateFormatter to convert the strings into Date values and use those to get the time difference, which you can then convert into hours/minutes.

    let time1 = "10:30AM"
    let time2 = "1:20PM"

    let formatter = DateFormatter()
    formatter.dateFormat = "h:mma"

    let date1 = formatter.date(from: time1)!
    let date2 = formatter.date(from: time2)!

    let elapsedTime = date2.timeIntervalSince(date1)

    // convert from seconds to hours, rounding down to the nearest hour
    let hours = floor(elapsedTime / 60 / 60)

    // we have to subtract the number of seconds in hours from minutes to get
    // the remaining minutes, rounding down to the nearest minute (in case you
    // want to get seconds down the road)
    let minutes = floor((elapsedTime - (hours * 60 * 60)) / 60)

    print("\(Int(hours)) hr and \(Int(minutes)) min")
Share:
11,403

Related videos on Youtube

tyguy
Author by

tyguy

Updated on June 04, 2022

Comments

  • tyguy
    tyguy over 1 year

    If I have two variables, "10:30" and another one "1:20", is there a way to to get the time difference between them of "2 hr and 50 min"?? I tried this below

    func calcTime(time1: String,time2: String) -> String {
        let time12 = (String(format: "%02d", time1))
        let time22 = (String(format: "%02d", time2))
    
        let time10 = time12.prefix(2)
        let time20 = time22.prefix(2)
    
        print("hours: \(time12)")
        print("minutes: \(time22)")
    
        let time11 = time1.suffix(2)
        let time21 = time2.suffix(2)
    
        var hours = 12 - Int(time10)! + Int(time20)!
        var minutes = Int(time11)! + Int(time21)!
    
        if minutes > 60 {
            hours += 1
            minutes -= 60
        }
    
        let newHours = (String(format: "%02d", hours))
        let newMin = (String(format: "%02d", minutes))
    
       return "\(newHours)hrs. \(newMin)min."
    }
    

    It's not really working the way I want it to.

    • TheNitram
      TheNitram over 5 years
      What I would do is convert them to TimeInterval then subtract the from another then convert the difference to your string format.
    • vadian
      vadian over 5 years
      Actually the difference is 2 hr and 50 min. 😉 And 1:20 is obviously PM, but how do you distinguish AM / PM? And I don't understand the first String(format lines. What are they supposed to do if the argument is a string?
  • tyguy
    tyguy over 5 years
    Thanks that helped a lot. I figured out a way yesterday, but it took me 120 lines of code. This is much simpler and isn't as big.
  • Ammar Mujeeb
    Ammar Mujeeb almost 4 years
    How to get seconds also, I want to show like mm:ss.
  • Ammar Mujeeb
    Ammar Mujeeb almost 4 years
    let seconds = floor((elapsedTime - (minutes * 60)))
  • Eman Shedeed
    Eman Shedeed over 3 years
    I try this but this line let date1 = formatter.date(from: time1)! through nil value exception