Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get current age when datepicker change jquery

Tags:

jquery

$('#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
});

I am using this code to get the current age when datepicker change value.

I am just confused what 1970 stands for in this age = new Date(today - dob).getFullYear() - 1970; do i need to change it to make it dynamic?

like image 967
Brownman Revival Avatar asked Oct 18 '22 02:10

Brownman Revival


1 Answers

The subtraction of 1970 is required because when providing an integer value to the Date() constructor (as is the case for new Date(today - dob)) it is assumed that you are providing the number of milliseconds since the January 1st 1970 epoch.

Therefore you need to subtract 1970 from the year value of the date resulting from the DoB calculation to get the age of the user.

Your code is completely correct. You will never need to change the calculation.

like image 134
Rory McCrossan Avatar answered Nov 15 '22 13:11

Rory McCrossan