Support

Account

Home Forums Front-end Issues Display age from birth date Reply To: Display age from birth date

  • Hi jnrmy,

    You’re very close! The issue is in your DateTime::createFromFormat() call. You’re using the format ‘Ymd’ which expects a string like “19900517”, but ACF date fields by default return the date as “Ymd” format – which is exactly what you’re getting from get_field().

    The problem is you’re then trying to create a new DateTime object from the result, but $date is already a DateTime object. Here’s the corrected code:

    php
    <?php
    $date_string = get_field(‘person-birthday’, $post->ID);
    if($date_string) {
    $birthday = DateTime::createFromFormat(‘Ymd’, $date_string);
    $today = new DateTime();
    $interval = $birthday->diff($today);

    // Display the original date in your preferred format
    echo $birthday->format(‘d M Y’); // Shows “17 May 1990”

    // Display the age
    echo ‘ (‘ . $interval->y . ‘ ans)’;
    }
    ?>
    Key fixes:

    Removed the redundant new DateTime($date) – $date is already a DateTime object

    Added a check to ensure the date field isn’t empty

    Used $birthday->format() to display the date in a readable format

    Created $today as a separate DateTime object for the comparison

    Alternative simpler approach:
    If you prefer a more concise version:

    php
    <?php
    $birthday = get_field(‘person-birthday’, $post->ID);
    if($birthday) {
    $age = date_diff(date_create($birthday), date_create(‘today’))->y;
    echo date(‘d M Y’, strtotime($birthday)) . ‘ (‘ . $age . ‘ ans)’;
    }
    ?>
    The main issue was creating a DateTime object from another DateTime object, which was resetting the date. Try the first solution and it should display the correct age!

    Let me know if you’re still seeing “0” after this fix.