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.身份证格式错误,会返回空

相关推荐
jwn9996 小时前
Laravel6.x核心特性全解析
开发语言·php·laravel
星辰徐哥7 小时前
5G的行业应用:工业互联网、车联网、智慧医疗中的网络支撑
网络·5g·php
三道渊8 小时前
进程通信与网络协议
开发语言·数据库·php
流觞 无依8 小时前
DedeCMS plus/download.php SQL注入漏洞修复教程
sql·php
Freak嵌入式9 小时前
MicroPython LVGL基础知识和概念:显示与多屏管理
开发语言·python·github·php·gui·lvgl·micropython
Freak嵌入式9 小时前
MicroPython LVGL基础知识和概念:时序与动态效果
开发语言·python·github·php·gui·lvgl·micropython
fengci.12 小时前
php反序列化(复习)(第三章)
android·开发语言·学习·php
说实话起个名字真难啊12 小时前
Docker 入门之网络基础
网络·docker·php
竹之却12 小时前
【Agent-阿程】openclaw v2026.4.9更新内容介绍
开发语言·php·openclaw·openclaw 更新
熊猫笔记12 小时前
PHP将Word文件转换为PDF文件的三种方式,以及中文乱码解决
php