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

Viewed 445

I'm trying to sum some time-format param in format 00:00:00.000, is there some library or javascript function I could use easily? some function in moment.js that I miss?

the code expected is

//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'

Do you have some ideas that may help?

3 Answers

Add an example for sum times with format HH:mm:ss content in a object:

  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 });        
    }

In this way iterated my object "preventivo.fase" and save in "totInHour" the sum. Finally inject that value into the property "object.sum.tempoTotaleInOre" with the correct formatting "HH:mm:ss"

Using moment.duration and moment-duration-format plugin

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>

Try to follow these steps...

  • convert both time1 and time2 to the timestamp format
  • if time2>time1. sum=time2+(time2-time1) else: sum=time1+(time1-time2)
  • convert sum to the format you need.

You could replace if/else statement in step 2 by using abs()

Related