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'; | |
}; |
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
Usage:
Note that I didn’t add support for dates in the future (since I didn’t need it).
The
str
parameter is parsed usingDate.parse
, so it won’t work in IE6 or IE7 without a workaround. It accepts the IETF standard (RFC 1123 Section 5.2.14 and elsewhere) date syntax:"Mon, 25 Dec 1995 13:30:00 GMT"
. It understands the continental US time-zone abbreviations, but for general use, use a time-zone offset, for example,"Mon, 25 Dec 1995 13:30:00 GMT+0430"
(4 hours, 30 minutes east of the Greenwich meridian). If you do not specify a time zone, the local time zone is assumed. GMT and UTC are considered equivalent.Since it can handle dates in
yyyy-mm-dd
format, you can use this with HTML5<time>
elements having adatetime
attribute in that format. Sadly, it won’t work with ISO 8601-formatted dates (e.g.2004-02-12T15:19:21+00:00
) which may also be used for thedatetime
attribute.