25

Possible Duplicate:
Calculate age in JavaScript

In some point of my JS code I have jquery date object which is person's birth date. I want to calculate person's age based on his birth date.

Can anyone give example code on how to achieve this.

Community
  • 1
  • 1
Aram Gevorgyan
  • 501
  • 1
  • 6
  • 12
  • 2
    Downvoted, as it is [easily searchable](https://duckduckgo.com/?q=get%20age%20from%20birth%20date%20javascript). Can't think how you got that upvote! – halfer Apr 04 '12 at 09:15

3 Answers3

64

Try this function...

function calculate_age(birth_month,birth_day,birth_year)
{
    today_date = new Date();
    today_year = today_date.getFullYear();
    today_month = today_date.getMonth();
    today_day = today_date.getDate();
    age = today_year - birth_year;

    if ( today_month < (birth_month - 1))
    {
        age--;
    }
    if (((birth_month - 1) == today_month) && (today_day < birth_day))
    {
        age--;
    }
    return age;
}

OR

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;
}

[See Demo.][1] [1]: http://jsfiddle.net/mkginfo/LXEHp/7/

James Alvarez
  • 7,159
  • 6
  • 31
  • 46
Ashwini Agarwal
  • 4,828
  • 2
  • 42
  • 59
  • 2
    Very cool! Seeing as how you only have one command in the if (age--;), the brackets are optional, but still pretty good. I'd also combine all the var declarations into one split with commas, but overall, great code, very useful. Thanks mate! – davewoodhall Mar 17 '15 at 03:18
  • Tried the demo and gave date of birth as 01 June 1998 (today is 02 Nov 2016). That means the person 18 years old now. But it shows error message that Age should be greater than or equal to 18. Not accurate thus vote down. – Syed Nov 02 '16 at 11:16
  • very helpfull code – Gurpreet Singh Jan 24 '17 at 09:08
  • how if the ages are taken from axios json array to be use in v-for? – Daddi Al Amoudi Apr 25 '21 at 17:40
38

JsFiddle

You can calculate with Dates.

var birthdate = new Date("1990/1/1");
var cur = new Date();
var diff = cur-birthdate; // This is the difference in milliseconds
var age = Math.floor(diff/31557600000); // Divide by 1000*60*60*24*365.25
Frank van Wijk
  • 3,234
  • 20
  • 41
8
function getAge(birthday) {
    var today = new Date();
    var thisYear = 0;
    if (today.getMonth() < birthday.getMonth()) {
        thisYear = 1;
    } else if ((today.getMonth() == birthday.getMonth()) && today.getDate() < birthday.getDate()) {
        thisYear = 1;
    }
    var age = today.getFullYear() - birthday.getFullYear() - thisYear;
    return age;
}

JSFiddle

fragmentedreality
  • 1,287
  • 9
  • 31