php日歷是一個很簡單但很實用的函數,如果打算自己寫網站源代碼的朋友可以看看。筆者沒有添加樣式,盡量保持代碼的簡潔,如果需要美化,可自行添加css代碼^_^。輸出的效果如下:
<?php
function build_calendar($month,$year,$dateArray) {
// 日歷表頭,星期天開始一直到星期六
$daysOfWeek = array('S','M','T','W','T','F','S');
// 本月第一天的位置
$firstDayOfMonth = mktime(0,0,0,$month,1,$year);
// 獲取本月天數
$numberDays = date('t',$firstDayOfMonth);
// 獲取本月第一天
$dateComponents = getdate($firstDayOfMonth);
// 獲取月份的英文單詞
$monthName = $dateComponents['month'];
$dayOfWeek = $dateComponents['wday'];
// 月歷表頭
$calendar = "<table class='calendar'>";
$calendar .= "<caption>$monthName $year</caption>";
$calendar .= "<tr>";
// 星期表頭
foreach($daysOfWeek as $day) {
$calendar .= "<th class='header'>$day</th>";
}
// 開始輸出日歷
// 初始化天數計數器,從1號開始
$currentDay = 1;
$calendar .= "</tr><tr>";
// 使用變量 $dayOfWeek 可以保證一周七天精確輸出
if ($dayOfWeek > 0) {
$calendar .= "<td colspan='$dayOfWeek'> </td>";
}
$month = str_pad($month, 2, "0", STR_PAD_LEFT);
while ($currentDay <= $numberDays) {
// 7天一行,7天一到新增一行
if ($dayOfWeek == 7) {
$dayOfWeek = 0;
$calendar .= "</tr><tr>";
}
$currentDayRel = str_pad($currentDay, 2, "0", STR_PAD_LEFT);
$date = "$year-$month-$currentDayRel";
$calendar .= "<td class='day' rel='$date'>$currentDay</td>";
// 計數器
$currentDay++;
$dayOfWeek++;
}
// 最後一行表格的處理,往往最後一行不可能全部填滿,需要要空格填充。
if ($dayOfWeek != 7) {
$remainingDays = 7 - $dayOfWeek;
$calendar .= "<td colspan='$remainingDays'> </td>";
}
$calendar .= "</tr>";
$calendar .= "</table>";
return $calendar;
}
?>
<?php
$dateComponents = getdate();
$month = $dateComponents['mon'];
$year = $dateComponents['year'];
echo build_calendar($month,$year,$dateArray);
?>