Calculate age in years on date select from jquery datepicker

user2541120 picture user2541120 · Jul 29, 2013 · Viewed 22k times · Source

I would like to calculate the age of the user as soon as he selects a date from jquery datepicker.

$(document).ready(function() {
  $( "#nominee_one_dob" ).datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: 'yy-mm-dd',

    onSelect: function (date) {
        var dob = Date.parse(date);
        if (dob.addYears(18) < Date.today())
        {
            alert("Under 18");
        }
        else
        {
            alert(" Over 18");
        }
    }

  });

I am able to get the date selected when i alert(date) but I am not getting anything from the further code.

Please help.

Answer

Praveen picture Praveen · Jul 29, 2013

Bugs in your code:

(1)

var dob = Date.parse(date);  //return in milliseconds 

therefore you can't extract year using dob.getFullYear()

(2)

Date.today()  //Nope. not available

no method available.

Fixes:

(1) var dob = new Date(date);

no need to parse, datepicker returns the date not string.

(2) var today = new Date(); //returns current dateTime

(3) use .getFullYear() to extract year from Date.

Remaining code:

$(document).ready(function() {
  $( "#nominee_one_dob" ).datepicker({
    changeMonth: true,
    changeYear: true,
    dateFormat: 'yy-mm-dd',

    onSelect: function (date) {
         var dob = new Date(date);
         var today = new Date();

        if (dob.getFullYear() + 18 < today.getFullYear())
        {
            alert("Under 18");
        }
        else
        {
            alert(" Over 18");
        }
    }

  });
});

Working JSFiddle