如何对持续时间值(但不是日期)进行计算,例如运行结果?

时间:2018-01-22 20:05:31

标签: javascript jquery

我有一个运动结果数据库,如下所示:

const database = [{"distance in km": 10, "duration": "00:45:36", "pace": "00:04:34"}];
  1. 要计算pace值,我必须将duration除以number of kilometers,但我该怎么做?无论我尝试什么方法,都会返回NaN

  2. 如何对多个持续时间值执行计算?例如。如何获得三次跑步的平均速度? (0:05:2200:04:5400:05:05应平均为00:05:07

1 个答案:

答案 0 :(得分:0)

fill: '-1'
function durationToSeconds(dur) {
dur=dur.toString();
     var hours=parseFloat(dur.substr(0, dur.indexOf(":")));
     var minutes=parseFloat(dur.substr(dur.indexOf(":")+1, dur.lastIndexOf(":")));
     var seconds=parseFloat(dur.substr(dur.lastIndexOf(":")+1));
     return (hours*60*60)+(minutes*60)+(seconds);
}
function secondsToDuration(secs) {
     var hours=Math.floor(secs/(60*60));
     secs-=hours*60*60;
     var minutes=Math.floor(secs/60);
     secs-=minutes*60;
     var seconds=secs;
     return (hours.toString().length===1?"0":"") + hours + ":" + (minutes.toString().length===1?"0":"") + minutes + ":" + (seconds.toString().length===1?"0":"") + seconds;
}
function getPace(t1, speed) {
     var secs1=durationToSeconds(t1);
     return secondsToDuration(Math.round(secs1/speed));
}