[英]PHP Carbon: How to get diffInDays if hours difference is less than 24 hours?
I'm having 2 different dates with less than 24 hours difference.我有 2 个不同的日期,相差不到 24 小时。 When I try to get difference in days I get 0
当我尝试在几天内有所不同时,我得到 0
$end = 2022-09-07 02:20:47
$now = 2022-09-06 16:00:00
$diffDays = $end ->diffInDays($now , false); // return 0
$diffDays = $now->diffInDays($end, false); // return 0
How to make detect that this is another day and should return diffInDays as 1 not 0如何检测这是另一天并且应该将 diffInDays 返回为 1 而不是 0
You can use diffInHours() < 24
, and you can also mix it with diffInMinutes < 60
.您可以使用
diffInHours() < 24
,也可以将其与diffInMinutes < 60
混合使用。 If it's either of those, then return 1. However, I would suggest dropping the absolute = false flag for doing that, as negative numbers will always hit those checks.如果是其中任何一个,则返回 1。但是,我建议为此删除 absolute = false 标志,因为负数总是会命中这些检查。
$end = Carbon::parse('2022-09-07 02:20:47') ;
$now = Carbon::parse('2022-09-06 16:00:00');
// These will return 10
$diffHours = $end->diffInHours($now);
$diffHours = $now->diffInHours($end);
// These return 620
$diffMinutes = $end->diffInMinutes($now);
$diffMinutes = $now->diffInMinutes($end);
This is because method signature looks like this:这是因为方法签名如下所示:
public function diffInDays(Carbon $dt = null, $abs = true)
{
$dt = $dt ?: static::now($this->getTimezone());
return (int) $this->diff($dt, $abs)->format('%r%a');
}
so it will round it to lower (0) if under 24 hours.因此,如果在 24 小时内,它将舍入到更低的 (0)。
Maybe you want try floatDiffInDays
instead to see different in decimal?也许您想尝试
floatDiffInDays
来查看十进制的不同? See sample below,请参阅下面的示例,
echo Carbon::parse('2000-01-01 12:00')->floatDiffInDays('2000-02-11 06:00'); // 40.75
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.