Search code examples
phplaravelphp-carbon

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. 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.


Solution

  • 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);