Skip to content

Calculate a Person's Age in PHP (Accounting for Leap Years)

1 min read

I've seen a lot of code out there for calculating a person's age that makes the mistake of ignore leap years. If you ignore leap years then the age will be out by a day or more on or around the person's birthday which isn't what you want.

It is relatively simple to correct for this though by checking the month and day of the difference and adjusting accordingly:-

 * Returns a person's age today, or on a given day
 * @param date $dob date of birth in the format 'Y-m-d'
 * @param date $date date to calculate person's age at
function calculateAge($dob, $date=null) {
    $dob = strtotime($dob);

    $date = $date ? strtotime($date) : time();

    // Calculate the age
    $age = date('Y', $date)-date('Y', $dob);

    // Correct age for leap year
    return (date('md', date('U', $dob)) > date('md', date('U', $date))) ? $age-1 : $age;

This should return the correct age on the date passed to it in the second parameter accounting for the extra days due to leap years between the date and the date of birth.

© 2024 Andy Carter