Last active
August 26, 2019 18:38
-
-
Save Pustur/9b867bb2934803b4ff2314c0d2e21c79 to your computer and use it in GitHub Desktop.
JavaScript – Convert a timestamp to a string "X days X hours X minutes X seconds X milliseconds". Useful to show elapsed time since [event]
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
function timestampToString(timestamp, useMilliseconds) { | |
const periods = { | |
day: 86400000, | |
hour: 3600000, | |
minute: 60000, | |
second: 1000, | |
millisecond: 1, | |
}; | |
if (!useMilliseconds) { | |
timestamp *= 1000; | |
delete periods.millisecond; | |
} | |
return Object.entries(periods) | |
.reduce((result, [period, value]) => { | |
const num = Math.floor(timestamp / value); | |
const plural = num === 1 ? '' : 's'; | |
const str = `${num} ${period}${plural} `; | |
timestamp -= num * value; | |
return `${result}${num === 0 ? '' : str}`; | |
}, '') | |
.trim(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Outputs: