Friday, November 26, 2010

How to calculate age in PHP

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

<?php

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;
?>

No comments:

Post a Comment