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

如何在PHP中准确比较两个时间?解决凌晨时间比较异常

问题原因与解决方案

你的问题出在strtotime()的默认行为上:当你只传入'1:30 AM'这类时间字符串时,它会自动拼接当前日期生成完整时间戳;而time()返回的是当前完整的日期时间戳,两者比较的是完整的日期时间,不是单纯的时间点先后。

比如当前是当天的00:15(12:15 AM),strtotime('1:30 AM')会生成当天01:30的时间戳,确实比当前大,这在同一天内是正确的,但如果你的需求是跨天比较(比如当前是凌晨,目标时间是前一天的),或者只想比较时间部分忽略日期,就会出现不符合预期的结果。

下面是两种针对性的解决方案:

方案一:只比较时间部分(忽略日期)

把两个时间都转换成当天0点到该时间的秒数,再进行比较,这样就只看几点几分的先后:

$current_time = time();
// 计算当前时间的当天秒数:当前时间戳减去当天0点的时间戳
$current_seconds = $current_time - strtotime('today');

$time1 = '1:30 AM';
// 计算目标时间的当天秒数
$target_seconds = strtotime($time1) - strtotime('today');

if ($current_seconds < $target_seconds) {
    echo 'Perfectos!';
}

也可以用更直观的字符串比较(24小时制字符串的字典序和时间先后一致):

$current_time_str = date('H:i', time());
$target_time_str = date('H:i', strtotime('1:30 AM'));

if ($current_time_str < $target_time_str) {
    echo 'Perfectos!';
}

方案二:处理跨天场景(比如当前是凌晨,目标时间为前一天)

如果你的逻辑是:凌晨时间段(比如00:00-06:00)的当前时间,要和前一天的目标时间比较,避免误判为未来时间,可以这样写:

$current_time = time();
$time1 = '10:50 AM';

// 判断当前是否在凌晨0点到6点之间
if (date('H', $current_time) < 6) {
    // 目标时间设为前一天的对应时间
    $draw_time = strtotime('yesterday ' . $time1);
} else {
    // 正常使用当天的目标时间
    $draw_time = strtotime($time1);
}

if ($current_time < $draw_time) {
    echo 'Perfectos!';
}

另外推荐使用PHP的DateTime类,代码可读性更高,也不容易出错:

$current_dt = new DateTime();
$target_dt = DateTime::createFromFormat('h:i A', '1:30 AM');
$today_start = new DateTime('today');

$current_seconds = $current_dt->getTimestamp() - $today_start->getTimestamp();
$target_seconds = $target_dt->getTimestamp() - $today_start->getTimestamp();

if ($current_seconds < $target_seconds) {
    echo 'Perfectos!';
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 17:50:24