Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate time difference in Swift 4

Tags:

swift

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.

like image 471
tyguy Avatar asked Dec 02 '25 05:12

tyguy


1 Answers

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")
like image 95
Nima Yousefi Avatar answered Dec 03 '25 23:12

Nima Yousefi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!