Skip to content

Instantly share code, notes, and snippets.

@SergeyKozlov
Forked from danielgwood/gist:1510463
Created September 24, 2018 04:59
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 SergeyKozlov/ffdcf821c7908d15ef1c6d7316ed9317 to your computer and use it in GitHub Desktop.
Save SergeyKozlov/ffdcf821c7908d15ef1c6d7316ed9317 to your computer and use it in GitHub Desktop.
Human formatted time between dates (JavaScript)
/**
* Given two dates (or one date and assume "now" for the second), convert this to
* a human-readable string, like "2 months".
*
* I use this to put "3 months ago" strings into plugins. My use case has the date
* coming in as a seconds-only UNIX epoch, so the params are expected at this.
*
* @param time1 integer Number of seconds since UNIX epoch
* @param time2 integer Number of seconds since UNIX epoch
* @return string
*/
function(time1, time2) {
// Check/sanitise vars
time1 = Math.max(0, parseInt(time1));
if(typeof time2 == "undefined") {
var now = new Date();
time2 = Math.floor(now.getTime() / 1000);
}
var period = Math.abs(time1 - time2);
var timespan = 1;
var format = 'seconds';
if (period > 31556926) {
// More than one year
format = 'years';
timespan = Math.floor(period / 31556926);
}
else if (period > 2629744) {
// More than one month
format = 'months';
timespan = Math.floor(period / 2629744);
}
else if (period > 604800) {
// More than one week
format = 'weeks';
timespan = Math.floor(period / 604800);
}
else if (period > 86400) {
// More than one day
format = 'days';
timespan = Math.floor(period / 86400);
}
else if (period > 3600) {
// More than one hour
format = 'hours';
timespan = Math.floor(period / 3600);
}
else if (period > 60) {
// More than one minute
format = 'minutes';
timespan = Math.floor(period / 60);
}
// Remove the s
if(timespan == 1) {
format = substr(format, 0, -1);
}
return timespan + ' ' + format;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment