Skip to content

Instantly share code, notes, and snippets.

@Pustur
Last active August 26, 2019 18:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pustur/9b867bb2934803b4ff2314c0d2e21c79 to your computer and use it in GitHub Desktop.
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]
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
Copy link
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