Home >Backend Development >PHP Tutorial >PHP Practice: Calendar (Simple Code, Easy to Expand)_PHP Tutorial
I took the time to write a calendar program, focusing only on functions and implementation ideas, so the code and functions are relatively simple, but it is also easier to understand and expand.
The show() function is used to display the calendar. You can modify the show() function to display different years and months by passing values.
<?php class Calendar{ public $weekarray = array('星期日','星期一','星期二','星期三','星期四','星期五','星期六'); public $firstDay = '';//当月第一天 public $firstNum = '';//返回当月第一天对应的星期数字 public $firstDayNum = '';//当月第一天对应的中文星期 /** * 指定日是星期几 * eg:$date='2014-07-21' */ public function getWeek($date){ $date = strtotime($date);//strtotime() 函数将任何英文文本的日期时间描述解析为 Unix 时间戳 $num = date('w',$date);//数字型的星期几,如: "0" (星期日) 至 "6" (星期六) return $num; } /** * 取得指定月有多少天 * eg:$month = '2014-07' */ public function getMonthNum($month){ $month = strtotime($month); return date('t',$month);//指定月份的天数 } /** * 显示日历 */ public function show(){ //取得当前日期 $year = date('Y'); $month = date('m'); $day = date('d'); echo '<table border="1" style="text-align:center;">'; echo '<tr><td colspan="7">'.$year.'-'.$month.'</td></tr>'; echo '<tr><th>星期日</th><th>星期一</th><th>星期二</th><th>星期三</th><th>星期四</th><th>星期五</th><th>星期六</th></tr>'; //取得当前月有多少天 $yearMonth = '$year."-".$month'; $monthNum = $this->getMonthNum($yearMonth); //取得当前月第一天是星期几 $this->firstDay = $year."-".$month."-01"; $this->firstNum = $this->getWeek($this->firstDay); $this->firstDayNum = $this->weekarray[$this->firstNum]; echo '<tr>'; for($i=1;$i<=$monthNum+($this->firstNum);$i++){ echo '<td>'; if($i >= $this->firstNum+1){ $a = $i-$this->firstNum; if($a == $day){ echo '<div style="background-color:blue;color:#fff;">'.$a.'</div>'; }else{ echo '<div>'.$a.'</div>'; } } echo '</td>'; if($i%7 == 0){//每输出7列就换一行 echo '</tr>'; } } echo '</table>'; } } $calendar = new Calendar(); $calendar->show();
Rendering:
Usage of PHP date() function
Here is a detailed explanation of the date() function: http://wenku.baidu.com/link?url=OPDGzaCMWgjDE0ya8QlDbLIXX0c11ohUjsoLyRm-cYp7lz-O_7H4XBILv8JfomhbnSxXSW0FhqxYBK0_gn8Nr77XMWp-_st7v8AYecbNZjG