Blog Archive

Javascript calculate Age from Birthdate

In our day to day programming we often come across business logic that depends on the age of a person. So in reality we ask for the persons date of birth and then we have to find the age, after that do some type of validation based on that age. Here is an example just to address that need in JavaScript.

Enter Birth Date: (in MM/DD/YYYY format)

<html>
<head>
</head>
<body>

<SCRIPT LANGUAGE="JavaScript1.2"> <!--

function myAgeValidation() {

    var lre = /^\s*/;
    var datemsg = "";
   
    var inputDate = document.as400samplecode.myDate.value;
    inputDate = inputDate.replace(lre, "");
    document.as400samplecode.myDate.value = inputDate;
    datemsg = isValidDate(inputDate);
        if (datemsg != "") {
            alert(datemsg);
            return;
        }
        else {
            //Now find the Age based on the Birth Date
            getAge(new Date(inputDate));
        }

}

function getAge(birth) {

    var today = new Date();
    var nowyear = today.getFullYear();
    var nowmonth = today.getMonth();
    var nowday = today.getDate();

    var birthyear = birth.getFullYear();
    var birthmonth = birth.getMonth();
    var birthday = birth.getDate();

    var age = nowyear - birthyear;
    var age_month = nowmonth - birthmonth;
    var age_day = nowday - birthday;
   
    if(age_month < 0 || (age_month == 0 && age_day <0)) {
            age = parseInt(age) -1;
        }
    alert(age);
   
    if ((age == 18 && age_month <= 0 && age_day <=0) || age < 18) {
    }
    else {
        alert("You have crossed your 18th birthday !");
    }

}

function isValidDate(dateStr) {

   
    var msg = "";
    // Checks for the following valid date formats:
    // MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
    // Also separates date into month, day, and year variables

    // To require a 2 & 4 digit year entry, use this line instead:
    //var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;
    // To require a 4 digit year entry, use this line instead:
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

    var matchArray = dateStr.match(datePat); // is the format ok?
    if (matchArray == null) {
        msg = "Date is not in a valid format.";
        return msg;
    }

    month = matchArray[1]; // parse date into variables
    day = matchArray[3];
    year = matchArray[4];

   
    if (month < 1 || month > 12) { // check month range
        msg = "Month must be between 1 and 12.";
        return msg;
    }

    if (day < 1 || day > 31) {
        msg = "Day must be between 1 and 31.";
        return msg;
    }

    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
        msg = "Month "+month+" doesn't have 31 days!";
        return msg;
    }

    if (month == 2) { // check for february 29th
    var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
    if (day>29 || (day==29 && !isleap)) {
        msg = "February " + year + " doesn't have " + day + " days!";
        return msg;
    }
    }

    if (day.charAt(0) == '0') day= day.charAt(1);
   
    //Incase you need the value in CCYYMMDD format in your server program
    //msg = (parseInt(year,10) * 10000) + (parseInt(month,10) * 100) + parseInt(day,10);
   
    return msg;  // date is valid
}

// --> </SCRIPT>

<form name="as400samplecode">
Enter Birth Date:  <input type="text" name="myDate" size=10 maxlength=10> (in MM/DD/YYYY format)
<input type="button" value="Find Age" onclick="Javascript:myAgeValidation()">
</form>

</body>

</html>

16 comments :

  1. This is cool! I'd like to expand on it. I have very little programming.. anything - and it's from the 80s. How can I get help doing that?

    Thank you,

    Pam Hoffman
    EverydaySpacer.com

    ReplyDelete
    Replies
    1. It doesnt have the validation my dear friend and just it show only the year


      I had post my code hear review it

      Delete
  2. Thank you very much

    ReplyDelete
  3. Hi,

    Very nice!

    I need to know the Code for a date Input: dd.mm.yyyy.

    ReplyDelete
  4. This of course does not work... it doesn't take into account the actual date of your birthday, it's determining your age based on subtracting the year of your birth from the current year. Try your birth year with today's date and it will be right... but try yesterday and it will be wrong.

    ReplyDelete
  5. hi,can you do a js code,like bib's marathon number being generate from the date of birth and full name. eg: Lee Chong Wei (25031994) will be like this LCW25031994?

    ReplyDelete
  6. does not work, try yesterday

    ReplyDelete

  7. function change(){
    setTimeout(function(){
    var dateObj = new Date();
    var month = dateObj.getUTCMonth() + 1; //months from 1-12
    var day = dateObj.getUTCDate();
    var year = dateObj.getUTCFullYear();


    var newdate = year + "/" + month + "/" + day;

    var entered_birthdate = document.getElementById('birth_dates').value;
    var birthdate = new Date(entered_birthdate);
    var birth_year = birthdate.getUTCFullYear();
    var birth_month = birthdate.getUTCMonth() + 1;
    var birth_date = birthdate.getUTCDate();




    var age_year = (year-birth_year);
    var age_month = (month-birth_month);
    var age_date = ((day-birth_date) < 0)?(31+(day-birth_date)):(day-birth_date);

    var test = (birth_year>year)?true:((age_year===0)?((month 1)?age_year:( ((age_year=== 1 )&&(age_month >= 0))?age_year:((age_month < 0)?(age_month+12):((age_month > 1)?age_month: ( ((age_month===1) && (day>birth_date) ) ? age_month:age_date) ) ));


    var ages = ((age===age_date)&&(age!==age_month)&&(age!==age_year))?(age_date+"days"):((((age===age_month+12)||(age===age_month)&&(age!==age_year))?(age+"months"):age_year+"years"));

    document.getElementById("ages").innerHTML = ages;



    }




    }, 30);

    };

    ReplyDelete
  8. that was help full budy

    ReplyDelete
  9. You can do it more accurately with momentjs

    ReplyDelete