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

PHP如何判断当前DateTime是否处于两个指定时间区间之外

问题分析与解决

核心问题

你写的反转逻辑存在两个关键问题:

  1. 语法错误:$Notification['beginTime' 缺少闭合方括号 ],会直接导致代码运行报错。
  2. 逻辑错误:一个时间不可能同时满足「小于开始时间」和「大于结束时间」,这两个条件是互斥关系,应该用**逻辑或(||)**而非逻辑与(&&)。

原逻辑回顾

原代码的逻辑规则是:

  • 当 currentDate 处于 beginTime 和 endTime 之间(不包含边界值)时,执行 error_log
  • 其余情况(即 currentDate 早于等于 beginTime,或晚于等于 endTime),执行 updateInternalNotification

正确的反转逻辑

如果要直接判断「当前时间在区间外」并执行 updateInternalNotification,正确的条件应该是当前时间早于开始时间,或者晚于结束时间,代码如下:

if ($currentDate < $Notification['beginTime'] || $currentDate > $Notification['endTime']) {
    updateInternalNotification();
}

如果业务需要把边界时间(等于 beginTime 或 endTime)也判定为区间外,可将比较符调整为 <= 和 >=:

if ($currentDate <= $Notification['beginTime'] || $currentDate >= $Notification['endTime']) {
    updateInternalNotification();
}

逻辑原理补充

从逻辑运算的角度,反转原条件等价于对原条件取反:
原条件:$Notification['beginTime'] < $currentDate && $Notification['endTime'] > $currentDate
根据德摩根定律取反后:$currentDate <= $Notification['beginTime'] || $currentDate >= $Notification['endTime']
和上面的正确逻辑完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 13:09:55