利用 PHP 构建万年历功能主要涉及两个关键步骤:
• 计算当前目标月份包含的总天数 $days
• 确定当前目标月份的第一天是星期几 $dayofweek
$days 变量的用途:明确当月总天数后,即可通过循环结构逐日输出。
$dayofweek 变量的用途:知晓每月1号对应的星期数值,才能计算出在正式输出日期前需预留的空格数量(即空白占位)。最终生成的界面效果如下图所示:

以下是“万年历类”的具体实现代码:
<?php/**
* 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->_currentDate." | ||||||
|---|---|---|---|---|---|---|
| 星期日 | 星期一 | 星期二 | 星期三 | 星期四 | 星期五 | 星期六 |
| $i | ||||||
";
$this->_table.="_year)."&m=".($this->_month-1)."'>上一月 "; $this->_table.="_year)."&m=".($this->_month+1)."'>下一月
";
}
/**
* 输出日历
*/
public function showCalendar()
{
$this->_showTitle();
$this->_showDate();
echo $this->_table;
}
}
$calc=new Calendar();
$calc->showCalendar();出处:http://www.cnblogs.com/hongfei