Skip to content

Instantly share code, notes, and snippets.

@cmcculloh
Created June 11, 2021 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmcculloh/8755205d7b2d0dd5f7ebe06c985fae32 to your computer and use it in GitHub Desktop.
Save cmcculloh/8755205d7b2d0dd5f7ebe06c985fae32 to your computer and use it in GitHub Desktop.
Converting a timespan of HH:MM:SS to MS using Javascript
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