Skip to content

Instantly share code, notes, and snippets.

@hoangsetup
Created August 11, 2016 02:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hoangsetup/e2f0bd914f4d1fcb18d3fe22c6cc03b5 to your computer and use it in GitHub Desktop.
Save hoangsetup/e2f0bd914f4d1fcb18d3fe22c6cc03b5 to your computer and use it in GitHub Desktop.
Milliseconds to human string. ex: 2 days ago.
function millisecondsToStr(milliseconds) {
// TIP: to find current time in milliseconds, use:
// var current_time_milliseconds = new Date().getTime();
function numberEnding(number) {
return (number > 1) ? 's' : '';
}
var temp = Math.floor((Date.now() - milliseconds) / 1000);
var years = Math.floor(temp / 31536000);
if (years) {
return years + ' year' + numberEnding(years);
}
//TODO: Months! Maybe weeks?
var days = Math.floor((temp %= 31536000) / 86400);
if (days) {
return days + ' day' + numberEnding(days);
}
var hours = Math.floor((temp %= 86400) / 3600);
if (hours) {
return hours + ' hour' + numberEnding(hours);
}
var minutes = Math.floor((temp %= 3600) / 60);
if (minutes) {
return minutes + ' minute' + numberEnding(minutes);
}
var seconds = temp % 60;
if (seconds) {
return seconds + ' second' + numberEnding(seconds);
}
return 'less than a second'; //'just now' //or other string you like;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment