Skip to content

Instantly share code, notes, and snippets.

@sgreenfield
Created September 18, 2013 00:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgreenfield/6602864 to your computer and use it in GitHub Desktop.
Save sgreenfield/6602864 to your computer and use it in GitHub Desktop.
Date.prototype.toRelativeTime = function(date) {
var delta = date - this, units, conversions;
conversions = {
millisecond: 1, // ms -> ms
second: 1000, // ms -> sec
minute: 60, // sec -> min
hour: 60, // min -> hour
day: 24, // hour -> day
month: 30, // day -> month (roughly)
year: 12 // month -> year
};
for (var key in conversions) {
if (delta < conversions[key]) {
break;
} else {
units = key;
delta = delta / conversions[key];
}
}
if (units === 'second') return 'less than a minute';
delta = Math.floor(delta);
if (delta !== 1) { units += "s"; }
return [delta, units].join(" ");
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment