Created
July 24, 2010 17:14
-
-
Save mathiasbynens/488821 to your computer and use it in GitHub Desktop.
Relative date
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just rewrote the whole thing, inspired by (and heavily based on) @cowboy’s fork of this gist. Thanks Ben!