php編寫日曆類
阿新 • • 發佈:2022-05-09
<?php /** * 日曆類 * Class Calendar * @author fengzi * @date 2022-05-05 15:42 */ class Calendar{ protected $table = ''; protected $year; protected $month; protected $day; protected $days; protected $currentDate; protected $space; protected $daysUp; protected $daysDown; function __construct() { date_default_timezone_set('PRC'); $this->year = isset($_GET['y']) ? $_GET['y'] : date('Y', time()); //變動的年份 $this->month = isset($_GET['m']) ? $_GET['m'] : date('n', time()); //變動的月份 if ( intval($this->month) > 12) {$this->month = 1; $this->year++; } if ( intval($this->month) < 1) { $this->month = 12; $this->year--; } $this->day = date('j', time()); //當月第幾天 $this->months = date('n', time()); //當前月份 $this->currentDate = $this->year." 年 ".$this->month." 月"; $this->space = date('w', mktime(0, 0, 0, $this->month, 1, $this->year)); //每月的 1號 是星期幾 $this->days = date("t",mktime(0,0,0,$this->month,1,$this->year));//得到給定的月份應有的天數 $this->daysUp = date("t",mktime(0,0,0,$this->month-1,1,$this->year));//得到給定的月份上一個月的應有的天數 $this->daysDown = date("t",mktime(0,0,0,$this->month+1,1,$this->year));//得到給定的月份下一個月的應有的天數 } //拼接表 protected function mosaicTable() { $this->table .= "<table><thead><tr align='center'><th colspan='7'>".$this->currentDate."</th></tr></thead>"; $this->table .= "<tbody><tr>"; $this->table .= "<td style='color:red;'>星期日</td>"; $this->table .= "<td>星期一</td>"; $this->table .= "<td>星期二</td>"; $this->table .= "<td>星期三</td>"; $this->table .= "<td>星期四</td>"; $this->table .= "<td>星期五</td>"; $this->table .= "<td style='color:red;'>星期六</td>"; $this->table .= "</tr>"; } //填日期 protected function fillingDate() { $this->table .= "<tr>"; //補足第一行前面淡色部分 $up = $this->daysUp - $this->space + 1; if ( (int)$this->space !== 0 ) { for ($i=0; $i < $this->space; $i++) { $this->table .= "<td style='color:#aaa;'>$up</td>"; $up++; } } $nums = $this->space; for ($i=1; $i <= $this->days; $i++) { if ( $nums % 7 != 0 ) { if ($i == (int)$this->day && $this->month == $this->months) { $this->table .= "<td style='color:red;'>$i</td>"; } else { $this->table .= "<td>$i</td>"; } } else { if ($i == (int)$this->day && $this->month == $this->months) { $this->table .= "</tr><tr><td style='color:red;'>$i</td>"; } else { $this->table .= "</tr><tr><td>$i</td>"; } } $nums++; } //補足最後一行後面淡色部分 $down = 6 - ($nums % 7) + 1; if ( ($nums % 7) != 0 ) { for ($i=1; $i <= $this->daysDown; $i++) { if ( $i > $down) { break; } $this->table .= "<td style='color:#aaa;'>$i</td>"; } } $this->table .= "</tr></tbody></table>"; } //增減月份 protected function increaseAndDecreaseMonth() { $this->table .= "<h3><a href='?y=".($this->year)."&m=".($this->month-1)."'>上一月</a> "; $this->table .= "<a href='?y=".($this->year)."&m=".($this->month+1)."'>下一月</a></h3>"; } //顯示日曆表 public function showTable() { $this->mosaicTable(); $this->fillingDate(); $this->increaseAndDecreaseMonth(); echo $this->table; } } $Calendar = new Calendar(); $Calendar->showTable();