$('#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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With