月曆生成是經典程式練習,涉及日期計算、陣列操作、HTML 輸出。本文提供現代化重構版本,支援月份導航、今日高亮、響應式設計。
<?php
/**
* 簡易月曆類別
* 支援月份導航、今日高亮、自訂樣式
*/
class SimpleCalendar {
private int $year;
private int $month;
private DateTime $currentDate;
private DateTime $firstDay;
private int $daysInMonth;
private int $startWeekday; // 0=Sun ... 6=Sat
public function __construct(?string $date = null) {
$this->currentDate = $date ? new DateTime($date) : new DateTime();
$this->currentDate->setTime(0, 0, 0);
$this->year = (int)$this->currentDate->format('Y');
$this->month = (int)$this->currentDate->format('m');
$this->firstDay = clone $this->currentDate;
$this->firstDay->modify('first day of this month');
$this->startWeekday = (int)$this->firstDay->format('w');
$this->daysInMonth = (int)$this->currentDate->format('t');
}
public function getPrevMonthUrl(string $baseUrl = ''): string {
$prev = clone $this->currentDate;
$prev->modify('first day of last month');
return $baseUrl . '?date=' . $prev->format('Y-m-d');
}
public function getNextMonthUrl(string $baseUrl = ''): string {
$next = clone $this->currentDate;
$next->modify('first day of next month');
return $baseUrl . '?date=' . $next->format('Y-m-d');
}
public function getTitle(): string {
return $this->currentDate->format('Y 年 F');
}
/**
* 生成月曆網格資料
* @return array> 6 週 x 7 天,null 代表空白
*/
public function getGrid(): array {
$grid = [];
$day = 1;
for ($week = 0; $week < 6; $week++) {
$grid[$week] = [];
for ($dow = 0; $dow < 7; $dow++) {
$cellIndex = $week * 7 + $dow;
if ($cellIndex < $this->startWeekday) {
// 月初空白
$grid[$week][$dow] = null;
} elseif ($day <= $this->daysInMonth) {
$grid[$week][$dow] = $day++;
} else {
// 月末空白
$grid[$week][$dow] = null;
}
}
// 如果已填滿所有天數且非第一週,可提早結束
if ($day > $this->daysInMonth && $week > 0) {
// 保留完整 6 週高度,或 break 縮減
}
}
return $grid;
}
public function isToday(int $day): bool {
$today = new DateTime();
return $this->year === (int)$today->format('Y')
&& $this->month === (int)$today->format('m')
&& $day === (int)$today->format('j');
}
public function render(string $baseUrl = ''): string {
$grid = $this->getGrid();
$prevUrl = $this->getPrevMonthUrl($baseUrl);
$nextUrl = $this->getNextMonthUrl($baseUrl);
$title = $this->getTitle();
$html = '';
$html .= '';
$html .= '‹ ';
$html .= '' . htmlspecialchars($title) . ' ';
$html .= '› ';
$html .= ' ';
// 週標題
$weekdays = ['日', '一', '二', '三', '四', '五', '六'];
$html .= '';
foreach ($weekdays as $wd) {
$html .= '' . $wd . ' ';
}
$html .= ' ';
$html .= '';
foreach ($grid as $week) {
$html .= '';
foreach ($week as $dow => $day) {
$classes = [];
if ($day === null) {
$classes[] = 'empty';
$html .= ' ';
} else {
if ($this->isToday($day)) $classes[] = 'today';
if ($dow === 0 || $dow === 6) $classes[] = 'weekend';
$html .= '';
$html .= '' . $day . '';
$html .= ' ';
}
}
$html .= ' ';
}
$html .= '
';
return $html;
}
}
// 使用範例
$dateParam = $_GET['date'] ?? null;
$calendar = new SimpleCalendar($dateParam);
echo $calendar->render($_SERVER['PHP_SELF']);
?>
<style>
.calendar {
width: 100%;
max-width: 400px;
border-collapse: collapse;
font-family: system-ui, sans-serif;
margin: 1rem auto;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
border-radius: 8px;
overflow: hidden;
}
.calendar th, .calendar td {
padding: 0.5rem;
text-align: center;
border: 1px solid #eee;
}
.calendar thead th {
background: #f8f9fa;
font-weight: 600;
}
.calendar-title {
font-size: 1.1rem;
}
.weekdays th {
background: #e9ecef;
font-size: 0.85rem;
color: #495057;
}
.day-number {
display: inline-block;
width: 2rem;
height: 2rem;
line-height: 2rem;
border-radius: 50%;
}
.today .day-number {
background: #0d6efd;
color: white;
font-weight: bold;
}
.weekend .day-number {
color: #dc3545;
}
.empty {
background: #f8f9fa;
}
.calendar a {
text-decoration: none;
color: #0d6efd;
}
.calendar a:hover { text-decoration: underline; }
</style>
<?php
// 擴展類別加入事件資料
class EventCalendar extends SimpleCalendar {
private array $events = []; // ['YYYY-MM-DD' => [['title'=>'', 'color'=>''], ...]]
public function addEvent(string $date, string $title, string $color = '#0d6efd'): void {
$this->events[$date][] = ['title' => $title, 'color' => $color];
}
protected function renderDay(int $day): string {
$dateStr = sprintf('%04d-%02d-%02d', $this->year, $this->month, $day);
$dayEvents = $this->events[$dateStr] ?? [];
$html = '' . $day . '';
if ($dayEvents) {
$html .= '';
foreach ($dayEvents as $event) {
$html .= '';
}
$html .= '';
}
return $html;
}
}
?>
需引入農曆轉換庫(如 `phplunar`),在 `renderDay()` 中顯示農曆日期。
<?php
function render_simple_calendar(int $year = null, int $month = null): string {
$year ??= (int)date('Y');
$month ??= (int)date('m');
$firstDay = mktime(0, 0, 0, $month, 1, $year);
$startDow = (int)date('w', $firstDay);
$daysInMonth = (int)date('t', $firstDay);
$today = (int)date('j');
$isCurrentMonth = $year === (int)date('Y') && $month === (int)date('m');
$html = '';
$html .= '' . date('Y年n月', $firstDay) . ' ';
$html .= '日 一 二 三 四 五 六 ';
// 月初空白
for ($i = 0; $i < $startDow; $i++) $html .= ' ';
for ($day = 1; $day <= $daysInMonth; $day++) {
$dow = ($startDow + $day - 1) % 7;
$class = [];
if ($isCurrentMonth && $day === $today) $class[] = 'today';
if ($dow === 0 || $dow === 6) $class[] = 'weekend';
$html .= '' . $day . ' ';
if ($dow === 6) $html .= ' ';
}
$html .= '
';
return $html;
}
?>