如何在 swift 5 中找到 2 date/time 字符串的总和

How to find sum of 2 date/time string in swift 5

我在一个循环中有多个 date/time 字符串

for item in self.sleepingActivityData ?? [] {
                    let value = Util.getFormattedDateString(inputDateString: self.findDateDiff(time1Str: item.startsAt ?? "", time2Str: item.endsAt ?? ""), inputDateFormat: "h m", outputDateFormat: "HH:mm")
                    print(value as Any) // "00:45"
                    
                }

'value' 的值为“00:45”、“00:30”、“00:45”。我想添加这 3 个时间字符串,所以总和应该是“02:00” 我怎样才能在 swift 中做到这一点?

这是我的 getFormattedDateString() 函数:

static func getFormattedDateString(inputDateString: String, inputDateFormat: String, outputDateFormat: String) -> String?{
        let dateFormatterInput = DateFormatter()
        dateFormatterInput.dateFormat = inputDateFormat//"yyyy-MM-dd HH:mm:ss"
        
        let dateFormatterOutput = DateFormatter()
        dateFormatterOutput.dateFormat = outputDateFormat//"EEEE, MMM dd hh:mm a"
        
        if let date = dateFormatterInput.date(from: inputDateString) {
            return (dateFormatterOutput.string(from: date))
        } else {
            return nil
        }
    }

& 这就是我在 findDateFiid() func:

中发现两次之间的区别的方式
   func findDateDiff(time1Str: String, time2Str: String) -> String {
        let timeformatter = DateFormatter()
        timeformatter.dateFormat = "HH:mm:ss"

        guard let time1 = timeformatter.date(from: time1Str),
            let time2 = timeformatter.date(from: time2Str) else { return "" }
        //You can directly use from here if you have two dates
        let interval = time2.timeIntervalSince(time1)
        let hour = interval / 3600;
        let minute = interval.truncatingRemainder(dividingBy: 3600) / 60
        return "\(Int(hour)) \(Int(minute))"
    }

我在操场上编写了这个代码,你可以用你自己的数组替换日期 dateArray:self.sleepingActivityData

导入 UIKit

var dateArray = ["00:45", "00:30", "00:45"]
var sumH: Int = Int()
var sumM: Int = Int()

for (index, item) in dateArray.enumerated() {
    print(item as Any) // "00:45"
    if index < dateArray.count {
        addTime(timeStr: dateArray[index])
    }
}

func addTime(timeStr: String) {
    let values = timeStr.components(separatedBy: ":")
    //sum hours
    guard let h = Int(values[0]) else {return}
    //sum minutes
    guard let m = Int(values[1]) else {return}

    sumM = sumM + m
    sumH = sumH + h
    
    if sumM >= 60 {
        sumM = sumM - 60
        sumH = sumH+1
    }
    
    print("hours:",sumH)
    print("minutes:",sumM)
}

没有string-date-mathAPI.

基本上你需要两种方法将 HH:mm 转换为分钟,反之亦然

func hhmmToMinutes(_ hhmm : String) -> Int {
    let components = hhmm.components(separatedBy: ":")
    guard components.count == 2,
          let hr = Int(components[0]),
          let mn = Int(components[1]) else { return 0 }
    return hr * 60 + mn
}

func minutesToHourMinute(_ minutes : Int) -> String {
    let hr = minutes / 60
    let mn = minutes % 60
    return String(format: "%02ld:%02ld", hr, mn)
}

然后你可以使用更高级别API来计算时间

let array = ["00:45", "00:30", "00:45"]
let minutes = array.map{hhmmToMinutes([=11=])}.reduce(0, +)
let timeString = minutesToHourMinute(minutes)
print(timeString) // 02:00