IT & Programming

Get age from date with PHP

This function accepts a date parameter and returns the number of years since years of given date.

Function

function getAge($date) {

    list($birthYear, $birthMonth, $birthDay) = explode('-', $date);

    $yearDiff = date('Y') - $birthYear;
    $monthDiff = date('m') - $birthMonth;
    $dayDiff = date('d') - $birthDay;

    if ($dayDiff < 0 || $monthDiff < 0)
        $yearDiff--;

    return $yearDiff;
}

Calling The Function

echo getAge('1985-10-06');

Output

27

Leave A comment

Email address is optional and will not be published. Only add email address if you want a reply from blog author.
Please fill required fields marked with *