Created
June 11, 2021 14:41
-
-
Save cmcculloh/8755205d7b2d0dd5f7ebe06c985fae32 to your computer and use it in GitHub Desktop.
Converting a timespan of HH:MM:SS to MS using 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
console.log('qa', (1 * 60 * 60 * 1000) + (40 * 60 * 1000) + (30 * 1000)) | |
const rawTimespan = '01:40:30'; | |
const rawTimespanArray = rawTimespan.split(':').slice(-3); | |
const timespanFromReduce = rawTimespanArray.reduce((timespan, segment, i, rawTimespanArray) => { | |
if (rawTimespanArray.length - 1 === i) { | |
// we are processing the last one (ms), so multiply by 1000 | |
return (parseFloat(segment) + timespan) * 1000; | |
} else { | |
return (parseFloat(segment) + timespan) * 60; | |
} | |
}, 0); | |
console.log('timespanFromReduce', timespanFromReduce); | |
let timespanFromWhile = 0; | |
while(rawTimespanArray.length > 0) { | |
const timechunk = parseFloat(rawTimespanArray.shift()); | |
if (rawTimespanArray.length === 0) { | |
timespanFromWhile = (timechunk + timespanFromWhile) * 1000; | |
} else { | |
timespanFromWhile = (timechunk + timespanFromWhile) * 60; | |
} | |
} | |
console.log('timespanFromWhile', timespanFromWhile); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment