Saturday, March 30, 2013

PHP Function to calculate age from date of birth

Hello friends,

In almost every project in which we let the user register on our website, we definitely want date of birth (DOB) and age of the user. So I thought about creating a function which will calculate age from date of birth, so we won't have to take age from the user and it will save us some coding and time. 

So today in Developer's Blog we will learn that how to calculate age from date of birth.

function calculateAge($dob) 
{
    //calculate years of age (input string: YYYY-MM-DD)
    list($year, $month, $day) = explode("-", $dob);

    $year_diff  = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff   = date("d") - $day;

    if ($day_diff < 0 || $month_diff < 0)
        $year_diff--;

    return $year_diff;
}

I hope this will help you and you will like it.

Don't forget to leave your comments.

Thank you
Ravinder

No comments:

Post a Comment