Created
January 16, 2012 13:16
-
-
Save tomasdev/1620816 to your computer and use it in GitHub Desktop.
date comparison
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
/** | |
* 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