Carbon升级后diffInSeconds()返回负值,运算顺序是否变更?
Carbon 3.x 中 diffInSeconds() 运算顺序变更说明
是的,Carbon 3.x 对 diffInSeconds() 这类时间差值方法的运算逻辑做了明确变更。
在 Carbon 2.x 版本中,$time_after->diffInSeconds($time_before) 的计算逻辑是 当前实例($time_after)减去传入参数($time_before),因此当 $time_after 晚于 $time_before 时,会得到正值结果。
而升级到 Carbon 3.x 后,这类差值方法的默认逻辑变为 传入参数减去当前实例,也就是等同于 Carbon 2.x 中 $time_before->diffInSeconds($time_after) 的效果,所以当 $time_after 晚于 $time_before 时,会返回负值。
解决方法
- 调换参数顺序:将代码改为
$time_before->diffInSeconds($time_after),恢复 2.x 时期的正值结果逻辑 - 使用绝对值参数:调用方法时传入第二个参数
true,直接获取差值的绝对值,不受顺序影响:
$time_before = Carbon::now(); // << call that takes 85 s >> $time_after = Carbon::now(); $duration_in_secs = $time_after->diffInSeconds($time_before, true);
内容的提问来源于stack exchange,提问作者Pete
相关产品推荐
相关产品推荐

