How to calculate the age of a person with JS, from the date of birth?

Asked

Viewed 32,771 times

32

How can I calculate a person’s age in Javascript from the date of birth?

I tried something like:

function idade(dia, mes, ano) {
   return new Date().getFullYear() - ano;
}

idade(11, 12, 1980); //  33
idade(15, 2, 2011);  // 2
idade(5, 31, 1993);  // 20

5 answers

46


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
  • 1

    This narration was very intuitive and easy to learn, congratulations. : ) Answers like this should be thankful, thanks.

17

I suggest comparing the month and the day of the month: if today’s date is greater than or equal to that of birth (i.e. the birthday has passed), then it is enough to make the difference between the years. Otherwise, make a difference and subtract 1:

function idade(nascimento, hoje) {
    var diferencaAnos = hoje.getFullYear() - nascimento.getFullYear();
    if ( new Date(hoje.getFullYear(), hoje.getMonth(), hoje.getDate()) < 
         new Date(hoje.getFullYear(), nascimento.getMonth(), nascimento.getDate()) )
        diferencaAnos--;
    return diferencaAnos;
}

Example in jsFiddle.

8

A one-line solution, calculating from the number of days:

// calcula a idade considerando os parâmetros 
// 'nascimento' e 'hoje' como objetos Date
function calculaIdade(nascimento, hoje){
    return Math.floor(Math.ceil(Math.abs(nascimento.getTime() - hoje.getTime()) / (1000 * 3600 * 24)) / 365.25);
}

The logic used is as follows::

  • Math.abs(nascimento.getTime() - hoje.getTime()) - returns the amount of milliseconds passed since nascimento until hoje. The function Math.abs returns the module of subtraction, that is, transforms a negative number into positive and maintains the signal of a positive.
  • / (1000 * 3600 * 24) - calculates the number of days from the amount of milliseconds returned in the previous expression. Dividing by 1000, we have the number of seconds; the number of seconds dividing by 3600 we have the number of hours (because in 1 hour it fits 3600 seconds); and finally we divide the amount of hours by 24, we will have the corresponding amount of days.
  • Math.ceil - round up the decimal value of the previous operation, as it is considered that a day has passed even if the amount of hours does not give 24 hours. As for example a baby born last night, we consider that by this morning already has 1 day of life.
  • / 365.25 - finally, we calculate the year by dividing the total of days by the total of days that fit into a year. The number 365.25 is because a year has approximately 365 days and 6 hours, which is equal to 365.25 days. The bixesto year comes from this difference, because every 4 years, the 6 hours disregarded in the calendar become 24 hours, ie another day.
  • Math.floor - round down the amount of years. Yeah, no matter if the person is birthday tomorrow and is 25,999 years old, she is 25 years old.
  • 1

    +1 Interesting, your suggestion. I think it would be nice for you to explain a little in your answer how the calculation works (for example, not everyone will understand that the 0.25 extra in the divisor to get the result in years is due to the counting of leap years). A good explanation gives credibility to the answer and potentially helps you gain more positive votes. :)

  • 1

    Added the explanation of the calculation. Grateful for the suggestion.

  • 1

    I believe it is a reasonable approximation, but it will still fail in dates close to the multiple years of 100 (where the rules for leap year change).

8

How about calculating in a much more minimalist way? The calculation with ms is highly superior considered performance. Ex: I was born on 17/12/1995. So:

function calcAge(dateString) {
  var birthday = +new Date(dateString);
  return ~~((Date.now() - birthday) / (31557600000));
}

console.log(calcAge("Thu Dec 17 1995 00:51:54 GMT-0300 (BRT)"));
If the code is executed before the day 17/12/2015. I will still be 19 years :P

The technique used is in: http://jsperf.com/birthday-calculation And I thank Caio Ribeiro for showing me

2

Hello, I adapted the code of @Gabriel S. to accept date in the Brazilian standard.

function calcIdade(data) {
    var d = new Date,
        ano_atual = d.getFullYear(),
        mes_atual = d.getMonth() + 1,
        dia_atual = d.getDate(),
        split = data.split('/'),
        novadata = split[1] + "/" +split[0]+"/"+split[2],
        data_americana = new Date(novadata),
        vAno = data_americana.getFullYear(),
        vMes = data_americana.getMonth() + 1,
        vDia = data_americana.getDate(),
        ano_aniversario = +vAno,
        mes_aniversario = +vMes,
        dia_aniversario = +vDia,
        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;
}
// calcIdade('02/01/1978') => 39
// calcIdade('03/09/1980') => 36

Browser other questions tagged

You are not signed in. Login or sign up in order to post.