取得某月天數是日曆、排程、帳單系統常見需求。本文提供純 PHP 邏輯實作,不依賴 cal_days_in_month() 擴展,適合受限環境。
<?php
class DateHelper {
public $year;
public $month;
public function __construct($year = null, $month = null) {
$this->year = $year ?? (int)date('Y');
$this->month = $month ?? (int)date('m');
}
public function getLastDay() {
if ($this->month === 2) {
return $this->isLeapYear($this->year) ? 29 : 28;
}
if (in_array($this->month, [4, 6, 9, 11])) {
return 30;
}
return 31;
}
public function isLeapYear($year) {
// 閏年規則:能被4整除但不能被100整除,或能被400整除
return (($year % 4 === 0 && $year % 100 !== 0) || $year % 400 === 0);
// 或直接用 PHP 內建:return (bool)date('L', strtotime("$year-01-01"));
}
}
// 使用範例
$helper = new DateHelper(2024, 2);
echo $helper->getLastDay(); // 29 (2024 為閏年)
$lastDay = (int)date('t', strtotime('2024-02-01')); // 29
// 或
$lastDay = cal_days_in_month(CAL_GREGORIAN, 2, 2024); // 需 calendar 擴展