Get current age when datepicker change 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 use this code to get the current age when changing the datepicker value.

I'm just confused about what 1970 means in this age = new Date(today - dob).getFullYear() - 1970; . Do I need to change it to make it dynamic?

+5
source share
2 answers

Subtraction of 1970 is required because when providing an integer value to the Date() constructor (as is the case with new Date(today - dob) ) it is assumed that you specify the number of milliseconds since the era of January 1, 1970.

Therefore, you need to subtract 1970 from the year value of the date obtained from the DoB calculation to get the user's age.

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

+2
source

Your datepicker plugin uses timestamp values ​​that represent seconds from Unix Epoch on January 1, 1970 in UTC. Therefore, you must calculate the years than to subtract the initial year.

So, the answer: No, you do not need to change anything, the age that you get is already dynamic.

+1
source

All Articles