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

相关推荐
2601_9657984721 小时前
Salient Theme Setup Guide for Fast Creative WordPress Sites
数据库·web3·php·wordpress
xixiaoyunya1 天前
中小微企业轻量组网方案的技术选型与实践:从传统专线到软定义隧道的成本与效能分析
服务器·php·apache
知行产研1 天前
中国矿山无人驾驶出海的三重门
数据库·mysql·php
前进的程序员1 天前
告别Copilot?Codex本地化部署指南
开源·php·copilot·codex
weixin_BYSJ19871 天前
springboot智慧公共交通系统---附源码51123
java·javascript·spring boot·python·django·flask·php
外滩运维专家2 天前
通配符证书到期,阿里云上几个服务的证书怎么一次换完
运维·开发语言·nginx·https·php·消息推送
郑州光合科技余经理2 天前
海外版多语言团购系统架构:主数据互通与核销边界
java·开发语言·前端·后端·系统架构·php·ai编程
暂时先用这个名字2 天前
信创站群系统架构图(东方通 THS + PHP‑FPM,政府网站站群,立项 / 实施方案)
开发语言·系统架构·php
heimeiyingwang2 天前
【架构实战】Kubernetes网络模型深度解析:从Pod通信到Ingress网关实战
开发语言·架构·php
运维行者_2 天前
预测性云监控怎么做?AI驱动的7大核心能力与落地路径
服务器·开发语言·网络·数据库·人工智能·python·php