PHP function that returns the exact age

Here is a simple PHP function that returns the exact age of a person given his/her birthdate: function age($month, $day, $year){ $y = gmstrftime(“%Y”); $m = gmstrftime(“%m”); $d = gmstrftime(“%d”); […]

Here is a simple PHP function that returns the exact age of a person given his/her birthdate:

function age($month, $day, $year){
 $y = gmstrftime("%Y");
 $m = gmstrftime("%m");
 $d = gmstrftime("%d");
 $age = $y - $year;
 if($m <= $month)
 {
 if($m == $month)
 {
 if($d < $day) $age = $age - 1;
 }
 else $age = $age - 1;
 }
 return($age);
}

The function is used with a call like this:

age(2,1,1979);

The example call would return 30 (at this moment). You can use this to display the age of your users if you have their birthdate.

Enjoy!

Tiny break: 📬 Want to stay up to date with frontend and trends in web design? Check out our Collective and stay in the loop.

Manoela Ilic

Editor-in-Chief at Codrops. Designer, developer, and dreamer — sharing web inspiration with millions since 2009. Bringing together 20+ years of code, creativity, and community.

The
New
Collective

🎨✨💻 Stay ahead of the curve with handpicked, high-quality frontend development and design news, picked freshly every single day. No fluff, no filler—just the most relevant insights, inspiring reads, and updates to keep you in the know.

Prefer a weekly digest in your inbox? No problem, we got you covered. Just subscribe here.

Feedback 3

Comments are closed.
  1. Pingback: PHP function that returns the exact age

  2. $intCurrentDateStamp = time();
    $intBirthStamp = mktime( 0, 0, 0, 12, 24, 1986 );
    $intAge = $intCurrentDateStamp – $intBirthStamp;
    echo round( ( ( ( ( $intAge / 60 ) / 60 ) / 24 ) / 365 ) );

  3. The code from Mary is a bit complicated and is wrong (if the locale is not GMT it might produce false result).

    The code from Adam is wrong as well as it doesn’t take leap years into account.

    function age($year, $month, $day) {
    $y = date(‘Y’);
    $m = date(‘m’);
    $d = date(‘d’);

    $age = $y – $year;

    if( ($m < $month) || ($m == $month && $d < $day) )
    {
    $age–;
    }

    return $age;
    }