php根据身份证号获取年龄优化版

function  toAge($idCard){
    if(empty($idCard)) return '';
    //获取当前年份;
    $now_year   = date('Y');

    //获取当前年份月份;
    $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');

  if(strlen($idCard)==18){ //18位身份证号;
      //获取身份证号对应的年,月份,日期;
     $card_year  = substr($idCard,6,4);

     //获取身份证号对应月份
     $card_month = substr($idCard,10,2);
     $card_month = substr($card_month,0,1)=='0' ? substr($card_month,-1): $card_month;
    
     //获取身份证号对应日期;
     $card_day   = substr($idCard,12,2);
     $card_day   = substr($card_day,0,1)=='0' ? substr($card_day,-1): $card_day;
     }else{  //15位身份证号;
        //获取身份证号对应的年,月份,日期;
     $card_year  = '19'.substr($idCard,6,2);

     //获取身份证号对应月份
     $card_month = substr($idCard,8,2);
     $card_month = substr($card_month,0,1)=='0' ? substr($card_month,-1): $card_month;
    
     //获取身份证号对应日期;
     $card_day   = substr($idCard,10,2);
     $card_day   = substr($card_day,0,1)=='0' ? substr($card_day,-1): $card_day;
    }
    //获取当前年份和身份证年份之差;
    $age        = $now_year - $card_year;

    $realAge = 0;

    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;
} 

 

posted @ 2020-08-05 16:43  王芬老师  阅读(536)  评论(2编辑  收藏  举报