Calculate age from datepicker field in ACF

I have been building a member-based website recently for a client and needed to display the age on the profile page. I was using Advanced Custom Fields to build the profiles and used the datepicker field to set the date.

To calculate this, use the snippet below to achieve what you need.

<?php
if(get_field('date_of_birth')) {
$date = get_field('date_of_birth');
$birthday = new DateTime($date);
$interval = $birthday->diff(new DateTime);
?>
<p>Age: <strong><?php echo $interval->y; ?></strong></p>
<?php } ?>

 

Note, I needed to have the Return Format of the field set to the custom output below for it to work (display format can be anything you wish):

Useful post? Share it

Leave a Reply

Your email address will not be published. Required fields are marked *