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,精確到生日當天。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章