Skip to content

Instantly share code, notes, and snippets.

@mholtzhausen
Last active February 23, 2021 13:48
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 mholtzhausen/f380f9cfbc06e917c0ccffa238ea86a2 to your computer and use it in GitHub Desktop.
Save mholtzhausen/f380f9cfbc06e917c0ccffa238ea86a2 to your computer and use it in GitHub Desktop.
Timespan to Milliseconds
const timespanToMs=(timeSpan)=>{
let lut={'':1, ms:1, s:1000, m:60000, h:3600000, d: 86400000, w:604800000, y:31556952000 }
let ms=(`${timeSpan}`.match(/\d+[ywdhms]{0,2}\s?/g)).reduce((a,s)=>{
let [,v,m] =s.match(/(\d+)([ywdhms]{0,2})/)
return a + (v * lut[m])
},0)
return ms
}
let passTests=[
timespanToMs('22s') === 22000,
timespanToMs('22d') === 1900800000,
timespanToMs(' 1y 4d 22s') === 31902574000
].filter(test=>test===false).length===0
console.log(passTests ? 'Passed all tests':'Something croaked')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment