如何计算总时间 [英] How do I calculate a total time
本文介绍了如何计算总时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发一个基于Web的应用程序,以捕获视频播放列表的总时间.我的主要问题是我不知道如何从数组中计算总时间,例如:30:00 + 30:00 = 01:00.时间以mm:ss为单位,我需要以hh:mm
I am developing a web-based application to capture total time of playlist of video. my main problem is that I don't know how can I calculate the total time from an array e.g: 30:00 + 30:00 = 01:00. Time is in mm:ss output I need in hh:mm
var time = ["13:24", "4:28", "7:29"];
for (k in time){
add(time[k].split(":"));
}
推荐答案
您可以做什么的示例.
// assuming num will always be positive
function zeroPad(num) {
var str = String(num);
if (str.length < 2) {
return '0' + str;
}
return str;
}
// assuming your time strings will always be (H*:)(m{0,2}:)s{0,2} and never negative
function totalTimeString(timeStrings) {
var totals = timeStrings.reduce(function (a, timeString) {
var parts = timeString.split(':');
var temp;
if (parts.length > 0) {
temp = Number(parts.pop()) + a.seconds;
a.seconds = temp % 60;
if (parts.length > 0) {
temp = (Number(parts.pop()) + a.minutes) + ((temp - a.seconds) / 60);
a.minutes = temp % 60;
a.hours = a.hours + ((temp - a.minutes) / 60);
if (parts.length > 0) {
a.hours += Number(parts.pop());
}
}
}
return a;
}, {
hours: 0,
minutes: 0,
seconds: 0
});
// returned string will be HH(H+):mm:ss
return [
zeroPad(totals.hours),
zeroPad(totals.minutes),
zeroPad(totals.seconds)
].join(':');
}
var result1 = totalTimeString([
'13:24',
'4:28',
'7:29'
]);
console.log(result1);
var result2 = totalTimeString([
'13:24:06',
'4:28:46',
'17:29:11'
]);
console.log(result2);
这篇关于如何计算总时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文