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

相关推荐
niucloud-admin14 小时前
PHP V6 单商户常见问题——云编译报SSL证书错误的处理方案
php
计算机安禾15 小时前
【Linux从入门到精通】第31篇:防火墙漫谈——iptables与firewalld防护指南
linux·运维·php
2401_8734794019 小时前
企业安全团队如何配合公安协查?IP查询在电子取证中的技术实践
tcp/ip·安全·网络安全·php
L16247620 小时前
Win11 共享→Windows Server 访问故障总结(极简可复用)
开发语言·windows·php
niucloud-admin21 小时前
PHP V6 单商户常见问题——本地phpstudy部署,访问域名/admin 、域名/wap无法自动跳转对应首页问题
php
隔窗听雨眠1 天前
MySQL主从延迟根因诊断法
开发语言·php
niucloud-admin1 天前
PHP V6 单商户常见问题——运行内存太小导致的报错处理
php
nbwenren1 天前
办公AI实测:Gemini3、GPT-4o、Claude3.5谁更强?
服务器·数据库·php
hopetomorrow1 天前
学习路之PHP --PHP 常用扩展及作用表
开发语言·学习·php
幽络源小助理1 天前
影视脚本分镜在线协作系统源码 PHP剧本创作平台
开发语言·php