- Pedro : Hi, Maria. How old are you?
- Maria : Pedro, I was born on February 28, 1990.
- Pedro : So, I already know how old you are!
- Maria : What is it?
- Pedro : Just pick up the current year and subtract for the year you were born. Soon, 2014 - 1990 = 24. You are 24 years old.
- Maria : No, actually I'm 23 years old. I do 24 February 28th.
- Maria : To calculate age, you subtract the current year by the year of birth. But if you have not yet passed the anniversary date, you subtract 1.
- Peter : Ah, yeah. I forgot that!
function idade(ano_aniversario, mes_aniversario, dia_aniversario) {
var d = new Date,
ano_atual = d.getFullYear(),
mes_atual = d.getMonth() + 1,
dia_atual = d.getDate(),
ano_aniversario = +ano_aniversario,
mes_aniversario = +mes_aniversario,
dia_aniversario = +dia_aniversario,
quantos_anos = ano_atual - ano_aniversario;
if (mes_atual < mes_aniversario || mes_atual == mes_aniversario && dia_atual < dia_aniversario) {
quantos_anos--;
}
return quantos_anos < 0 ? 0 : quantos_anos;
}
console.log(idade(1980, 12, 11)); // 33
console.log(idade(2011, 2, 15)); // 2
console.log(idade(1993, 31, 5)); // 20