PHP获取身份证年龄和性别,网上找了几个都不大好,自己弄一个
<?php
declare(strict_types=1);
namespace App\Helper;
class CertNumberHelper
{
public static function getAge(string $id): int
{
$birthDate = strtotime(substr($id, 6, 8));//截取日期并转为时间戳
$year = date('Y', $birthDate);
$month = date('m', $birthDate);
$day = date('d', $birthDate);
$currentY = date('Y');
$currentM = date('m');
$currentD = date('d');
$age = $currentY - $year;
if ($month > $currentM || ($month == $currentM && $day > $currentD)) {
$age--;
}
return $age;
}
public static function getGender(string $id): string
{
return intval(substr($id, (strlen($id) == 15 ? -1 : -2), 1)) % 2 == 1 ? '男' : '女';
}
}