You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP日历函数无法自动更新当前月份与日期问题求助

问题修复方案

根因分析

  • 函数调用未设置默认动态参数:build_calendar需传入月份、年份参数,页面调用时大概率使用了写死的11月、2021年测试值,没有添加「无GET参数时自动读取当前系统时间」的逻辑,导致跨月后不会自动切换
  • 当日高亮逻辑遗漏:代码中仅给未来/当日的可预约日期添加了today类属性,若当日属于当月已过去的日期,today类不会被写入单元格标签,无法触发高亮

修复步骤

1. 修正页面调用逻辑

在你调用build_calendar的页面位置,替换原有调用代码为:

// 优先读取URL参数中的月年,无参数则取系统当前年月
$month = isset($_GET['month']) ? intval($_GET['month']) : date('m');
$year = isset($_GET['year']) ? intval($_GET['year']) : date('Y');
// 校验月份合法性,避免非法参数报错
$month = max(1, min(12, $month));
echo build_calendar($month, $year);

2. 修复函数内高亮逻辑

找到build_calendar函数内的日期渲染分支代码,修改为:

$today = $date==date('Y-m-d')? "today" : "";
if($date<date('Y-m-d')){
    // 过去日期也添加class属性,保证当日高亮正常生效
    $calendar.="<td class='$today'><h4>$currentDay</h4> <button class='btn btn-danger btn-xs'>N/A</button>";
}else{
    $calendar.="<td class='$today'><h4>$currentDay</h4> <a href='book.php?date=".$date."' class='btn btn-success btn-xs'>Book</a>";
}

3. 可选样式补充

如果还未配置高亮样式,在CSS中添加如下代码即可实现当日高亮效果:

.today {
    background-color: #e3f2fd;
    border: 2px solid #2196f3;
}

内容的提问来源于stack exchange,提问作者tea-codes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 02:54:08