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

PHP中如何取日期范围无重叠判断逻辑的反逻辑?

如何反转日期范围无重叠的判断逻辑

嘿,我来帮你搞定这个逻辑转换的问题!首先咱们先明确你原代码的作用:

原条件if(strtotime($endDateA) <= strtotime(trim($startDateB)) or strtotime($startDateA) >= strtotime(trim($endDateB)))是用来判断两个日期范围完全无重叠的——要么A的结束时间早于/等于B的开始时间,要么A的开始时间晚于/等于B的结束时间,满足任一情况就说明没重叠。

现在你要取它的反逻辑,也就是判断两个日期范围存在重叠,这时候就得用到逻辑运算里的德摩根定律了:!(A or B) 等价于 !A and !B。简单说就是,对“或”条件取反,等于把每个条件分别取反,再用“与”连接起来。

咱们对应到你的代码里拆解一下:

  • 原条件里的第一个判断(A):strtotime($endDateA) <= strtotime(trim($startDateB)),取反后变成:strtotime($endDateA) > strtotime(trim($startDateB))
  • 原条件里的第二个判断(B):strtotime($startDateA) >= strtotime(trim($endDateB)),取反后变成:strtotime($startDateA) < strtotime(trim($endDateB))

然后把这两个取反后的条件用&&(PHP里的逻辑与,比and优先级更高,更推荐用)连接起来,就是你要的反逻辑代码了:

if (strtotime($endDateA) > strtotime(trim($startDateB)) && strtotime($startDateA) < strtotime(trim($endDateB))) {
    // 这里写两个日期范围有重叠时的处理逻辑
}

举个例子帮你理解:如果A是2024-01-01到2024-01-10,B是2024-01-05到2024-01-15,那A的结束时间(10号)大于B的开始时间(5号),同时A的开始时间(1号)小于B的结束时间(15号),满足条件,说明两个范围有重叠,这和实际情况一致。

另外提醒一下:PHP里or和||、and和&&的优先级不同,原代码用or没问题,但取反后的逻辑建议用&&,避免因优先级问题导致的意外错误哦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:58:51