Created
March 9, 2015 18:17
-
-
Save caiquecastro/fb53c5551c3719ffad2d to your computer and use it in GitHub Desktop.
Calculate age
This file contains hidden or 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
function calcAge(birth_date) { | |
var today = new Date; | |
var age = { | |
years: 0, | |
months: 0 | |
}; | |
age.years = today.getFullYear() - birth_date.getFullYear(); | |
if (today.getMonth() < birth_date.getMonth() || today.getMonth() == birth_date.getMonth() && today.getDate() < birth_date.getDate()) { | |
age.years--; | |
} | |
age.months = today.getMonth() - birth_date.getMonth(); | |
if(today.getDate() < birth_date.getDate()) { | |
age.months--; | |
} | |
if(age.months < 0) { | |
age.months += 12; | |
} | |
if(age.years < 0 || age.months < 0) return null; | |
return age; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment