本函式 calendar($month, $year) 可根據指定年月自動生成 HTML 表格形式的月曆。若參數為空,預設顯示當月。支援上下月切換導航,並正確處理閏年與每月天數差異。
<?php
/**
* 自動生成月曆
* @param int $MM 月份 (1-12),預設為當月
* @param int $YYYY 年份,預設為今年
*/
function calendar($MM = "", $YYYY = "") {
if ($MM == "") $MM = date("m");
if ($YYYY == "") $YYYY = date("Y");
if (!checkdate($MM, 1, $YYYY)) return;
// 計算關鍵日期資訊
$firstDay = (int)strftime("%w", mktime(0,0,0,$MM,1,$YYYY)); // 本月 1 號是星期幾 (0=日)
$daysInMonth = (int)strftime("%d", mktime(0,0,0,$MM+1,0,$YYYY)); // 本月總天數
$monthName = strftime("%b %Y", mktime(0,0,0,$MM,1,$YYYY)); // 如 "Jan 2024"
// 上/下月導航參數
$prevMonth = (int)strftime("%m", mktime(0,0,0,$MM-1,1,$YYYY));
$prevYear = (int)strftime("%Y", mktime(0,0,0,$MM-1,1,$YYYY));
$nextMonth = (int)strftime("%m", mktime(0,0,0,$MM+1,1,$YYYY));
$nextYear = (int)strftime("%Y", mktime(0,0,0,$MM+1,1,$YYYY));
// 輸出表格標題
echo "<table border='1' cellpadding='3' cellspacing='0'>\n";
echo " <tr>\n";
echo " <th><a href='?month=$prevMonth&year=$prevYear'><<</a></th>\n";
echo " <th colspan='5'>$monthName</th>\n";
echo " <th><a href='?month=$nextMonth&year=$nextYear'>>></a></th>\n";
echo " </tr>\n";
echo " <tr>\n";
foreach (array("Sun","Mon","Tue","Wed","Thu","Fri","Sat") as $day) {
echo " <th>$day</th>\n";
}
echo " </tr>\n";
// 生成日期格子
$currentDay = 1;
for ($week = 0; $week < 6; $week++) {
echo " <tr>\n";
for ($dow = 0; $dow < 7; $dow++) {
if (($week == 0 && $dow < $firstDay) || $currentDay > $daysInMonth) {
echo " <td> </td>\n";
} else {
$highlight = ($currentDay == date("j") && $MM == date("m") && $YYYY == date("Y")) ? " style='background:#ffffcc'" : "";
echo " <td$highlight>$currentDay</td>\n";
$currentDay++;
}
}
echo " </tr>\n";
if ($currentDay > $daysInMonth) break;
}
echo "</table>\n";
}
?>
<?php
require_once 'calendar.php';
// 顯示 2024 年 1 月
calendar(1, 2024);
// 顯示當月(無參數)
calendar();
?>