Add two or more string time values (hh:mm:ss) with JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Add two or more string time values (hh:mm:ss) with JavaScript | |
| * | |
| * Usage: | |
| * > addTimes(['04:20:10', '21:15:10']); | |
| * > "25:35:20" | |
| * > addTimes(['04:35:10', '21:35:10']); | |
| * > "26:10:20" | |
| * > addTimes(['30:59', '17:10']); | |
| * > "48:09:00" | |
| * > addTimes(['19:30:00', '00:30:00']); | |
| * > "20:00:00" | |
| * | |
| * @param {String[]} times Array of time strings to be added | |
| * @returns {String} the total time | |
| */ | |
| function addTimes(times) { | |
| let totalHours = 0 | |
| let totalMinutes = 0 | |
| let totalSeconds = 0 | |
| for (const time of times) { | |
| const splitTime = (time || '').split(':') | |
| totalHours += isNaN(parseInt(splitTime[0])) ? 0 : parseInt(splitTime[0]) | |
| totalMinutes += isNaN(parseInt(splitTime[1])) ? 0 : parseInt(splitTime[1]) | |
| totalSeconds += isNaN(parseInt(splitTime[2])) ? 0 : parseInt(splitTime[2]) | |
| } | |
| if (totalSeconds >= 60) { | |
| const minutesFromSeconds = (totalSeconds / 60) << 0 | |
| totalMinutes += minutesFromSeconds | |
| totalSeconds -= 60 * minutesFromSeconds | |
| } | |
| if (totalMinutes >= 60) { | |
| const hoursFromMinutes = (totalMinutes / 60) << 0 | |
| totalHours += hoursFromMinutes | |
| totalMinutes -= 60 * hoursFromMinutes | |
| } | |
| // Uncomment lines below to 'restart' | |
| // from 23:59:59 to 00:00:00 instead of going to 24:00:00 and up | |
| /* | |
| const totalTimeInSeconds = totalSeconds + totalMinutes * 60 + totalHours * 60 * 60; | |
| // source: https://stackoverflow.com/questions/1322732/convert-seconds-to-hh-mm-ss-with-javascript#comment57297644_25279340 | |
| return new Date(totalTimeInSeconds * 1000).toISOString().substr(11, 8) | |
| */ | |
| /** | |
| * Convert a time part ('hh', 'mm' or 'ss') from an integer to a string | |
| * | |
| * @param {Number} time the number to convert to a time string | |
| * @returns {String} the time as as string, padded with zeros | |
| */ | |
| const timeToString = time => time.toString().padStart(2, '0') | |
| return `${timeToString(totalHours)}:${timeToString(totalMinutes)}:${timeToString(totalSeconds)}` | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment