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分支。
解决方式
有两种可行方案:
- 给
$startTime设置与用户相同的时区:
$startTime = $startTime->day($theirTime->day) ->month($theirTime->month) ->year($theirTime->year) ->setTimezone($timezone);
- 将两个时间统一转换为服务器默认时区(
Europe/London)后再比较:
if ($ourTime >= $startTime) { echo 'run now'; } else { echo 'do not run'; }
内容的提问来源于stack exchange,提问作者Ryan H
相关产品推荐
相关产品推荐

