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

相关推荐
李纲明4 小时前
WordPress 后台登录马上被踢回登录页:Cookie 域、HTTPS、盐值和页面缓存怎么查
运维·缓存·https·php·wordpress·cookie
4SAPI4 小时前
AI 数据分析工具大模型 API 选型指南
大数据·人工智能·架构·php·1024程序员节
f8979070705 小时前
php升级之后切换到php8.2.35报pdo错误
php
4SAPI5 小时前
搭建 AI 数据分析工具大模型 API 选型指南
数据库·人工智能·架构·php·1024程序员节
Regentsoft丽晶软件6 小时前
从 “定时拉取“ 到 “事件驱动“,服装库存实时同步的底层架构怎么设计?
经验分享·php·零售
用户60968624266089 小时前
页面构建器做的页面翻译:短代码、区块、动态内容各自会踩什么坑
php·wordpress
阿文和她的Key9 小时前
PHP2Shell事故四层拆解:AI找洞是小时级,披露协调还是邮件级
网络·人工智能·架构·php
贵州诚鑫致达科技有限公司12 小时前
PHP两个9.2分RCE漏洞,速查版本
服务器·php·1024程序员节
hudie76513 小时前
LikeShop 二开最常改的 5 个文件(附改前改后对比)
前端·uni-app·php·个人开发
东宇科技13 小时前
crmeb开源版本安装步骤2026-10-20
后端·php·crmeb