Skip to content

Instantly share code, notes, and snippets.

@markhker
Forked from joseluisq/add_two_times.js
Created November 9, 2017 22:42
Show Gist options
  • Save markhker/33868633a18d5bf3f8561aac5daf906f to your computer and use it in GitHub Desktop.
Save markhker/33868633a18d5bf3f8561aac5daf906f to your computer and use it in GitHub Desktop.
Sum two times values HH:mm:ss with javascript
/**
* Sum two times values HH:mm:ss with javascript
* Usage:
* > addTimes('04:20:10', '21:15:10');
* > "25:35:20"
*
* @param {string} start
* @param {string} end
* @returns {String}
*/
function addTimes(start, end) {
times = [];
times1 = start.split(':');
times2 = end.split(':');
for (var i = 0; i < 3; i++) {
times1[i] = (isNaN(parseInt(times1[i]))) ? 0 : parseInt(times1[i])
times2[i] = (isNaN(parseInt(times2[i]))) ? 0 : parseInt(times2[i])
times[i] = times1[i] + times2[i];
}
var seconds = times[2];
var minutes = times[1];
var hours = times[0];
if (seconds % 60 === 0) {
hours += seconds / 60;
}
if (minutes % 60 === 0) {
res = minutes / 60;
hours += res;
minutes = minutes - (60 * res);
}
return hours + ':' + minutes + ':' + seconds;
}
@markhker
Copy link
Author

markhker commented Nov 9, 2017

There is a bug, if you try something like
addTimes('04:35:10', '21:35:10');
you've got 25:70:20

I fix it like it (from 30 line)

res = (minutes / 60) | 0;
hours += res;
minutes = minutes - (60 * res);

And if you need zero when minutes less then 10, like in my case
('0' + minutes).slice(-2);

@francisco-solis99
Copy link

francisco-solis99 commented Dec 13, 2023

Another way 🚀:

`
function addTimes(start, end) {
let totalSeconds = 0;
const times = [start, end]

for(const time of times) {
const [hours, minutes, seconds] = time.split(':').map(Number);
totalSeconds += (hours * 3600) + (minutes * 60) + seconds;
}

const hours = Math.floor(totalSeconds / 3600).toString().padStart(2, '0')
const minutes = Math.floor((totalSeconds % 3600) / 60).toString().padStart(2, '')
const seconds = (totalSeconds % 60).toString().padStart(0,'2');

return ${hours}:${minutes}:${seconds};
}
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment