Duration between HMS
Provides the duration between two HH:MM:SS values.
by MegaScience
HTML
<label for="start">Start Time: </label><input id="start" type="text" pattern="([0-9]{1,2}:[0-9]{2}:[0-9]{2}|[0-9]{1,2}:[0-9]{2}|[0-9]{1,2})" patternOld="([0-9]{1,2}:){1,2}?([0-9]{2})" placeholder="[00:][00:]00" value="00:00:00"/><br />
<label for="end">End Time: </label><input id="end" type="text" pattern="([0-9]{1,2}:[0-9]{2}:[0-9]{2}|[0-9]{1,2}:[0-9]{2}|[0-9]{1,2})" placeholder="[00:][00:]00" value="00:00:00"/><br />
<button id="submit">Submit</button>
<button id="clear">Clear</button>
<p id="durationContainer">Duration: <span id="duration">...</span></p>
CSS
#durationContainer {
user-select: none;
}
#duration {
color: red;
user-select: text;
}
br {
margin-bottom: 5px;
}
input:invalid {
border: red solid 2px;
}
JavaScript
const submit = document.getElementById('submit')
const clear = document.getElementById('clear')
const start = document.getElementById('start')
const end = document.getElementById('end')
const duration = document.getElementById('duration')
function hmsToSeconds(hms) {
//const [hours = 0, minutes = 0, seconds = 0] = hms.trim().split(':')
const [s = 0, m = 0, h = 0] = hms.trim().split(':').reverse()
return (h * 3600) + (m * 60) + (+s)
}
function secondsToHms(s) {
return new Date(1000 * s).toISOString().substr(11, 8)
}
function main() {
submit.addEventListener('click', () => {
const startInSeconds = hmsToSeconds(start.value)
const endInSeconds = hmsToSeconds(end.value)
const timeBetween = Math.abs(startInSeconds - endInSeconds)
duration.innerText = secondsToHms(timeBetween)
})
clear.addEventListener('click', () => duration.innerText = '...')
}
main()