Saturday, 19 September 2020

Calculate the Age from Date of Birth in JavaScript

Hi Everyone,

Today I have got an requirement to calculate the Age based on Date of Birth.

Here is the way to get the Age using JavaScript.

function getAge(dateString) {
    // var dateString = '12/02/1988'
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    console.log(today.getMonth())
    console.log(birthDate.getMonth())
    console.log(m);
    // Logically we cannot include the current year if the birthday has not completed in the current year.
    // The below condition checks the same and removes the current year from Age.
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;

}

Hope this helps.

--
Happy Coding
Gopinath.

No comments:

Post a Comment