PHP如何实现简单日历类编写?本篇文章小编给大家分享一下PHP实现简单日历类编写代码,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
代码如下:
calendar.class.php
year = isset($_GET['year'])?$_GET['year']:date("Y");
$this->month = isset($_GET["month"])?$_GET["month"]:date("m");
$this->first_week = date("w", mktime(0, 0 ,0, $this->month, 1, $this->year));
$this->day = date("t", mktime(0, 0 ,0, $this->month, 1, $this->year));
}
function showCalendar() {
// echo $this->year."年".$this->month."月".$this->first_week."天".$this->day;
echo "
"; //用表格输出
$this->chageDate("index.php"); //用于用户调整年月份
$this->weekList();//显示星期
$this->dayList(); //显示天数
echo "
";
}
//1、显示星期
private function weekList() {
$week = array("日","一","二","三","四","五","六");
echo "
";
for ($i = 0; $i < count($week); $i++) {
echo "".$week[$i]." | ";
}
echo "
";
}
//2.显示天数
private function dayList() {
$color = "#2ca50c";
echo "
";
for ($i = 0; $i < $this->first_week; $i++) { //输出空格,弥补当前月空缺部分
echo " | ";
}
for ($k = 1; $i <= $this->day; $k++) {
$i++;
if ($k == date("d")) echo "".$k." | "; //是今天,加效果
else echo "".$k." | ";
if ($i % 7 == 0) {
echo "
"; //每7天一次换行
if ($i % 2 == 0) $color = "#2ca50c";
else $color = "#9ddb27"; //实现各行换色的效果
}
}
while ($i % 7 != 0) { //将剩余的空格补完
echo " | ";
$i++;
}
echo "
";
}
//3、用于用户调整天数
private function chageDate($url="index.php") {
echo "
";
echo "".$this->year."年".$this->month."月
";
echo "
";
echo "
";
echo "".""."<"."";
echo " | ".""."<<"."";
echo " | ";
echo '";
echo '';
echo " | ";
echo ""."".">>"."";
echo " | "."".">"."";
echo " |
";
}
private function prevYear($year, $month) { //获取上一年的数据
$year--;
if ($year < 1970) $year = 1970;
return "year={$year}&month={$month}";
}
private function prevMonth($year, $month) {
if ($month == 1) {
$year--;
if ($year < 1970) $year = 1970;
$month = 12;
}else $month--;
return "year={$year}&month={$month}";
}
private function nextYear($year, $month) { //获取上一年的数据
$year++;
if ($year > 2038) $year = 2038;
return "year={$year}&month={$month}";
}
private function nextMonth($year, $month) {
if ($month == 12) {
$year++;
if ($year > 2038) $year = 2038;
$month = 1;
}else $month++;
return "year={$year}&month={$month}";
}
}
主页 index.php
日历显示
showCalendar();
?>