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

        要计算最真实的周岁年龄,精确到生日当天,我的思路是根据生日当天一直到今天的天数,然后去除每年的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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值