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

来源:互联网 发布:手机定位软件免费版 编辑:程序博客网 时间:2024/04/28 18:47

        要计算最真实的周岁年龄,精确到生日当天,我的思路是根据生日当天一直到今天的天数,然后去除每年的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,精确到生日当天。

0 0
原创粉丝点击