PHP 內建 date()、strtotime()、cal_days_in_month() 已完整封裝曆法邏輯,無需手動實作 Zeller 公式。
<?php
/**
* 月曆生成器類
*/
class CalendarRenderer
{
private const MONTHS_ZH = ['', '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
private const MONTHS_EN = ['', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
private const WEEKDAYS_ZH = ['日', '一', '二', '三', '四', '五', '六'];
private const WEEKDAYS_EN = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
private const BG_COLORS = ['#FFE4B5', '#FFFFFF', '#98FB98', '#FFE4B5', '#9ACD32', '#6B8E23', '#FFA500', '#FF6347', '#FF0000', '#FF8C00', '#FFFF00', '#FFB6C1'];
public function __construct(
private int $year,
private int $month,
private string $lang = 'zh'
) {
$this->validateInput();
date_default_timezone_set('Asia/Shanghai');
}
private function validateInput(): void
{
if ($this->year < 1970 || $this->year > 2037) {
throw new InvalidArgumentException('年份必須在 1970-2037 之間');
}
if ($this->month < 1 || $this->month > 12) {
throw new InvalidArgumentException('月份必須在 1-12 之間');
}
}
public function render(): string
{
$firstDayTimestamp = strtotime("{$this->year}-{$this->month}-01");
$firstDayOfWeek = (int)date('w', $firstDayTimestamp); // 0=週日 ... 6=週六
$daysInMonth = (int)date('t', $firstDayTimestamp);
$monthName = $this->lang === 'zh' ? self::MONTHS_ZH[$this->month] : self::MONTHS_EN[$this->month];
$weekdays = $this->lang === 'zh' ? self::WEEKDAYS_ZH : self::WEEKDAYS_EN;
$bgColor = self::BG_COLORS[$this->month - 1];
$html = "";
$html .= "{$this->year}年 {$monthName} ";
// 表頭:星期
$html .= "";
foreach ($weekdays as $day) {
$html .= "{$day} ";
}
$html .= " ";
// 日期網格
$day = 1;
for ($row = 0; $row < 6; $row++) {
$html .= "";
for ($col = 0; $col < 7; $col++) {
$html .= "";
// 判斷是否顯示日期
if ($row === 0 && $col < $firstDayOfWeek) {
// 月初空白
$html .= " ";
} elseif ($day <= $daysInMonth) {
// 正常日期
$isToday = ($this->year === (int)date('Y') && $this->month === (int)date('m') && $day === (int)date('d'));
$style = $isToday ? "style='background:#3498db; color:white; border-radius:50%; width:30px; height:30px; display:inline-flex; align-items:center; justify-content:center;'" : '';
$html .= "{$day}";
$day++;
} else {
// 月尾空白
$html .= " ";
}
$html .= " ";
}
$html .= " ";
if ($day > $daysInMonth) break; // 提前結束
}
$html .= "
";
return $html;
}
}
// === 處理表單提交 ===
$year = isset($_POST['myYear']) ? (int)$_POST['myYear'] : (int)date('Y');
$month = isset($_POST['myMonth']) ? (int)$_POST['myMonth'] : (int)date('m');
$error = '';
try {
$calendar = new CalendarRenderer($year, $month);
$calendarHtml = $calendar->render();
} catch (InvalidArgumentException $e) {
$error = $e->getMessage();
$calendar = new CalendarRenderer((int)date('Y'), (int)date('m'));
$calendarHtml = $calendar->render();
}
?>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<title>PHP 動態月曆表</title>
<style>
body { font-family: 'Microsoft JhengHei', sans-serif; max-width: 800px; margin: 20px auto; padding: 20px; }
.form-group { margin-bottom: 15px; display: flex; gap: 10px; align-items: center; }
label { font-weight: bold; }
input[type="number"] { padding: 8px; border: 1px solid #ddd; border-radius: 4px; width: 80px; }
input[type="submit"] { padding: 8px 20px; background: #3498db; color: white; border: none; border-radius: 4px; cursor: pointer; }
input[type="submit"]:hover { background: #2980b9; }
.error { color: #e74c3c; margin: 10px 0; font-weight: bold; }
table { margin-top: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
</style>
</head>
<body>
<h1>PHP 動態月曆表</h1>
<form method="post" class="form-group">
<label>年份 (1970-2037):</label>
<input type="number" name="myYear" value="<?= $year ?>" min="1970" max="2037" required>
<label>月份 (1-12):</label>
<input type="number" name="myMonth" value="<= $month ?>" min="1" max="12" required>
<input type="submit" value="生成月曆">
</form>
<?php if ($error): ?>
<div class="error"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<?= $calendarHtml ?>
</body>
</html>
| 函數/技術 | 用途 | 說明 |
|---|---|---|
strtotime("Y-m-01") | 取得月初時間戳 | 字串解析靈活,支援相對時間 |
date('w', $ts) | 取得星期幾 (0-6) | 0=週日,決定首行偏移 |
date('t', $ts) | 取得月份總天數 | 自動處理閏年二月 |
date('Y-m-d') | 取得今日日期 | 用於高亮當前日期 |
| 面向物件封裝 | 邏輯與視圖分離 | 易測試、易維護、可複用 |
ChineseCalendar 庫或自行實作本文將原始程式碼重構為現代 PHP 類別架構,修正了原始碼中年份驗證邏輯錯誤(原碼 $year <2038 但 strtotime 32 位元上限為 2038-01-19),強化輸入驗證與 XSS 防護,採用語意化 HTML 與 CSS 樣式分離。此實作可直接整合至 CMS、OA 系統或個人專案中。