Skip to content

Instantly share code, notes, and snippets.

@twfarland
Last active August 29, 2015 13:56
Show Gist options
  • Save twfarland/9064285 to your computer and use it in GitHub Desktop.
Save twfarland/9064285 to your computer and use it in GitHub Desktop.
Relative date function
// Returns a text description of a past time relative to now, e.g: 1 minute ago, 3 hours ago, 2 years ago.
var intervals = [['year', 31556926], ['month', 2629744], ['week', 604800], ['day', 86400], ['hour', 3600], ['minute', 60], ['second', 1]];
// time is in seconds
function textDate (time) {
var diff = new Date().valueOf() * 1000 - time, i, v, n;
for (i = 0; i < intervals.length; i++) {
v = intervals[i];
if (diff > v[1]) {
n = Math.floor(diff / v[1]);
return n + ' ' + v[0] + ((n === 1) ? '' : 's') + ' ago';
}
}
return 'Just now';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment