Calculate age in years using javascript

2

How to calculate age from an input type="text" using javascript? I have the input:

<input style="width: 100%" type="text" readonly id="data_nascimento"/>

How to do this calculation? The date format is "01/01/2015."

Do I need to convert to Object Date? How to perform this procedure from the content of the input?

    
asked by anonymous 21.10.2015 / 19:03

4 answers

7

Using only Javascript, you can use this function:

function calcularIdade(aniversario) {
    var nascimento = aniversario.split("/");
    var dataNascimento = new Date(parseInt(nascimento[2], 10),
    parseInt(nascimento[1], 10) - 1,
    parseInt(nascimento[0], 10));

    var diferenca = Date.now() -  dataNascimento.getTime();
    var idade = new Date(diferenca);

    return Math.abs(idade.getUTCFullYear() - 1970);
}

Fiddle: link

    
21.10.2015 / 19:34
1

If you can use the momentjs, it will be simpler to do this calculation. See in this link :

var birthDay = "1984-10-22";
var age = Math.floor(moment(new Date()).diff(moment(birthDay),'years',true));
console.log(age);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
    
21.10.2015 / 19:32
1

Check this function. I think you do what you want. I'm not sure about the date format.

function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}

No input you put:

<input style="width: 100%" type="text" readonly id="data_nascimento"
    onBlur="getAge(this.value)" />
    
21.10.2015 / 19:26
1
function idade(d1, d2){
    d2 = d2 || new Date();
    var diff = d2.getTime() - d1.getTime();
    return Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
}
console.log( idade(new Date(1998, 09, 3)) );

JsFiddle

    
25.10.2015 / 15:40