Created
October 31, 2018 15:40
-
-
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.
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
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