Home > Javascript, Jquery > Age Calculation from Date of Birth Using Javascript/Jquery

Age Calculation from Date of Birth Using Javascript/Jquery


Many times we want to allow users to enter site only if they are of 18 years of age, or while registering we ask DOB and we need to calculate their age if they are eligible or not. Here is the javascript function to calculate age based on DOB.

Method 1:

<script type="text/javascript">
	function CalAge() {

    var now = new Date();
    var mm = document.getElementById('ddlmnths').value;
    var ddr = document.getElementById('ddldays');
    var dd = ddr.options[ddr.selectedIndex].value;
    var yy = document.getElementById('ddlyrs').value;
    bDay = dd + "/" + mm + "/" + yy;
    bD = bDay.split('/');
   	    if (bD.length == 3) {
        	   born = new Date(bD[2], bD[1] * 1 - 1, bD[0]);
                 years = Math.floor((now.getTime() - born.getTime()) / (365.25 * 24 * 60 * 60 * 1000));
        if (years < 18) {
            alert(“You are not eligible”);

        }
        else if (years = 18 || years > 18) {
        	alert(“Welcome”);
        }
    }
}
</script>

Method 2 :

<script type="text/javascript">

     function CalAge() {
     var dd = $("#ddldays").val();
     var mm = $("#ddlmnths").val();
     var yy = $("#ddlyrs").val();
     var age = 18;

     var mydate = new Date();
     mydate.setFullYear(yy, mm-1, dd);

     var currdate = new Date();
     currdate.setFullYear(currdate.getFullYear() - age);
     if ((currdate - mydate) < 0){
     alert(“You are not eligible”);
     }
     else
    {
	alert(“Welcome”);
    }
   }
</script>
About these ads
  1. ammu
    September 22, 2011 at 11:07 am

    nice….

  2. June 2, 2012 at 4:09 am

    helpful info

  3. April 6, 2013 at 4:59 pm

    Its such as you learn my thoughts! You seem to grasp
    a lot approximately this, like you wrote the ebook in it or something.
    I believe that you just can do with some % to pressure the message house a little bit, however other than that, that is wonderful blog. An excellent read. I will certainly be back.

  1. No trackbacks yet.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: