php 实现日历

PHP 实现日历的方法
使用 PHP 可以轻松实现一个日历功能,以下是几种常见的实现方式:
基础日历实现
function generateCalendar($year, $month) {
$firstDay = mktime(0, 0, 0, $month, 1, $year);
$daysInMonth = date('t', $firstDay);
$firstDayOfWeek = date('w', $firstDay);
echo "<table border='1'>";
echo "<tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr>";
echo "<tr>";
for ($i = 0; $i < $firstDayOfWeek; $i++) {
echo "<td></td>";
}
$currentDay = 1;
while ($currentDay <= $daysInMonth) {
if (($currentDay + $firstDayOfWeek - 1) % 7 == 0 && $currentDay != 1) {
echo "</tr><tr>";
}
echo "<td>$currentDay</td>";
$currentDay++;
}
echo "</tr></table>";
}
generateCalendar(2023, 11);
使用 DateTime 类实现
function createCalendar($year, $month) {
$date = new DateTime("$year-$month-01");
$daysInMonth = $date->format('t');
$firstDay = $date->format('w');
echo "<table border='1'>";
echo "<tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr>";
echo "<tr>";
for ($i = 0; $i < $firstDay; $i++) {
echo "<td></td>";
}
$dayCount = 1;
while ($dayCount <= $daysInMonth) {
if (($dayCount + $firstDay - 1) % 7 == 0 && $dayCount != 1) {
echo "</tr><tr>";
}
echo "<td>$dayCount</td>";
$dayCount++;
}
echo "</tr></table>";
}
createCalendar(2023, 11);
带导航功能的日历
function calendarWithNavigation($year = null, $month = null) {
$currentYear = $year ?? date('Y');
$currentMonth = $month ?? date('m');
$prevMonth = $currentMonth - 1;
$prevYear = $currentYear;
if ($prevMonth < 1) {
$prevMonth = 12;
$prevYear--;
}
$nextMonth = $currentMonth + 1;
$nextYear = $currentYear;
if ($nextMonth > 12) {
$nextMonth = 1;
$nextYear++;
}
echo "<div style='text-align:center;'>";
echo "<a href='?year=$prevYear&month=$prevMonth'>Previous</a> ";
echo date('F Y', mktime(0, 0, 0, $currentMonth, 1, $currentYear));
echo " <a href='?year=$nextYear&month=$nextMonth'>Next</a>";
echo "</div>";
generateCalendar($currentYear, $currentMonth);
}
calendarWithNavigation($_GET['year'] ?? null, $_GET['month'] ?? null);
带事件标记的日历
function calendarWithEvents($year, $month, $events = []) {
$firstDay = mktime(0, 0, 0, $month, 1, $year);
$daysInMonth = date('t', $firstDay);
$firstDayOfWeek = date('w', $firstDay);
echo "<table border='1'>";
echo "<tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr>";
echo "<tr>";
for ($i = 0; $i < $firstDayOfWeek; $i++) {
echo "<td></td>";
}
$currentDay = 1;
while ($currentDay <= $daysInMonth) {
if (($currentDay + $firstDayOfWeek - 1) % 7 == 0 && $currentDay != 1) {
echo "</tr><tr>";
}
$dateKey = "$year-$month-$currentDay";
$eventMark = isset($events[$dateKey]) ? "<br><small>" . $events[$dateKey] . "</small>" : "";
echo "<td>$currentDay$eventMark</td>";
$currentDay++;
}
echo "</tr></table>";
}
$sampleEvents = [
'2023-11-15' => 'Meeting',
'2023-11-20' => 'Birthday'
];
calendarWithEvents(2023, 11, $sampleEvents);
这些方法提供了不同复杂程度的 PHP 日历实现,可以根据具体需求选择适合的方案或进行组合使用。







