首页 > 解决方案 > 以 HH:MM:SS 格式将时间数组相加

问题描述

我正在尝试创建一个函数,它将时间数组中的所有值加在一起。

const times = ["00:00:50", "00:03:20", "00:00:50"]

到目前为止我所拥有的

  function sumTime(t1, t2, array = []) {
    const times = [3600, 60, 1],
      sum = [t1, t2, ...array]
        .map((s) => s.reduce((s, v, i) => s + times[i] * v, 0))
        .reduce((a, b) => a + b, 0);
    return times
      .map((t) => [Math.floor(sum / t), (sum %= t)][0])
      .map((v) => v.toString().padStart(2, 0));
  }
sumTime(times)

但我得到一个错误Cannot read property 'reduce' of undefined。不知道我哪里出错了?

标签: javascript

解决方案


这将是我这样做的方法:将 hh:mm:ss 格式的时间转换为数字将更容易将它们加在一起。最后,您可以将其转换回 Date 并调用toISOString(). substr(11, 8)会给你 hh:mm:ss 回来。

const times = ["00:00:50", "00:03:20", "00:00:50"];
    
function sumTime(times) {
  let sumSeconds = 0;
    
  times.forEach(time => {
    let a = time.split(":");
    let seconds = +a[0] * 60 * 60 + +a[1] * 60 + +a[2];
    sumSeconds += seconds;
  });
    
  return new Date(sumSeconds * 1000).toISOString().substr(11, 8);
}
    
console.log(sumTime(times));    //00:05:00


推荐阅读