Santhosh Kumar Santhosh Kumar - 5 months ago 12
Javascript Question

Calculate date from jquery datepicker

I am calculating the age from jquery datepicker. But this works when only the date is in

(mm/dd/yy)
format. I need to get this working in
dd/mm/yy
.

//Code

$('#dob').datepicker({
onSelect: function(value, ui) {
var today = new Date(),
dob = new Date(value),
age = new Date(today - dob).getFullYear() - 1970;

$('#age').text(age);
},
maxDate: '+0d',
yearRange: '1920:2010',
changeMonth: true,
changeYear: true
});


If i try to set
dateFormat: 'mm/dd/yy'
in the property this wont work.
Any help?

K K K K
Answer

Try this: http://jsfiddle.net/lotusgodkk/GCu2D/120/

Js:

$('#dob').datepicker({
onSelect: function(value, ui) {
    console.log(ui.selectedYear)
    var today = new Date(), 
        dob = new Date(value), 
        age = ui.selectedYear - 1970; //This is the update

    $('#age').text(age);
},
maxDate: '+0d',
yearRange: '1920:2010',
changeMonth: true,
changeYear: true,
});

If you inspect the ui object in console, you'll see that it stores year,day,month separately. You can access them like ui.selectedDay or selectedYear . Hope this helps.

Comments