Skip to content

Instantly share code, notes, and snippets.

@cowboy
Forked from mathiasbynens/relative-date.js
Created July 24, 2010 17:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cowboy/488837 to your computer and use it in GitHub Desktop.
Save cowboy/488837 to your computer and use it in GitHub Desktop.
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;
function approx(num) {
return num < 5 ? 'a few' : Math.round(num);
};
return s <= 1 ? 'just now'
: m < 1 ? approx(s) + ' seconds ago'
: m <= 1 ? 'a minute ago'
: h < 1 ? approx(m) + ' minutes ago'
: h <= 1 ? 'an hour ago'
: d < 1 ? approx(h) + ' hours ago'
: d <= 1 ? 'yesterday'
: w < 1 ? approx(d) + ' days ago'
: w <= 1 ? 'last week'
: M < 1 ? approx(w) + ' weeks ago'
: M <= 1 ? 'last month'
: y < 1 ? approx(M) + ' months ago'
: y <= 1 ? 'a year ago'
: approx(y) + ' years ago';
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment