使用php实现根据身份证获取年龄的代码

今天小编给大家分享的是使用php实现根据身份证获取年龄的代码,相信很多人都不太了解,为了让大家更加了解php实现根据身份证获取年龄的代码,所以给大家总结了以下内容,一起往下看吧。一定会有所收获的哦。

使用php实现根据身份证获取年龄的代码

实例代码如下:

function getAge($id){

# 1.从身份证中获取出生日期
$id = $id;//身份证
$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() 方法,传入身份证号即可计算。

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

以上就是使用php实现根据身份证获取年龄代码的简略介绍,当然详细使用上面的不同还得要大家自己使用过才领会。如果想了解更多,欢迎关注行业资讯频道哦!