这里是一个使问题更清楚的例子。以下两个示例给出了错误的区别:
// 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:59
与00:00:01
相比返回2秒的差,并且00:00:01
与23:59:59
比较。
很遗憾,您需要将它们转换为日期时间。 php如何知道23:59:59和00:00:01不在同一天发生?
您需要做的是将两个变量都赋值,并查看第二次是否在第一次之前。如果是这样,请增加一天。然后检查差异:
$date1 = Carbon::parse('23:59:59');
$date2 = Carbon::parse('00:00:01');
if($date2->lt($date1)) {
$date2->addDay();
}
$date2->diffInSeconds($date1); // 2