javascript - 以 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
。不知道我哪里出错了?
解决方案
这将是我这样做的方法:将 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
推荐阅读
- python - python .append() 替换列表的所有项目
- python - 具有多个函数和列表的 Python 线程
- php - Laravel 8:ReflectionException 函数()不存在
- c++ - 使用 `{}` 在 C++ 中聚合初始化联合
- javascript - Javascript中的未定义与引用错误
- reactjs - WebStorm 特定文件名不会被识别为 TypeScript 文件
- python-3.x - 为什么 pip 要求我选择一个程序来运行 pip?
- java - android中更改主题的切换按钮
- tensorflow - Tensorflow 1.12 与 Tensorflow 2.4 不同的结果
- macos - 如何修改 vim .zshrc 中的文本?