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

Usage:

relativeDate('2010-07-24');
relativeDate('May 24, 1988');
relativeDate('Wed, 09 Aug 1995 00:00:00 GMT');

Note that I didn’t add support for dates in the future (since I didn’t need it).

The str parameter is parsed using Date.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 a datetime 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 the datetime attribute.

window.onload = function() {
 var elems = document.getElementsByTagName('time'),
     i = elems.length;
 while (i--) {
  if (d = elems[i].getAttribute('datetime')) {
   elems[i].innerHTML = relativeDate(d);
  };
 };
};

@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