Skip to content

Instantly share code, notes, and snippets.

@jwebcat
Forked from joseluisq/add_two_times.js
Last active November 5, 2017 11:32
Show Gist options
  • Save jwebcat/b68101bd0c17acc913b8b3fd411f57c4 to your computer and use it in GitHub Desktop.
Save jwebcat/b68101bd0c17acc913b8b3fd411f57c4 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) {
res = minutes / 60;
hours += res;
minutes = minutes - (60 * res);
}
return hours + ':' + minutes + ':' + seconds;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment