php通过身份证号码计算年龄

1.需求,需要获取工人的年龄来各种判断业务
2.代码方法

= 复制代码
/**
     * 通过身份证号码计算年龄
     * @param $idCard
     * @return int|string $idCard 身份证号码
     * @throws Exception 年龄(成功)或空字符串(失败)
     */
    static function getIdCardAge($idCard)
    {
        // 如果身份证为空,直接返回空字符串
        if (empty($idCard)) {
            return '';
        }

        // 移除可能存在的空格
        $idCard = trim($idCard);

        // 验证身份证格式(简单验证,支持15位和18位)
        $isValid = preg_match('/(^\d{15}$)|(^\d{17}(\d|X|x)$)/', $idCard);
        if (!$isValid) {
            return '';
        }

        // 提取出生日期
        if (strlen($idCard) == 18) {
            // 18位身份证
            $birthDate = substr($idCard, 6, 8);
            $birthDate = sprintf('%04d-%02d-%02d',
                substr($birthDate, 0, 4),
                substr($birthDate, 4, 2),
                substr($birthDate, 6, 2)
            );
        } else {
            // 15位身份证(转换为18位格式)
            $birthDate = '19' . substr($idCard, 6, 6);
            $birthDate = sprintf('%04d-%02d-%02d',
                substr($birthDate, 0, 4),
                substr($birthDate, 4, 2),
                substr($birthDate, 6, 2)
            );
        }

        // 将出生日期字符串转换为时间戳
        $birthTimestamp = strtotime($birthDate);
        // 获取当前时间戳
        $nowTimestamp = time();

        // 计算出生年份和当前年份
        $birthYear = date('Y', $birthTimestamp);
        $currentYear = date('Y', $nowTimestamp);

        // 计算年龄
        $age = $currentYear - $birthYear;

        //
       /* $birthMonthDay = date('md', $birthTimestamp);
        $currentMonthDay = date('md', $nowTimestamp);
        if ($currentMonthDay < $birthMonthDay) {
            $age--;
        }*/

        return $age;
    }

3.注意 **

1.身份证格式错误,会返回空

相关推荐
BingoGo1 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php
JaguarJack1 天前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php·服务端
BingoGo2 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php
JaguarJack2 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php·服务端
JaguarJack3 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
后端·php·服务端
BingoGo3 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
php
JaguarJack4 天前
告别 Laravel 缓慢的 Blade!Livewire Blaze 来了,为你的 Laravel 性能提速
后端·php·laravel
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
QQ5110082855 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php
WeiXin_DZbishe5 天前
基于django在线音乐数据采集的设计与实现-计算机毕设 附源码 22647
javascript·spring boot·mysql·django·node.js·php·html5