Skip to content

Instantly share code, notes, and snippets.

@nesquena
Created April 23, 2009 02:09
Show Gist options
  • Save nesquena/100239 to your computer and use it in GitHub Desktop.
Save nesquena/100239 to your computer and use it in GitHub Desktop.
// Looks like "Updated " + date.toRelativeString() + " ago"
Date.prototype.toRelativeString = function(){
var now = new Date;
var later = this;
var offset = later.getTime() - now.getTime();
var distanceInMinutes = (offset.abs() / 60000).round();
if (distanceInMinutes == 0) { return 'a few seconds'; }
else if ($R(0,1).include(distanceInMinutes)) { return 'a minute'; }
else if ($R(2,44).include(distanceInMinutes)) { return distanceInMinutes + ' minutes';}
else if ($R(45,89).include(distanceInMinutes)) { return '1 hour';}
else if ($R(90,1439).include(distanceInMinutes)) { return 'about ' + (distanceInMinutes / 60).round() + ' hours'; }
else if ($R(1440,2879).include(distanceInMinutes)) {return '1 day'; }
else if ($R(2880,43199).include(distanceInMinutes)) {return 'about ' + (distanceInMinutes / 1440).round() + ' days'; }
else if ($R( 43200,86399).include(distanceInMinutes)) { return 'a month'; }
else if ($R(86400,525599).include(distanceInMinutes)) {return (distanceInMinutes / 43200).round() + ' months'; }
else if ($R(525600,1051199).include(distanceInMinutes)) {return 'a year';}
else return 'over ' + (distanceInMinutes / 525600).round() + ' years';
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment