diff($target); // $age = $interval->y; // // // 如果生日还没到,减一岁 // if ($target->format('m-d') < $birthdate->format('m-d')) { // $age--; // } // // return $age; // 提取出生年月日 $birthYear = substr($idNumber, 6, 4); $birthMonth = substr($idNumber, 10, 2); $birthDay = substr($idNumber, 12, 2); // 创建出生日期和目标日期的 DateTime 对象 $birthdate = new DateTime("$birthYear-$birthMonth-$birthDay"); $target = new DateTime($targetDate); // 计算年龄 $interval = $birthdate->diff($target); // 使用正确的属性获取年龄 $age = $interval->y; return $age; } //根据身份证获取生日 public static function getBirthdayFromIDCard($idCard) { // 检查身份证号码是否有效 if (!preg_match("/^(\d{15}$|^\d{17}[xX\d]$)/", $idCard)) { return false; } // 提取出生日期部分 $birthday = substr($idCard, 6, 8); // 如果是15位的身份证号码,需要将年份从两位扩展到四位(假设1900-2000) if (strlen($idCard) == 15) { $year = substr($birthday, 0, 2); if ($year >= 0 && $year <= 20) { // 2000-2020 $birthday = '20' . $birthday; } else { // 1900-1999 $birthday = '19' . $birthday; } } // 格式化并返回日期字符串 return date('Y-m-d', strtotime($birthday)); } }