checkdate() 驗證給定的月、日、年是否構成合法的格里曆日期。自動處理閏年、各月天數、年份範圍等規則,是表單驗證、日期解析的基礎工具。
checkdate(int $month, int $day, int $year): bool
| 參數 | 類型 | 範圍/說明 |
|---|---|---|
$month | int | 月份 1-12 |
$day | int | 日期 1-31(實際上限取決於月份/年份) |
$year | int | 年份 1-32767(32位系統受限,64位更大) |
返回 true 合法,false 不合法。參數超出範圍直接返回 false,不拋出錯誤。
<?php
$tests = [
[2, 29, 1900] => false, // 1900 非閏年(整百年非400倍數)
[2, 29, 2000] => true, // 2000 閏年(400倍數)
[2, 29, 2100] => false, // 2100 非閏年
[4, 30, 2024] => true, // 4月30日存在
[4, 31, 2024] => false, // 4月無31日
[13, 1, 2024] => false, // 月份超出
[0, 1, 2024] => false, // 月份無效
[1, 0, 2024] => false, // 日期無效
[1, 1, 0] => false, // 年份無效
[12, 31, 9999] => true, // 大年份(64位系統)
];
echo "<pre>";
foreach ($tests as [$m, $d, $y] => $expected) {
$result = checkdate($m, $d, $y);
$status = $result === $expected ? '✅' : '❌';
printf("%s %02d/%02d/%04d => %s (預期: %s)\n", $status, $m, $d, $y, $result ? '合法' : '不合法', $expected ? '合法' : '不合法');
}
echo "</pre>";
?>
<?php
function validateBirthdate(string $input): array {
// 期望格式 Y-m-d
if (!preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $input, $matches)) {
return ['valid' => false, 'error' => '格式錯誤,請使用 YYYY-MM-DD'];
}
$year = (int)$matches[1];
$month = (int)$matches[2];
$day = (int)$matches[3];
if (!checkdate($month, $day, $year)) {
return ['valid' => false, 'error' => '日期不存在(如2月30日、非閏年2月29日等)'];
}
// 業務規則:出生日期不能是未來,且不早於 1900 年
$today = new DateTime();
$birth = DateTime::createFromFormat('Y-m-d', $input);
if ($birth > $today) {
return ['valid' => false, 'error' => '出生日期不能晚於今天'];
}
if ($year < 1900) {
return ['valid' => false, 'error' => '年份不可早於 1900'];
}
return ['valid' => true, 'date' => $birth];
}
// 測試
$inputs = ['2000-02-29', '2001-02-29', '2025-01-01', '1899-12-31', 'invalid'];
foreach ($inputs as $input) {
$res = validateBirthdate($input);
echo $input . ' => ' . ($res['valid'] ? '✅ 通過' : "❌ {$res['error']}") . "\n";
}
?>
<?php
function generateRandomValidDate(int $startYear = 1970, int $endYear = 2024): string {
while (true) {
$year = random_int($startYear, $endYear);
$month = random_int(1, 12);
// 先獲取該月最大天數
$maxDay = (int)date('t', mktime(0,0,0, $month, 1, $year));
$day = random_int(1, $maxDay);
// 雙重保險驗證
if (checkdate($month, $day, $year)) {
return sprintf('%04d-%02d-%02d', $year, $month, $day);
}
}
}
// 生成 10 個隨機合法日期
for ($i = 0; $i < 10; $i++) {
echo generateRandomValidDate() . "\n";
}
?>
PHP 內核實現大致相當於:
function checkdate_logic(int $m, int $d, int $y): bool {
if ($m < 1 || $m > 12) return false;
if ($d < 1) return false;
if ($y < 1 || $y > 32767) return false; // 32位系統限制
// 各月天數表(非閏年)
$dim = [1=>31, 2=>28, 3=>31, 4=>30, 5=>31, 6=>30, 7=>31, 8=>31, 9=>30, 10=>31, 11=>30, 12=>31];
// 閏年判斷:能被4整除但不能被100整除,或能被400整除
$isLeap = ($y % 4 === 0 && $y % 100 !== 0) || ($y % 400 === 0);
if ($isLeap) $dim[2] = 29;
return $d <= $dim[$m];
}
?>
checkdate() 僅支援格里曆(公曆)。若需驗證農曆、波斯曆、希伯來曆等,需使用:
IntlCalendar (intl 擴展):`IntlCalendar::createInstance()->set(...)->getActualMaximum(IntlCalendar::DAY_OF_MONTH)`kornrunner/php-chinese-calendar、jenssegers/date (Laravel)// 1. 直接用於用戶輸入未轉型
checkdate($_POST['month'], $_POST['day'], $_POST['year']); // 字串會被強制轉型,但「08」-> 8 正常,「09」-> 0 錯誤(八進制)!
// 2. 信任前端傳來的 timestamp 直接拆解
$ts = $_POST['timestamp'];
checkdate(date('m', $ts), date('d', $ts), date('Y', $ts)); // 若 $ts 為假/字串會報錯
// 1. 顯式轉型 + 範圍預檢
$m = (int)$_POST['month'];
$d = (int)$_POST['day'];
$y = (int)$_POST['year'];
if ($m >= 1 && $m <= 12 && $d >= 1 && $d <= 31 && $y >= 1900 && $y <= 2100) {
if (checkdate($m, $d, $y)) { /* 合法 */ }
}
// 2. 使用 DateTime 驗證(更嚴格,含時區、格式)
$dt = DateTime::createFromFormat('Y-m-d', $input);
if ($dt && $dt->format('Y-m-d') === $input) { /* 合法 */ }
checkdate() 是 PHP 驗證格里曆日期合法性的標準函數,正確處理了閏年規則與月份天數。實際開發中建議:前端做格式攔截,後端用 `checkdate()` 或 `DateTime::createFromFormat()` 雙重驗證,並結合業務規則(年份範圍、未來日期限制)。對於高併發場景,`checkdate()` 純數學運算極快,無性能瓶頸。