php身份证获取精准年龄 php实现根据身份证获取精准年龄

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

php身份证获取精准年龄 php实现根据身份证获取精准年龄

王佳斌   2021-04-21 我要评论

前言

有时候,我们希望通过SFZ来计算出年龄,那么下面我写的函数很适合。

实现

代码中已有详细注释。

function getAge($id){

# 1.从SFZ中获取出生日期
$id = $id;//SFZ
$birth_Date = strtotime(substr($id, 6, 8));//截取日期并转为时间戳

# 2.格式化[出生日期]
$Year = date('Y', $birth_Date);//yyyy
$Month = date('m', $birth_Date);//mm
$Day = date('d', $birth_Date);//dd

# 3.格式化[当前日期]
$current_Y = date('Y');//yyyy
$current_M = date('m');//mm
$current_D = date('d');//dd

# 4.计算年龄()
$age = $current_Y - $Year;//今年减去生日年
if($Month > $current_M || $Month == $current_M && $Day > $current_D){//深层判断(日)
 $age--;//如果出生月大于当前月或出生月等于当前月但出生日大于当前日则减一岁
}
# 返回
return $age;

}

使用

通过调用 getAge() 方法,传入SFZ号即可计算。

# 参数必须为 String 型
echo getAge('130322xxxxxxxxxx14');
// xx

小编再为大家分享一段代码:SFZ获取年龄信息:

/*
* 根据SFZ号码获取年龄
* inupt $code = 完整的SFZ号
* return $age : 年龄
*/
function ageVerification($code){
 $age_time = strtotime(substr($code, 6, 8));
 if($age_time === false){
 return false;
 }
 list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age_time)); 
 
 $now_time = strtotime("now");
 
 list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now_time));
 $age = $y2 - $y1;
 if((int)($m2.$d2) < (int)($m1.$d1)){
 $age -= 1;
 }
 return $age; 
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们