如何对字符串格式的时间持续时间数组求和

How to sum array of time Duration Which is in string format

我有一个字符串数组,格式如下,

let sample_array = ["05:30","06:20","04:20","09:40"]

当我们将所有string格式转换为DATE格式后,我们如何从这个数组中找到总时间。

我认为您可以跳过将字符串转换为日期以获得所需输出的步骤:

let sample_array = ["05:30","06:20","04:20","09:40"]
var hours:Int = 0
var minutes:Int = 0
for timeString in sample_array {
    let components = timeString.components(separatedBy: ":")
    let hourComp = Int(components.first ?? "0") ?? 0
    let minComp = Int(components.last ?? "0") ?? 0
    hours += hourComp
    minutes += minComp
}
hours += minutes/60
minutes = minutes%60
let hoursString = hours > 9 ? hours.description : "0\(hours)"
let minsString = minutes > 9 ? minutes.description : "0\(minutes)"
let totalTime = hoursString+":"+minsString

从问题和评论看来,您正在尝试从给定数组计算总时间(以小时和分钟为单位)。

let sample_array = ["05:30","06:20","04:20","09:40"]

func getTime(arr: [String]) -> Int {

  var total = 0
  for obj in arr {

      let comp = obj.split(separator: ":")

      var hours = 0
      var minutes = 0
      if let hr = comp.first, let h = Int(String(hr)) {
        hours = h * 60
      }

      if let mn = comp.last, let min = Int(String(mn)) {
        minutes = min
      }

      total += hours
      total += minutes

    }
    return total

}

let totalTime = getTime(arr: sample_array)
print(totalTime)

let hours = totalTime/60
let minutes = totalTime%60
print("\(hours) hours and \(minutes) minutes")

您还可以进一步计算日、月、年。

希望是你想要的。

对于您的情况,我建议您不要将其视为日期来处理。你可以通过实现一个函数来得到你想要的结果:

func getTotalTime(_ array: [String]) -> String {
    // getting the summation of minutes and seconds
    var minutesSummation = 0
    var secondsSummation = 0

    array.forEach { string in
        minutesSummation += Int(string.components(separatedBy: ":").first ?? "0")!
        secondsSummation += Int(string.components(separatedBy: ":").last ?? "0")!
    }

    // converting seconds to minutes
    let minutesInSeconds = secondsToMinutes(seconds: secondsSummation).0
    let restOfSeconds = secondsToMinutes(seconds: secondsSummation).1

    return "\(minutesSummation + minutesInSeconds):\(restOfSeconds)"
}

// 
func secondsToMinutes (seconds : Int) -> (Int, Int) {
    return ((seconds % 3600) / 60, (seconds % 3600) % 60)
}

因此:

let array = ["20:40" , "20:40"]
let result = getTotalTime(array)
print(result) // 41:20