Reputation: 1829
Suppose, I've an array of different time string.
let a: any = ["7:20", "5:50", "6:30"];
I want to sum up these HH:mm time strings. I am building up an app using Ionic 4 (Angular). I have already used momentjs for these. But, unfortunately yet I can't find any solution.
Update: Expected Result: 7:20 + 5:50 + 6:30 = 19:40 (HH:33)
Upvotes: 8
Views: 3971
Reputation: 147363
A POJS solution can be very simple:
/* Add array of time strings in H:mm format
** @param {Array<string>} timeArray - Array of H:mm
** @returns {string} - sum of times in H:mm format
*/
function addTimes(timeArray) {
let mins = timeArray.reduce((acc, time) => {
let [h, m] = time.split(':');
acc += h*60 + m*1;
return acc;
}, 0);
return (mins/60|0) + ':' + ('0'+(mins%60)).slice(-2);
}
// Example
console.log(addTimes(["7:20", "5:03", "6:42"]));
Upvotes: 3
Reputation: 7665
You can treat time as moment durations that can be summed up:
const any = ['7:20', '7:52', '5:03', '1:01', '9:02', '6:00'];
const sum = any.reduce((acc, time) => acc.add(moment.duration(time)), moment.duration());
console.log([Math.floor(sum.asHours()), sum.minutes()].join(':'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
Upvotes: 9
Reputation: 15821
Vanilla Javascript implementation:
const secondsToHm = s => ({
hours: ((s - s % 3600) / 3600) % 60,
minutes: ((s - s % 60) / 60) % 60,
})
let a = ["7:20", "5:50", "6:30"];
let total = 0;
for(let i = 0; i < a.length; i++){
const aSlice = a[i].split(':');
const aSeconds = (+aSlice[0]) * 60 * 60 + (+aSlice[1]) * 60;
total += aSeconds
}
console.log(`${secondsToHm(total).hours}:${secondsToHm(total).minutes}`);
Upvotes: 2
Reputation: 48357
You could use reduce
method by passing a callback function.
let arr= ["7:20", "5:50", "6:30"];
toSeconds = (str) => {
str = str.split(':');
return (+str[0]) * 60 + (+str[1]);
}
toHHss = (seconds) => {
let minutes = parseInt(seconds/60);
seconds = seconds - minutes*60;
return minutes + ':' + seconds;
}
let result = arr.reduce((r,elem) => r + toSeconds(elem), 0);
console.log(toHHss(result));
Upvotes: 3
Reputation: 2419
You can use moment.duration() to get the number of milliseconds for each time string in the array, and add them.
a.reduce((acc, t) => acc.add(moment.duration(t)), moment.duration())
Upvotes: 0