This topic is locked
[SOLVED]

 Javascript to calculate age in years, months and days

8/24/2020 2:29:48 PM
PHPRunner General questions
woodey2002 author

Hi Guys,
I have some javascript that calculates a persons age in yeats, months and days from their of dob to the time of admission.
So a user enters a DOB and a date of admission.
The age at admission is then auto calculated.
It work well, however I'm getting some inconsistent values with only the days calculatein of the formula where it seems to add extra days to the day portion only.
For example a person born 01/01/2005 and Admitted 23/08/2020 age calculation reads 15 years 7 months 26 days when the correct value should be 15 years, 7 months, 23 days (including the end date)
Any ideas how to tweak the days portion of JS below?



/// Age from db

var ctrldob = Runner.getControl(pageid, 'dob');

var ctrldoa = Runner.getControl(pageid, 'cc_Start_Date');

var ctrlpatient_age = Runner.getControl(pageid, 'patient_age');
ctrldoa.on('blur', setDateParams);

ctrldob.on('blur', setDateParams);



function setDateParams() {
if(ctrldob.getValue())

{

$('#p_dob').html($('#tsvalue_dob_1').val());

}

if(ctrldoa.getValue() && ctrldob.getValue())

{


var user_date = Date.parse(ctrldob.getValue());

var today_date = Date.parse(ctrldoa.getValue());

var diff_date = today_date -user_date ;

var num_years = diff_date/31536000000;

var num_months = (diff_date % 31536000000)/2628000000;

var num_days = ((diff_date % 31536000000) % 2628000000)/86400000;

var agestr = Math.floor(num_years) + ' Years ' + Math.floor(num_months) + ' Months ' + Math.floor(num_days+1) + ' Days';

ctrlpatient_age.setValue(agestr)

$('#p_age').html(agestr);

}

}


Thanks J

Myr0n 8/27/2020

Here is a code snippet that I usually use to get the age.

I changed the names of the variables to suit your needs and be easy to understand.

var ctrldob = new Date(2005, 1, 1);

var ctrldoa = new Date(2020, 8, 23);

var diff = new Date(ctrldoa.getTime() - ctrldob.getTime());

console.log(diff.getUTCFullYear() - 1970); // Gives difference as year

console.log(diff.getUTCMonth()); // Gives month count of difference

console.log(diff.getUTCDate() - 1); // Gives day count of difference
woodey2002 author 8/28/2020

Wow Myr0n Thanks you so much.
Amazing!!!!
Cheers,

J