— Peter: Hi, Maria. How old are you?
— Maria: Pedro, I was born on February 28, 1990.
— Peter: So I know how old you are!
— Maria: What is?
— Peter: Just take the current year and subtract by the year you were born. Soon, 2014 - 1990 = 24. You are 24 years old.
— Maria: No, actually I am 23 years old. I do 24 day 28 February.
— Maria: To calculate age, you subtract the current year by the year of birth. But if you have not yet passed the birthday date, you subtract 1.
— Peter: Ah, yeah. I forgot that detail!
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
This narration was very intuitive and easy to learn, congratulations. : ) Answers like this should be thankful, thanks.
– Marconi