根据生日获取年龄带单位
function getAgeByBirthday($birthday){ if(empty($birthday)) return ''; //获取当前年份; $now_year = substr(date('Y-m-d'),0,4); //获取当前年份月份; $now_month = substr(date('m'),0,1)=='0' ? substr(date('m'),-1) : date('m'); //获取当前日期; $now_day = substr(date('d'),0,1)=='0' ? substr(date('d'),-1) : date('d'); //获取身份证号对应的年,月份,日期; $card_year = substr($birthday,0,4); //1986-12-16; //获取身份证号对应月份 $card_month = substr($birthday,5,2); $card_month = substr($card_month,0,1)=='0' ? substr($card_month,-1): $card_month; //获取身份证号对应日期; $card_day = substr($birthday,8,2); $card_day = substr($card_day,0,1)=='0' ? substr($card_day,-1): $card_day; //获取当前年份和身份证年份之差; $age = $now_year - $card_year; //获取当前月份和身份证月份之差; $month = $now_month - $card_month; $day = $now_day - $card_day; $monthArr = [1,3,5,7,8,10,12]; $realAge = '0天'; if($age < 1 ){ //1岁内 //比较月份; if($month < 1){ //一个月以内,显示天数; if($day > 0 ){ $realAge = $day.'天'; } }elseif($month ==1){ if($day > 0){ $realAge = $month .'个月'. $day.'天'; }else{ if(in_array($card_month,$monthArr)){ $realAge = (31+$day).'天'; }else{ $realAge = (30+$day).'天'; } } }else { if($day > 0){ $realAge = $month .'个月'. $day.'天'; }else{ $realAge = ($month-1) .'个月'. (30+$day).'天'; } } }elseif($age >=1 && $age <=3 ){ //1-3岁 if($age ==1 ){ if($month > 0){ $realAge = $age .'岁'.$month.'个月'; }else{ $realAge = (12+$month).'个月'; if($month==0){ if($day < 0){ $realAge = (12-1).'个月'; } } } }elseif($age ==3){ if($month>=0){ if($day>=0){ $realAge = $age .'岁'.$month.'个月'; if($month == 0){ $realAge = $age .'岁'; } }else{ $realAge = $age .'岁'.($month-1).'个月'; if($month-1<=0){ $realAge = $age .'岁'; } } }else{ $realAge = ($age-1).'岁'.(12+$month).'个月'; } }else{ if($month > 0){ $realAge = $age .'岁'.$month.'个月'; }else{ $realAge = ($age-1).'岁'.(12+$month).'个月'; if($month == 0){ $realAge = $age .'岁'; } } } }else{ //大于3岁 if($now_month == $card_month){ //比较日期; if($now_day >= $card_day){ $realAge = $age.'岁'; }else{ $realAge = ($age -1).'岁'; } }elseif($now_month > $card_month){ $realAge = $age.'岁'; }else{ $realAge = ($age -1).'岁'; } } return $realAge; }