Skip to content

Instantly share code, notes, and snippets.

@tomasdev
Created January 16, 2012 13:16
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 tomasdev/1620816 to your computer and use it in GitHub Desktop.
Save tomasdev/1620816 to your computer and use it in GitHub Desktop.
date comparison
/**
* Long version
*/
var isLeap = function(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
};
var getAge = function(birthDate) {
var now = new Date(),
age = 0,
// days since the birthdate
days = Math.floor(( now.getTime() - birthDate.getTime() )/1000/60/60/24);
// iterate the years
for (var y = birthDate.getFullYear(), y2 = now.getFullYear(); y <= y2; y++){
var daysInYear = isLeap(y) ? 366 : 365;
if (days >= daysInYear){
days -= daysInYear;
age++;
// increment the age only if there are available enough days for the year.
}
}
return age;
};
// january 1st, 2011
var birth = new Date( 2011, 0, 1 );
if ( getAge(birth) < 21 ) {
console.log('Under age!');
} else {
console.log('Want a beer?');
}
/**
* Short version (doesn't work well)
* @deprecated
*/
var birthStamp = new Date( 2011, 0, 1 ).getTime();
if ( birthStamp < 21*365*86400*1000 ) {
console.log('Under age!');
} else {
console.log('Want a beer?');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment