» Birthday Bundle - Over $400 worth of Envato files for just $20

How to calculate age in PHP

Posted on August 29, 2008, Filled under PHP,  Bookmark it

Here’s a simple php function that calculates the age of someone, in years.

<?php
/*
Credits: http://www.bitrepository.com
URL: http://www.bitrepository.com/web-programming/php/simple-age-calculator.html
*/
function determine_age($birth_date)
{
$birth_date_time = strtotime($birth_date);
$to_date = date('m/d/Y', $birth_date_time);

list($birth_month, $birth_day, $birth_year) = explode('/', $to_date);

$now = time();

$current_year = date("Y");

$this_year_birth_date = $birth_month.'/'.$birth_day.'/'.$current_year;
$this_year_birth_date_timestamp = strtotime($this_year_birth_date);

$years_old = $current_year - $birth_year;

if($now < $this_year_birth_date_timestamp)
{
/* his/her birthday hasn't yet arrived this year */
$years_old = $years_old - 1;
}

return $years_old;
}

// You can write about any English textual datetime description

$birth_date = '1 May 1980';

$age = determine_age($birth_date);

echo $age;
?>

Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!

Get our RSS Feed!

Related Posts

2 Replies to "How to calculate age in PHP"

  1. Thanks for the code!!

  2. HI
    this code is not working for AGE before
    1970 year
    it is working only for the YEAR after 1970
    please check 1 ce

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)