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

PHP日期比较异常:当日日期匹配时误显示Past而非Ongoing

问题分析与修复方案

问题根源

你的代码里,new DateTime()会生成带当前时分秒的完整时间对象,但从数据库读取的start_date和end_date如果是纯年月日格式,转成DateTime后时间部分默认是00:00:00。当当前时间是当天非零点时刻(比如27-02-2023 10:30:00),$startDate(00:00:00)会被判定为小于$current_date,进入第一个分支;同时$endDate(00:00:00)也小于$current_date,最终返回Past,和预期不符。

修复方案

方案1:统一时间基准为当天零点

把当前日期设置为当天00:00:00,消除时分秒的干扰,同时简化判断逻辑:

$endDate = new DateTime($row['end_date']);
$startDate = new DateTime($row['start_date']);
$current_date = new DateTime('today'); // 等价于当天00:00:00

if ($endDate < $current_date) {
    $row["status"] = "Past";
} elseif ($startDate > $current_date) {
    $row["status"] = "Upcoming";
} else {
    $row["status"] = "Ongoing";
}

方案2:仅比较日期字符串(忽略时间)

如果不能修改当前时间的初始化方式,可以提取纯日期字符串进行比较:

$endDate = new DateTime($row['end_date']);
$startDate = new DateTime($row['start_date']);
$current_date = new DateTime();

// 提取YYYY-MM-DD格式的日期字符串
$startDateStr = $startDate->format('Y-m-d');
$endDateStr = $endDate->format('Y-m-d');
$currentDateStr = $current_date->format('Y-m-d');

if ($endDateStr < $currentDateStr) {
    $row["status"] = "Past";
} elseif ($startDateStr > $currentDateStr) {
    $row["status"] = "Upcoming";
} else {
    $row["status"] = "Ongoing";
}

逻辑说明

两种方案都优化了判断逻辑:

  • 先判断结束日期早于当前 → 标记Past
  • 再判断开始日期晚于当前 → 标记Upcoming
  • 其余情况(开始≤当前≤结束,或日期与当前同一天)均标记Ongoing

内容的提问来源于stack exchange,提问作者Taki Rajani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 09:24:56