Calculate Age from Date of Birth

wildmanmatt

New member
Hi,

I am trying to have a field display the current age of a person's record based on their date of birth. I have created my field for Age and setup a calculated field function like this
function dadabik_age ($params){
//explode the date to get month, day and year
$birthDate = explode("/", $params(date_of_birth));
//get age from date or birthdate
$age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md")
? ((date("Y") - $birthDate[2]) - 1)
: (date("Y") - $birthDate[2]));
echo "Age is:" . $age;
}

I would want this to be correct when viewing the record. When I apply the function, the age field just remains blank.

Can anyone see what I'm doing wrong? Or think of a better way to do it?

Thanks,

Matt

I'm not sure if I'm using the wrong function? Or if I should be using a JS function instead?
 

eugenio

Administrator
Staff member
Hello Matt,
I haven't checked your code but I don't see any RETURN statement therefore the calculated field cannot work.
Check the chapter 10.1. Calculated fields in the documentation for further details.

Best,
 

wildmanmatt

New member
Thanks for that.

If anyone is looking to do something similar, this is the code that I added to calculated_fields_functions.php that worked for me

function dadabik_age ($params){
//get age from date or birthdate
//explode the date to get month, day and year
$birthDate = explode("/", $params['date_of_birth']);
$age = (date("md", date("U", mktime(0, 0, 0, $birthDate[2], $birthDate[0], $birthDate[1]))) > date("md")
? ((date("Y") - $birthDate[0]) - 1)
: (date("Y") - $birthDate[0]));
return ($age);
}
 
Top