Created
October 6, 2012 09:18
-
-
Save robertklep/3844465 to your computer and use it in GitHub Desktop.
Create a humanized age string from a Javascript Date instance
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
Date.prototype.AGE_TABLE = [ | |
[ 60, 'second' , 'seconds' ], | |
[ 3600, 'minute' , 'minutes' ], | |
[ 86400, 'hour' , 'hours' ], | |
[ 604800, 'day' , 'days' ], | |
[ 2628030, 'week' , 'weeks' ], | |
[ 31557600, 'month' , 'months' ], | |
[ 4294967295, 'year' , 'years' ] | |
]; | |
Date.prototype.age = function() { | |
// determine age in seconds | |
var seconds = (new Date() - this) / 1000.0; | |
// future time? | |
var future = seconds < 0; | |
// convert to absolute | |
seconds = Math.abs(seconds); | |
// walk through age table | |
var suffix = ''; | |
var divider = 1; | |
for (var i = 0; i < this.AGE_TABLE.length; i++) | |
{ | |
var secs = this.AGE_TABLE[i][0]; | |
var singular = this.AGE_TABLE[i][1]; | |
var plural = this.AGE_TABLE[i][2]; | |
if (seconds < secs) | |
{ | |
seconds /= divider; | |
suffix = (parseInt(seconds) > 1) ? plural : singular; | |
break; | |
} | |
divider = secs; | |
}; | |
return (future ? 'in ' : '') + 'about ' + parseInt(seconds) + ' ' + suff | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment