您的位置:首页 > 编程语言 > PHP开发

PHP按照生日日期计算当前的实际年龄

2015-11-09 16:58 676 查看
        要计算最真实的周岁年龄,精确到生日当天,我的思路是根据生日当天一直到今天的天数,然后去除每年的365天,向下取整获得完整的年数,这个值就是周岁。中间的闰年会让总天数多出来几天,这些多出来的天数剔除出去就行了。

  代码如下:

class ComputeYear{
private static $leapYears = 0;

public static function getYear($birthday){
$currentDay = new \DateTime();
self::getLeapYears($currentDay->format('Y-m-d'),$birthday);
$daysDiff = date_diff($currentDay,date_create($birthday));
$realDays = $daysDiff->days-self::$leapYears;
if($realDays >= 365){
$age = floor($realDays / 365);
echo 'U r '.$age.' year old!';
}else{
echo "It's a Baby girl";
}
}

private static function getLeapYears($currentDay,$birthDay){
$currentYear = date('Y',strtotime($currentDay));
$currentMonth = date('m',strtotime($currentDay));
$birthYear = date('Y',strtotime($birthDay));
$birthMonth = date('m',strtotime($birthDay));
if($birthMonth > 2){
$birthYear += 1;
}
if($currentMonth < 2){
$currentYear += 1;
}
for($i = $birthYear;$i<=$currentYear;$i++){
if(self::checkLeap($i)){
self::$leapYears++;
}
}
}

private static function checkLeap($year){
$time = mktime(20,20,20,2,1,$year);
if (date("t",$time)==29){
return true;
}else{
return false;
}
}
}
ComputeYear::getYear('1991-11-10');

1991-11-09得到的是24,1991-11-10得到的是23,精确到生日当天。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  生日 php 日期