台灣身分證字號第 7-14 碼為出生日期(YYYYMMDD)。本文提供精確計算「周歲」的函數:過了生日才算滿一歲,含邊界條件處理、效能優化與單元測試案例。
<?php
/**
* 依身分證字號計算周歲
* @param string $id 身分證字號(含 1 碼英文 + 9 碼數字)
* @return int|false 年齡或失敗回傳 false
*/
function getAgeFromId(string $id): int|false {
// 1. 基本格式驗證
if (!preg_match('/^[A-Z][12]\d{8}$/', $id)) {
return false;
}
// 2. 擷取出生日期 (第 2-9 碼,索引 1-8)
$birthStr = substr($id, 1, 8); // YYYYMMDD
$birthYear = (int)substr($birthStr, 0, 4);
$birthMonth = (int)substr($birthStr, 4, 2);
$birthDay = (int)substr($birthStr, 6, 2);
// 3. 驗證日期合法性(排除 2024-02-30 等)
if (!checkdate($birthMonth, $birthDay, $birthYear)) {
return false;
}
// 4. 計算周歲:今年生日已過?已過→今年-出生年,未過→今年-出生年-1
$today = new DateTime('today');
$birthdayThisYear = new DateTime(sprintf('%04d-%02d-%02d', $today->format('Y'), $birthMonth, $birthDay));
$age = $today->format('Y') - $birthYear;
if ($today < $birthdayThisYear) {
$age--;
}
// 5. 合理性檢查(0-120 歲)
if ($age < 0 || $age > 120) return false;
return $age;
}
| 步驟 | 說明 | 範例 (身分證 A123456789 → 1923-04-05) |
|---|---|---|
| 擷取日期 | substr($id, 1, 8) | 19230405 |
| 驗證日期 | checkdate(4, 5, 1923) | true |
| 今年生日 | 2024-04-05 | DateTime('2024-04-05') |
| 今天 | 2024-03-15 | DateTime('today') |
| 比較 | 今天 < 今年生日 | true (3/15 < 4/5) |
| 年齡 | 2024-1923-1 = 100 | 100 歲 |
新制身分證首碼英文對應數值變更(A=10→10, ..., Z=33→33,但配發規則不同),出生日期解析邏輯不變,仍取第 2-9 碼。
<?php
function getAgesBatch(array $ids): array {
$today = new DateTime('today');
$thisYear = (int)$today->format('Y');
$results = [];
foreach ($ids as $id) {
if (!preg_match('/^[A-Z][12]\d{8}$/', $id)) {
$results[$id] = false;
continue;
}
$by = (int)substr($id, 1, 4);
$bm = (int)substr($id, 5, 2);
$bd = (int)substr($id, 7, 2);
if (!checkdate($bm, $bd, $by)) {
$results[$id] = false;
continue;
}
$age = $thisYear - $by;
// 避免建立 DateTime 物件,直接比較月日
$todayMd = (int)$today->format('md'); // 例:0315
$birthMd = $bm * 100 + $bd; // 例:0405
if ($todayMd < $birthMd) $age--;
$results[$id] = ($age >= 0 && $age <= 120) ? $age : false;
}
return $results;
}
<?php
// 測試資料:[身分證, 預期年齡(基準日 2024-03-15)]
$cases = [
['A123456789', 100], // 1923-04-05, 生日未到
['A123456789', 101], // 若基準日 2024-04-06
['B200010101', 23], // 2000-10-10, 生日未到
['C20010228', 23], // 2001-02-28, 生日已過
['D20000229', 24], // 2000-02-29 (閏年), 2024 非閏年視為 2/28 已過
['E20010229', false], // 2001-02-29 不合法
['F12345678', false], // 格式錯誤
];
// 固定基準日測試(使用 DateTimeImmutable + 覆寫 'today' 需用偽造時間庫)
// 簡易測試:手動設定 $today = new DateTime('2024-03-15');
foreach ($cases as [$id, $expected]) {
$result = getAgeFromId($id);
$status = ($result === $expected) ? 'PASS' : 'FAIL';
echo "[$status] $id => $result (expected $expected)\n";
}
| 錯誤寫法 | 問題 | 修正 |
|---|---|---|
(time() - strtotime($birth)) / 31536000 | 年長度非固定(閏年),誤差累積 | 用生日比較法 |
date('Y') - $birthYear | 未判斷生日是否已過 | 補上月日比較 |
直接用 substr($id, 6, 8) | 索引錯誤(應為 1,8) | 確認字串索引:第1碼英文,第2-9碼日期 |