You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.9 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Lib;
use DateTime;
class Tools{
//根据当前日期和身份证获取年龄
public static function calculateAgeFromID($idNumber, $targetDate) {
// 提取出生年月日
$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));
}
//根据身份证判断性别
public static function getGenderFromIDCard($idCard) {
// 检查身份证号是否合法长度应该是18
if (strlen($idCard) != 18) {
return null;
}
// 获取身份证号的第17位
$genderBit = intval($idCard[16]);
// 判断性别
if ($genderBit % 2 == 0) {
return 0;
} else {
return 1;
}
}
}