I'm having 2 different dates with less than 24 hours difference. When I try to get difference in days I get 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
CodePudding user response:
You can use diffInHours() < 24
, and you can also mix it with 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.
$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);
CodePudding user response:
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.
Maybe you want try floatDiffInDays
instead to see different in decimal?
See sample below,
echo Carbon::parse('2000-01-01 12:00')->floatDiffInDays('2000-02-11 06:00'); // 40.75