Skip to content

Instantly share code, notes, and snippets.

@mathiasbynens
Created July 24, 2010 17:14
Show Gist options
  • Save mathiasbynens/488821 to your computer and use it in GitHub Desktop.
Save mathiasbynens/488821 to your computer and use it in GitHub Desktop.
Relative date
function relativeDate(str) {
var s = (+new Date() - Date.parse(str)) / 1e3,
m = s / 60,
h = m / 60,
d = h / 24,
w = d / 7,
y = d / 365.242199,
M = y * 12,
R = Math.round;
return s <= 5 ? 'just now'
: m < 1 ? R(s) + ' seconds ago'
: R(m) <= 1 ? 'a minute ago'
: h < 1 ? R(m) + ' minutes ago'
: R(h) <= 1 ? 'an hour ago'
: d < 1 ? R(h) + ' hours ago'
: R(d) <= 1 ? 'yesterday'
: w < 1 ? R(d) + ' days ago'
: R(w) <= 1 ? 'a week ago'
: M < 1 ? R(w) + ' weeks ago'
: R(M) <= 1 ? 'a month ago'
: y < 1 ? R(M) + ' months ago'
: R(y) <= 1 ? 'a year ago'
: R(y) + ' years ago';
};
@mathiasbynens
Copy link
Author

Just rewrote the whole thing, inspired by (and heavily based on) @cowboy’s fork of this gist. Thanks Ben!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment