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

2 comments on “Calculate age from datepicker field in ACF

  1. Would there be a way to display the Age in weeks instead of years? I have a client who raises puppies and wants to show the age of each puppy in weeks. Thanks!

    1. You could get the value of days from the dates difference and then divide by 7 to get the number of weeks, using some PHP calculations.


      if(get_field('date_of_birth')) {
      $date = get_field('date_of_birth');
      $birthday = new DateTime($date);
      $interval = $birthday->diff(new DateTime);
      $days = $interval->days;
      $weeks = (int) ($days / 7);

      And then in the template, call it like this: echo $weeks;

      That should convert the date into weeks, not tested but should do the job.
      P

Leave a Reply

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