Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JavaScript – Convert a timestamp to a string "X days X hours X minutes X seconds X milliseconds". Useful to show elapsed time since [event]
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();
}
@Pustur

This comment has been minimized.

Copy link
Owner Author

Pustur commented Apr 26, 2016

Outputs:

timestampToString(1);             // 1 second
timestampToString(1, true);       // 1 millisecond

timestampToString(1001);          // 16 minutes 41 seconds
timestampToString(1001, true);    // 1 second 1 millisecond

timestampToString(1492471);       // 17 days 6 hours 34 minutes 31 seconds
timestampToString(1492471, true); // 24 minutes 52 seconds 471 milliseconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.