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