Skip to content

Instantly share code, notes, and snippets.

@brandonaaskov
Created October 31, 2018 15:40
Show Gist options
  • Save brandonaaskov/37a677b28d9e43e10d55370a661144cd to your computer and use it in GitHub Desktop.
Save brandonaaskov/37a677b28d9e43e10d55370a661144cd to your computer and use it in GitHub Desktop.
It's surprisingly often that I need to parse a duration into a time format. Here's the latest I've had to use. And yes, it uses LoDash but this is my gist and I use LoDash all the time.
getDuration (duration) { // duration in ms
const timeString = new Date(duration).toISOString().substr(11, 8)
const time = _.reduce(timeString.split(':'), (result, piece, index) => {
let key
if (index === 0) key = 'hours'
if (index === 1) key = 'minutes'
if (index === 2) key = 'seconds'
result[key] = parseInt(piece, 10)
return result
}, {})
const { hours, minutes, seconds } = time
if (hours > 0) return `${hours}h${minutes}m${seconds}s`
else if (minutes > 0) return `${minutes}m${seconds}s`
else return `${seconds}s`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment