I want get the exact age of the following date in var $birth_date
by php, How is it?
$birth_date = 2011/12/16;
$birth_date => For example, this is my birth date.
For example output from my birth date is: 0 Year, 0 Month, 1 Day
Using unix timestamps to handle birthdates is a bad idea, as their range is only very limited (1970-2038). Use php's builtin DateTime
class instead:
$then = DateTime::createFromFormat("Y/m/d", "2011/12/16");
$diff = $then->diff(new DateTime());
echo $diff->format("%y year %m month %d day
");
<?php
//calculate years of age (input string: YYYY-MM-DD)
function birthday ($birthday, $separator){
list($year,$month,$day) = explode($separator, $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;
}
echo getAge('2010/12/16', '/');
?>
Reformatted from http://snippets.dzone.com/posts/show/1310
I also recommend the Tizag PHP tutorial.