This topic is locked

Age calculation

2/5/2021 8:57:00 PM
PHPRunner General questions
I
ianweithers author

Sharing some code for calculation of age.
var ctrlAge = Runner.getControl(pageid, 'age');

var ctrlDate = Runner.getControl(pageid, 'date_of_birth');

now = new Date();

function func() {

var dateofbirth=new Date(ctrlDate.getValue());

var age=now.getFullYear()-dateofbirth.getFullYear();

var m = now.getMonth() - dateofbirth.getMonth();

if (m < 0 || (m === 0 && now.getDate() < dateofbirth.getDate())) {

age--;

}

ctrlAge.setValue(age);

};
ctrlAge.on('click', func);

S
salus1DevClub member 2/6/2021

Thanks for sharing, that's pretty cool. Here's a slightly different way to go, using PHP (copied from stackoverflow), just for comparison sake...
<?php

$bday = new DateTime('11.4.1987');

$today = new Datetime(date('m.d.y'));

$diff = $today->diff($bday);

printf(' Your age : %d years, %d month, %d days', $diff->y, $diff->m, $diff->d);

printf("\n");

?>

G
gchable 2/24/2021


function age($bday){

$bday = date("Y-m-d", strtotime($bday));

$interval = date_diff(date_create(), date_create($bday));

return $interval->format("%y");

}
echo age("1977-01-10");