使用 swift、和与差的小时运算

operation with hours using swift, sum and difference

在我的项目中,我需要分分秒秒地工作。 我在网上找不到太多信息。

这是我的问题:

let time1 = "22:00"
let time2 = "20:00"

问题 1:

如何减去时间 1 - 时间 2? 我期待结果 = 02:00 h

我开始编写一些代码,将这个时间转换为日期..

let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
var time1d = formatter.date(from: time1)!
let time2d = formatter.date(from: time2)!

但是现在我该如何减去这两个小时?

问题 2:

let time1 = "22:00"
let time2 = "20:00"

我如何计算 time1 + time2 的总和?例如应该给我结果 42:00 小时

感谢帮助

这不是约会。如果您只处理小时和分钟,并且输入始终是格式正确的字符串,您应该构建数据。

创建时间结构

struct Time {
    let hour: Int
    let minute: Int
}

还有一个自定义初始化程序。这假设您的字符串始终格式正确 00:00:

extension Time {
    init?(string: String) {
        guard string.count == 5,
              Array(string)[2] == ":",
              let hour = Int(string.prefix(2)),
              let minute = Int(string.suffix(2)),
              0...59 ~= minute else {
            return nil
        }
        self.hour = hour
        self.minute = minute
    }
}

为了显示您的时间结构 属性 您可以使其符合 CustomStringConvertible 并提供自定义描述

extension Time: CustomStringConvertible {
    var description: String {
        String(format: "%02d:%02d", hour, minute)
    }
}

关于加法和减法,您可以使您的 Time 结构符合 AdditiveArithmetic 并实现所需的运算符:

extension Time: AdditiveArithmetic {
    static func - (lhs: Time, rhs: Time) -> Time {
        let minutes = lhs.minute - rhs.minute + lhs.hour * 60 - rhs.hour * 60
        return .init(hour: minutes/60, minute: minutes%60)
    }
    static func + (lhs: Time, rhs: Time) -> Time {
        let minutes = lhs.minute + rhs.minute + lhs.hour * 60 + rhs.hour * 60
        return .init(hour: minutes/60, minute: minutes%60)
    }
    static var zero: Time { .init(hour: 0, minute: 0) }
}

游乐场测试:

let time1 = Time(string: "22:00")!
let time2 = Time(string: "20:00")!
let time3 = time1-time2
print(time3)
let time4 = time1+time2
print(time4)

那些将打印

02:00
42:00

首先我们创建 calculateDifference 函数,它使用 Swift 提供的 dateComponents 函数。

let time1 = "22:00"
let time2 = "20:00"

func formattedTime(_ time: String) -> Date? {
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "HH:mm"
    return formatter.date(from: time)
}

func calculateDifference(_ from: String, _ to: String) -> (hour: Int, minutes: Int) {
    guard let fromTime = formattedTime(from),
          let toTime = formattedTime(to) else {
        return (0,0)
    }
    let calendar = Calendar.current
    
    let components = calendar.dateComponents([.hour, .minute], from: fromTime, to: toTime)
    return (components.hour ?? 0, components.minute ?? 0)
}

然后我们创建 calculateSum,它在内部使用 calculateDifference 通过提供默认小时数 00:00

来获取小时数
func calculateSum(_ time1: String, _ time2: String) -> (hour: Int, minutes: Int) {
    let defaultTime = "00:00"
    let calculatedTime1 = calculateDifference(defaultTime, time1)
    let calcaultedTime2 = calculateDifference(defaultTime, time2)
    return(calculatedTime1.hour + calcaultedTime2.hour,
           calculatedTime1.minutes + calcaultedTime2.minutes)
}

现在,如果我们 运行 以下,我们将获得所需的结果。当然,需要进行一些格式化。

let difference = calculateDifference(time2, time1)
print("\(difference.hour):\(difference.minutes)")

let sum = calculateSum(time1, time2)
print("\(sum.hour):\(sum.minutes)")