Snippets

Calculate age

With this function you can calculate the age of a person Example: echo “Age is: ” . birthday (“1984-07-05″); Result will be (23 Feb 2012) = “Age is: 27″

function birthday ($birthday){
    list($year,$month,$day) = explode("-",$birthday);
    $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;
}

Source: http://dzone.com/snippets/calculate-age...

Share this snippet

 

Comments (3) - Leave yours

  1. Bill Wheeler said:

    PHP >=5.3 has a function/class built in to do this very thing….calculate the difference between two dates. Your function can easily whittled down to a couple of lines. :o )

    function birthday($birthday) {
    $diff = date_diff(date_create(), date_create($birthday));
    return $diff->y;
    }

    This will also support any date format that’s acceptable to PHP, not limited to YYYY-MM-DD.

    Hope this helps somebody!

  2. René said:

    Another function for calculate the age of a person, and in this case the format of the birthday doesn’t mind. It can be 1990-07-19 or 19-07-1990.

    function birthday ($birthday)
    {
    $datetime1 = new DateTime($birthday);
    $datetime2 = new DateTime(date(‘Y-m-d’));
    $different = $datetime1->diff($datetime2);

    return $different->format(‘%y’);
    }

  3. ljasinskipl said:

    Doesn’t work right. There should be something like:
    if($month_diff < 0)
    $year_diff–;
    if($month_diff == 0 && $day_diff < 0)
    $year_diff–;
    instead of

    if ($day_diff < 0 || $month_diff < 0)

Leave a Reply

Your email address will not be published. Required fields are marked *

Please respect the following rules: No advertising, no spam, no keyword in name field. Thank you!