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

Carbon PHP中>=比较未返回true的问题排查

问题:Carbon PHP 2日期时间比较不符合预期

我正在使用Carbon PHP 2进行日期时间比较。背景:服务器时区为Europe/London,用户可自行设置时区(即$timezone变量),Laravel 8项目默认时区同样为Europe/London。
用户提供的开始时间存储在数据库日期字段中,但代码运行时该时间的年月日信息不正确,因此将其覆盖为当前日期。
从输出可见用户时间大于开始时间,但if语句始终未执行,请问原因是什么?

代码示例

$timezone = 'Asia/Tokyo';

$startTime = Carbon::parse('2022-08-01 05:00:00');
$theirTime = Carbon::parse(Carbon::now())->setTimezone($timezone);
$ourTime = Carbon::parse($theirTime)->setTimezone('Europe/London');     

$startTime = $startTime->day($theirTime->day);
$startTime = $startTime->month($theirTime->month);
$startTime = $startTime->year($theirTime->year);

echo "their time: $theirTime ----- start: $startTime";

if ($theirTime >= $startTime) {
  echo 'run now';
} else {
  echo 'do not run';
}

输出结果

their time: 2022-08-05 05:16:27 ----- start: 2022-08-05 05:00:00do not run

原因分析与解决方法

问题核心是两个时间对象的时区不一致,导致表面显示的时间看似符合条件,但实际对应的UTC时间存在差异:

  • $theirTime是Asia/Tokyo时区的2022-08-05 05:16:27,对应UTC时间为2022-08-04 20:16:27
  • 修改后的$startTime仅调整了年月日,仍保留默认的Europe/London时区(当时处于夏令时,UTC+1),对应UTC时间为2022-08-05 04:00:00

实际UTC时间对比中,2022-08-04 20:16:27早于2022-08-05 04:00:00,因此$theirTime >= $startTime的判断结果为false,执行了else分支。

解决方式

有两种可行方案:

  1. 给$startTime设置与用户相同的时区:
$startTime = $startTime->day($theirTime->day)
    ->month($theirTime->month)
    ->year($theirTime->year)
    ->setTimezone($timezone);
  1. 将两个时间统一转换为服务器默认时区(Europe/London)后再比较:
if ($ourTime >= $startTime) {
  echo 'run now';
} else {
  echo 'do not run';
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 08:25:02