Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Display date difference from timestamp, "that much time ago" like.
function timeAgo(time) {
'use strict';
var second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24,
month = day * 30,
year = day * 365,
elapsed = Date.now() - time,
getString = function (value, unit) {
value = Math.round(elapsed / value);
return value + ' ' + unit + (value === 1 ? ' ago' : 's ago');
};
if (elapsed < minute) {
return getString(second, 'second');
} else if (elapsed < hour) {
return getString(minute, 'minute');
} else if (elapsed < day ) {
return getString(hour , 'hour');
} else if (elapsed < month) {
return getString(day, 'day');
} else if (elapsed < year) {
return getString(month, 'month');
} else {
return getString(year, 'year');
}
}
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.