PHP Function to Calculate Age From Date of Birth


There are several times when you need to display the age of the user on your website. There are two ways to do that:

  1. Add Date of Birth column as well as age column.
  2. Display age from the Date of Birth.

Taking both the field from the user doesn’t seems to be good enough, so what to do ?

Just add the following function and you get the age of the user from the Date of Birth.

<?php
function get_age($birth_date)
{
    return floor((time() - strtotime($birth_date))/31556926);
}
echo "I am ".get_age("1989-10-21") ." years old";
?>

Output:

I am 23 years old.

You need to write Date of Birth in yyyy-mm-dd format which is the default database date format.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.