找到时间平均值hh:mm:ss [英] Find time average of hh:mm:ss
本文介绍了找到时间平均值hh:mm:ss的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个小提琴,用毫秒来计算平均时间。但是,我的数据库以hh:mm:ss的格式存储数据。
小提琴
I have this fiddle that calculates average time with miliseconds. However, my DB stores data in format of hh:mm:ss. fiddle
var times= [ '00:00:03.00', '00:00:05.00', '00:00:02.00', '00:00:06.00'],
date = 0,
result = '';
function offsetify(t){
return t < 10 ? '0' + t : t;
}
for(var x = 0; x < times.length; x++ ) {
var tarr = times[x].split(':');
date += new Date(0, 0, 0, tarr[0], tarr[1], tarr[2].split('.')[0], tarr[2].split('.')[1]).getTime();
}
var avg = new Date(date/times.length);
result = offsetify(avg.getHours()) + ':' + offsetify(avg.getMinutes()) + ':' + offsetify(avg.getSeconds()) + '.' + offsetify(avg.getMilliseconds());
document.write(result);
我需要确保将秒数平均为例如8.75然后将平均值返回为00:00 :9
使用这样的数组:
I need to make sure when seconds are averaged for example to 8.75 then average is returned as 00:00:9 using array like this:
var times= [ '00:00:03', '00:00:05', '00:00:020', '00:00:07']
有人可以帮我修改这个以正确地舍入hh:mm:ss格式。谢谢。
can someone please help me modify this to properly round off hh:mm:ss format. thanks.
推荐答案
你可以得到秒数,绕过值并建立一个平均时间的新字符串。
You could get the seconds, round the value and build a new string of the average time.
function getAverageTime(array) {
var times = [3600, 60, 1],
parts = array.map(s => s.split(':').reduce((s, v, i) => s + times[i] * v, 0)),
avg = Math.round(parts.reduce((a, b) => a + b, 0) / parts.length);
return times
.map(t => [Math.floor(avg / t), avg %= t][0])
.map(v => v.toString().padStart(2, 0))
.join(':');
}
console.log(getAverageTime(['00:00:03', '00:00:05', '00:00:020', '00:00:07']));
console.log(getAverageTime(['00:00:03', '00:30:05', '00:30:020', '03:00:07']));
ES5
function getAverageTime(array) {
var times = [3600, 60, 1],
parts = array.map(function (s) {
return s.split(':').reduce(function (s, v, i) {
return s + times[i] * v;
}, 0);
}),
avg = Math.round(parts.reduce(function (a, b) {
return a + b;
}, 0) / parts.length);
return times
.map(function (t) {
var value = Math.floor(avg / t);
avg %= t;
return value;
})
.map(function (v) {
return v.toString().padStart(2, 0);
})
.join(':');
}
console.log(getAverageTime(['00:00:03', '00:00:05', '00:00:020', '00:00:07']));
console.log(getAverageTime(['00:00:03', '00:30:05', '00:30:020', '03:00:07']));
这篇关于找到时间平均值hh:mm:ss的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文