Skip to content

Instantly share code, notes, and snippets.

@caiquecastro
Created March 9, 2015 18:17
Show Gist options
  • Save caiquecastro/fb53c5551c3719ffad2d to your computer and use it in GitHub Desktop.
Save caiquecastro/fb53c5551c3719ffad2d to your computer and use it in GitHub Desktop.
Calculate age
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