php根据身份证获取年龄的办法

2025-10-17 07:13:28

1、打开PHPstudy,启动集成开发环境,创建test.php并用notepad++打开

php根据身份证获取年龄的办法

php根据身份证获取年龄的办法

php根据身份证获取年龄的办法

2、大家都知道身份证号码中是包含我们的出生日期的,只要把出生日期截取出来就可以计算出我们的年龄了。具体截取身份证里的出生日期方法如下:

//获取身份证号码

$id_card= $id;

//截取身份证里的出生日期

$birthDate = strtotime(substr($id_card, 6, 8));

echo date('Y-m-d',$birthDate);

php根据身份证获取年龄的办法

php根据身份证获取年龄的办法

3、得到出生日期后再与当前日期相减就可以得到年龄了,具体如下:

//获取身份证号码

$id_card= "441481199401122716";

//截取身份证里的出生日期

$birthDate = strtotime(substr($id_card, 6, 8));

//格式化[出生日期]

$Year = date('Y', $birthDate);

$Month = date('m', $birthDate);

$Day = date('d', $birthDate);

//获取当前日期

$currentYear = date('Y');

$currentMonth = date('m');

$currentDay = date('d');

//计算年龄

$ageNow= $currentYear-$Year;//今年减去生日年

if($Month>$currentMonth || $Month== $currentMonth&&$Day>$currentD){

//如果出生月大于当前月或出生月等于当前月但出生日大于当前日则减一岁

    $ageNow--;

}

echo $ageNow;

php根据身份证获取年龄的办法

4、浏览器访问test.php可以得到当前年龄。

php根据身份证获取年龄的办法

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢