计算 Swift 4 中的时差

2024-06-26

如果我有两个变量,“10:30”和另一个“1:20”,有没有办法获得它们之间的“2小时50分钟”的时间差?我在下面尝试过这个

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."
}

它并没有真正按照我想要的方式工作。


首先,你的数学是错误的。 10:30 -> 1:20 实际上是 2 小时 50 分钟。其次,您需要指定 AM 或 PM,或使用 24 小时(军用)时钟。最后,解决方案是使用DateFormatter将字符串转换为Date值并使用它们来获取时差,然后您可以将其转换为小时/分钟。

    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")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

计算 Swift 4 中的时差 的相关文章

随机推荐