How to calculate sum of multiple durations moment.js?

by cortez.connelly , in category: Javascript , 9 months ago

How to calculate sum of multiple durations moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 9 months ago

@cortez.connelly 

To calculate the sum of multiple durations in moment.js, you can use the moment.duration() function to create a duration object for each of the durations you want to sum. Then, you can simply add these duration objects together to get the total sum.


Here's an example of how you can calculate the sum of multiple durations in moment.js:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const moment = require('moment');

// Create duration objects for each of the durations you want to sum
const duration1 = moment.duration({ hours: 1, minutes: 30 });
const duration2 = moment.duration({ hours: 2, minutes: 15 });
const duration3 = moment.duration({ hours: 0, minutes: 45 });

// Add the duration objects together to get the total sum
const totalDuration = moment.duration(duration1 + duration2 + duration3);

// Format the total sum in the desired format
const formattedTotalDuration = moment.utc(totalDuration.as('milliseconds')).format('HH:mm');

console.log(formattedTotalDuration); // Output: 04:30


In this example, we have created three duration objects representing different time periods (1 hour and 30 minutes, 2 hours and 15 minutes, and 45 minutes). We then added these duration objects together to get the total sum, which is 4 hours and 30 minutes. Finally, we formatted the total sum in the HH:mm format to display it as 04:30.