PHP如何判断当前DateTime是否处于两个指定时间区间之外
问题分析与解决
核心问题
你写的反转逻辑存在两个关键问题:
- 语法错误:
$Notification['beginTime'缺少闭合方括号],会直接导致代码运行报错。 - 逻辑错误:一个时间不可能同时满足「小于开始时间」和「大于结束时间」,这两个条件是互斥关系,应该用**逻辑或(
||)**而非逻辑与(&&)。
原逻辑回顾
原代码的逻辑规则是:
- 当
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
相关产品推荐
相关产品推荐

