对 00:00:00.000 和 javascript 格式的两个时间参数求和

sum two time param on format 00:00:00.000 with javascript

我正在尝试以 00:00:00.000 格式对一些时间格式参数求和,有没有我可以轻松使用的库或 javascript 函数?我想念 moment.js 中的某些功能?

预期的代码是

//variables time1 and time2 are in format 'hh:mm:ss.SSS' hour, minutes, seconds, milliseconds.

let time1='00:00:04.666';
let time2='00:00:09.335';

console.log(sum(time1,time2));

//expected output is '00:00:13.001'

您有什么想法可以提供帮助吗?

使用 moment.duration 和 moment-duration-format 插件

function sum(time1,time2){

    return moment.duration(time1).add(moment.duration(time2)).format('hh:mm:ss.SSS', {trim: false});
    //trim: false prevents trimming of zero values for large units

    //return informat = 'hh:mm:ss.SSS';

}

console.log(sum('23:11:11.111','11:12:23.456'))

let time1='00:00:04.666';
let time2='00:00:09.335';


let result=sum(time1,time2);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.25.3/moment-with-locales.min.js" integrity="sha256-8d6kI5cQEwofkZmaPTRbKgyD70GN5mDpTYNP9YWhTlI=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.3.2/moment-duration-format.js" integrity="sha256-V2cDGIwcTkie65pWb06MoExJ2IROrXOYZxEvrLj1rf0=" crossorigin="anonymous"></script>

尝试按照这些步骤...

  • time1time2 都转换为时间戳格式
  • 如果time2>time1sum=time2+(time2-time1) 否则:sum=time1+(time1-time2)
  • sum转换为您需要的格式。

您可以使用 abs()

替换步骤 2 中的 if/else 语句

在对象中添加格式为 HH:mm:ss 内容的总和示例:

  object.sum.tempoTotaleInOre = 0;
    totInHours = 0;
    for (var key in preventivo.fase){
      totInHours += moment.duration().add(0,'hours').add(preventivo.fase[key].timeToSum,'minutes').add(0,'seconds');
      object.sum.tempoTotaleInOre = moment.duration(totInHours).format('HH:mm:ss',{ trim: false });        
    }

以这种方式迭代我的对象“preventivo.fase”并将总和保存在“totInHour”中。最后将该值以正确的格式“HH:mm:ss”

注入 属性“object.sum.tempoTotaleInOre”