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

时间:2018-06-04 11:30:15

标签: ios arrays swift nsdate nsdateformatter

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

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

在我们将所有string格式转换为DATE格式之后,我们如何才能从此数组中找到总时间。

3 个答案:

答案 0 :(得分:4)

我认为您可以跳过将字符串转换为日期以实现所需的输出:

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

答案 1 :(得分:1)

对于您的情况,我建议处理它而不将其视为日期。您可以通过实现以下函数来获得所需的结果:

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

// https://stackoverflow.com/questions/26794703/swift-integer-conversion-to-hours-minutes-seconds
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

答案 2 :(得分:0)

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

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")

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

我希望这是你想要的。