RMTWeb

View Original

JQuery - Calculate age from DOB

So a user has entered their date of birth in a text box and you want to calculate their age, and take in to account leap years. Create a JQuery function (this code):

function calculateAge(dob){var now = new Date();function isLeap(year){return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);}var days = Math.floor((now.getTime() - dob.getTime())/1000/60/60/24);var age = 0;for (var y = dob.getFullYear(); y <= now.getFullYear(); y++){           var daysInYear = isLeap(y) ? 366 : 365;if (days >= daysInYear){days -= daysInYear;age++;}}return age;}

Then, we need to run this when the text box (txtDateOfBirth) is changed (on blur), and in this example are going to put the age into another text box (txtAgeTextBox)

$('#txtDateOfBirth').blur(function(){     $("#txtAgeTextBox").val(calculateAge($.datepicker.parseDate('dd/mm/yy', $('#txtDateOfBirth').val()))});