使用 PHP 实现万年历功能的要点:
得到当前要处理的月份总共有多少天 $days
得到当前要处理的月份的一号是星期几 $dayofweek
$days 的作用: 知道要处理的月份共有多少天, 就可以通过循环输出天数了
$dayofweek 的作用: 只有知道每个月的 1 号是星期几, 才能知道在输出天数之前需要输出多少空格 (空白)
最终效果图如下:
万年历类的代码如下:
代码如下:
- /**
- * PHP 万年历
- * @author Fly 2012/10/16
- */
- class Calendar{
- protected $_table;//table 表格
- protected $_currentDate;// 当前日期
- protected $_year; // 年
- protected $_month; // 月
- protected $_days; // 给定的月份应有的天数
- protected $_dayofweek;// 给定月份的 1 号 是星期几
- /**
- * 构造函数
- */
- public function __construct()
- {
- $this->_table="";
- $this->_year = isset($_GET["y"])?$_GET["y"]:date("Y");
- $this->_month = isset($_GET["m"])?$_GET["m"]:date("m");
- if ($this->_month>12){// 处理出现月份大于 12 的情况
- $this->_month=1;
- $this->_year++;
- }
- if ($this->_month<1){// 处理出现月份小于 1 的情况
- $this->_month=12;
- $this->_year--;
- }
- $this->_currentDate = $this->_year.'年'.$this->_month.'月份';// 当前得到的日期信息
- $this->_days = date("t",mktime(0,0,0,$this->_month,1,$this->_year));// 得到给定的月份应有的天数
- $this->_dayofweek = date("w",mktime(0,0,0,$this->_month,1,$this->_year));// 得到给定的月份的 1 号 是星期几
- }
- /**
- * 输出标题和表头信息
- */
- protected function _showTitle()
- {
- $this->_table="
- ";
- $this->_table.="";
- $this->_table .="";
- $this->_table .="";
- $this->_table .="";
- $this->_table .="";
- $this->_table .="";
- $this->_table .="";
- $this->_table .="";
- $this->_table.="";
- }
- /**
- * 输出日期信息
- * 根据当前日期输出日期信息
- */
- protected function _showDate()
- {
- $nums=$this->_dayofweek+1;
- for ($i=1;$i<=$this->_dayofweek;$i++){// 输出 1 号之前的空白日期
- $this->_table.="";
- }
- for ($i=1;$i<=$this->_days;$i++){// 输出天数信息
- if ($nums%7==0){// 换行处理: 7 个一行
- $this->_table.="";
- }else{
- $this->_table.="";
- }
- $nums++;
- }
- $this->_table.="
- ".$this->_currentDate."
- 星期日 星期一 星期二 星期三 星期四 星期五 星期六
- $i
- $i
- ";
- $this->_table.="上一月";
- $this->_table.="下一月";
- }
- /**
- * 输出日历
- */
- public function showCalendar()
- {
- $this->_showTitle();
- $this->_showDate();
- echo $this->_table;
- }
- }
- $calc=new Calendar();
- $calc->showCalendar();
来源: https://www.php1.cn/detail/php-229191326c.html