Skip to content

Instantly share code, notes, and snippets.

@Pustur
Last active August 26, 2019 18:38
Show Gist options
  • Select an option

  • Save Pustur/9b867bb2934803b4ff2314c0d2e21c79 to your computer and use it in GitHub Desktop.

Select an option

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 timestamp2string(timestamp, useMilliseconds) {
var string = '',
periods = {
day: 86400000,
hour: 3600000,
minute: 60000,
second: 1000,
millisecond: 1
},
period;
if (!useMilliseconds) {
timestamp *= 1000;
delete periods.millisecond;
}
for (period in periods) {
var number = Math.floor(timestamp / periods[period]);
timestamp -= (number * periods[period]);
string += (number !== 0 ? number + ' ' + period + ((number !== 1) ? 's' : '') + ' ' : '');
}
return string.trim();
}
@Pustur
Copy link
Copy Markdown
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