<html>
<meta charset="UTF-8">
<title>日历</title>
<body>
<form action="index.php" method="get">
<table>
<tr>
<!-- 日期头 -->
<th>日</th>
<th>一</th>
<th>二</th>
<th>三</th>
<th>四</th>
<th>五</th>
<th>六</th>
</tr>
<?php
include "calendar.php";
?>
<tr>
<th><input type="submit" value="<" name="yeardown" style="border:none;background:none;cursor:pointer;outline:none;">
<input type="hidden" value="<?php echo $year?>" name="year"></th>
<th colspan="2"><?php echo $year?></th>
<th><input type="submit" value=">" name="yearup" style="border:none;background:none;cursor:pointer;outline:none;"></th>
<th><input type="submit" value="<" name="monthdown" style="border:none;background:none;cursor:pointer;outline:none;"></th>
<th><?php echo $month?></th>
<th><input type="submit" value=">" name="monthup" style="border:none;background:none;cursor:pointer;outline:none;">
<input type="hidden" value="<?php echo $month?>" name="month"></th>
</tr>
</table>
</form>
</body>
</html>
<?php
//先获取日期
if(isset($_GET['yeardown'])){ //年减少,年份往前推
$year=$_GET['year']-1;
$month=$_GET['month'];
$today=date("d");
}
else if(isset($_GET['yearup'])){ //年增加,年份往后推
$year=$_GET['year']+1;
$month=$_GET['month'];
$today=date("d");
}
else if(isset($_GET['monthdown'])){ //月减少,月份往前推
$year=$_GET['year'];
$month=$_GET['month']-1;
$today=date("d");
if ($month==0){ //遇到零月,年份减1,月份变12
$month=12;
$year--;
}
}
else if(isset($_GET['monthup'])){ //月增加,月份往后推
$year=$_GET['year'];
$month=$_GET['month']+1;
$today=date("d");
if ($month==13){ //月变为13时,年加1,月变为1
$month=1;
$year++;
}
}
else{ //一开始没有传参时,获取当前年月日
$year=date("Y");
$month=date("m");
$today=date("d");
}
$date=$year."-".$month."-1"; //将日期设为该月第一天
$day = date("w",strtotime($date));//查看该月第一天为周几
$dateArray = array(array());
$dateNew = array();
for ($i=0;$i<6;$i++){ //将日期都初始化为-1
for ($j=0;$j<7;$j++){
$dateArray[$i][$j]=-1;
}
}
$monthday=31; //大月31天
if ($month==4||$month==6||$month==9||$month==11){ //平月30天
$monthday=30;
}
if ($month==2){ //二月单独判断
$monthday=28;
if ($year%4==0&&$year%100!=0||$year%400==0){
$monthday=29;
}
}
for ($i=0;$i<42;$i++){ //初始化二维数组为-1
$dateNew[$i]=-1;
}
for ($i=$day;$i<$day+$monthday;$i++){ //日期对应的一维数组根据1号是周几往后推
$dateNew[$i]=$i-$day+1;
}
$k=0;
for ($i=0;$i<6;$i++){ //-1为空不显示
echo "<tr>";
for ($j=0;$j<7;$j++){ //其他日期挨个打印
$dateArray[$i][$j] = $dateNew[$k];
$k++;
if ($dateArray[$i][$j]==-1){ //没显示的天打印空
if($i==5&$j==0) //最后一行为空的时候不打印
break;
echo "<td></td>";
}
else{//当天的背景为绿色
if ($year==date("Y")&&$month==date("m")&&$dateArray[$i][$j]==date("d"))
echo "<td align='center' bgcolor='#7fff00'>".$dateArray[$i][$j]."</td>";
else
echo "<td align='center'>".$dateArray[$i][$j]."</td>";
}
}
echo "</tr>";
}
?>
运行效果如图

也可以访问php简单日历
本文详细介绍了一款基于PHP的自定义日历插件的实现过程。通过解析HTML和PHP代码,展示了如何创建一个可交互的日历,允许用户通过按钮控制年份和月份的切换。此外,还解释了如何根据当前日期高亮显示特定日期。
5019

被折叠的 条评论
为什么被折叠?



