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.

One thought on “Calculate the Age from Date of Birth in JavaScript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s