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

PHP比较格式化日期字符串判断先后结果异常如何解决?

问题根因

异常由字符串字典序比对规则导致:你在比对前通过format()方法将DateTime对象转为了n-j-Y g:i A格式的字符串,PHP对字符串做大小比较时会逐字符比对ASCII值,和实际时间先后逻辑不匹配。
比如9-3-2021 11:28 AM和9-21-2021 9:57 PM比对时,第3位字符3的ASCII值大于2,会直接判定前者更大,就出现了9月3日被判定晚于9月21日的错误。

修复方案

方案1(最优推荐):直接比较DateTime对象

PHP的DateTime类已经内置了比较运算符的重载,不需要转成字符串即可直接比对时间先后,完全规避格式导致的比对错误,修正后代码如下:

<?php
$time_format = 'n-j-Y g:i A';
$time_zone = 'America/phoenix';
$timezone_obj = new DateTimeZone($time_zone);

// 直接保留DateTime对象,不转成字符串
$present_time = DateTime::createFromFormat($time_format, '9-3-2021 11:28 AM', $timezone_obj);
$end_time = DateTime::createFromFormat($time_format, '9-21-2021 9:57 PM', $timezone_obj);

if($present_time > $end_time) {
   echo 'Present time has pass the end time.';
} else {
     echo 'Present time has not pass the end time.';
}
?>

运行后会输出符合预期的Present time has not pass the end time.。

方案2:转成时间戳或有序格式字符串比对

如果业务逻辑需要先转成字符串处理,可以选择以下两种格式做比对,结果和时间先后一致:

  1. 转成Unix时间戳(整型):调用getTimestamp()方法获取整型时间戳后比对
  2. 转成Y-m-d H:i:s格式字符串:按年、月、日、时、分、秒顺序排列的字符串,字典序和时间先后完全匹配
    示例代码:
// 时间戳比对示例
$present_timestamp = $present_time->getTimestamp();
$end_timestamp = $end_time->getTimestamp();
if($present_timestamp > $end_timestamp) {
  // 自定义逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 03:39:03