[如何在PHP中计算2次(而非日期时间)正好之间的秒数差。 Laravel // PHP //碳

问题描述 投票:0回答:2

这里是一个使问题更清楚的例子。以下两个示例给出了错误的区别:

// gives 86398 while the correct is 2sec
$diff_in_sec = strtotime('23:59:59') - strtotime('00:00:01'); 

// again gives 86398 while the correct is 2sec.
$diff_in_sec = Carbon::parse('00:00:01')->diffInSeconds(Carbon::parse('23:59:59')); 

我想要的是23:59:5900:00:01相比返回2秒的差,并且00:00:0123:59:59比较。

php laravel time difference
2个回答
2
投票

很遗憾,您需要将它们转换为日期时间。 php如何知道23:59:59和00:00:01不在同一天发生?


0
投票

您需要做的是将两个变量都赋值,并查看第二次是否在第一次之前。如果是这样,请增加一天。然后检查差异:

$date1 = Carbon::parse('23:59:59');
$date2 = Carbon::parse('00:00:01');
if($date2->lt($date1)) {
   $date2->addDay();
}

$date2->diffInSeconds($date1); // 2
© www.soinside.com 2019 - 2024. All rights reserved.