Snippets → PHP
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;
}
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.
)
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!
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’);
}
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)