PHP年龄计算
通过出生日期,再传入指定日期计算年龄,不传入则计算到今天的时间。
/**
* 计算年龄
* @param $birthday 出生时间 Y-m-d
* @param $data 当前时间 Y-m-d
**/
function getAge($birthday, $date = '') {
$birthday = strtotime($birthday);
if (!$birthday) {
return 0;
}
$date = strtotime($date);
$date = !$date ? time() : $date;
//格式化出生时间年月日
$byear = date('Y', $birthday);
$bmonth = date('m', $birthday);
$bday = date('d', $birthday);
//格式化当前时间年月日
$tyear = date('Y', $date);
$tmonth = date('m', $date);
$tday = date('d', $date);
//开始计算年龄
$age = $tyear - $byear;
if ($bmonth > $tmonth || $bmonth == $tmonth && $bday > $tday) {
$age--;
}
return $age;
}
