'how to Calculate sum of multiple durations moment-js?
I am tryng to calculate w total working hours of each user what I did is getting the duration of each day, now I want to calculate the total working hours Given this input
durations:[ '0:30:00', '0:30:00', '0:30:00', '1:00:00' ] being respectively half an hour each and the last element being one hour ,
now I want to be able to sum all of these duration to get the total working hours
Here's what I managed to do to get the duration I am open to all of your suggestions to improve my already existing code and get my wanted result which is totalHours=HH:mm:ss
let startTime = moment(book.startTime, 'hh:mm:ss');
let endTime = moment(book.endTime, 'hh:mm:ss');
let totalSec = endTime.diff(startTime, 'seconds');
var durations = moment()
.startOf('day')
.seconds(totalSec)
.format('H:mm:ss');
result.push(durations);
Solution 1:[1]
- Convert each duration to miliseconds
- Get the sum of those miliseconds
- Create moment object to format to hms
const durations = [ '0:30:00', '0:30:00', '0:30:00', '1:00:00' ];
const ms = durations.map(d => moment.duration(d).asSeconds() * 1000);
const sum = ms.reduce((prev, cur) => prev + cur, 0);
const hms = moment.utc(sum).format("HH:mm:ss");
console.log('HMS: ' + hms);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.32/moment-timezone-with-data.min.js"></script>
HMS: 02:30:00
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | 0stone0 |
