lara28580's avatar

Somehow diffInMinutes does not return negative numbers

I am trying to check dates with diffInMinutes but somehow I am not getting negative numbers if now() is bigger than given date. Someone can help?

@if(Carbon\Carbon::parse($event->ends_at)->diffInMinutes(now()->subMinutes(5), false) > 0)
            @php $time = $event->ends_at->diffInMinutes(now()->addMinutes(5)) @endphp
        @else
            @php $time = 0 @endphp
        @endif
0 likes
4 replies
LaryAI's avatar
Level 58

The issue is with the order of the subtraction. Instead of subtracting now() from the given date, subtract the given date from now(). This will give you a negative value if now() is greater than the given date. Here's the updated code:

@if(Carbon\Carbon::parse($event->ends_at)->diffInMinutes(now()->subMinutes(5), false) < 0)
    @php $time = now()->subMinutes(5)->diffInMinutes($event->ends_at) @endphp
@else
    @php $time = 0 @endphp
@endif

In this code, we first subtract 5 minutes from now() and then calculate the difference in minutes between the given date and the result. If the result is negative, we calculate the difference in minutes between the given date and now() minus 5 minutes.

MichalOravec's avatar
Level 75

From the docs:

The 2nd parameter again is optional and indicates if you want the return value to be the absolute value or a relative value that might have a - (negative) sign if the passed in date is less than the current instance. This will default to true, return the absolute value.

->diffInMinutes($event->ends_at, false)
1 like
Artwork's avatar

Indeed, thank you! The second parameter, in both the library and Laravel's implementations, stands for "absolute".

// Laravel 10.38.1
> $a = now();
> $b = now()->subDays(3);
> dump($a->diffInDays($b, true), $b->diffInDays($a, true));
= [ 2, 2 ]
> dump($a->diffInDays($b, false), $b->diffInDays($a, false));
= [ -2, 2 ]
Snapey's avatar

You can also use ->lt and ->gt on carbon instances if you just want a simple boolean and not the actual difference

1 like

Please or to participate in this conversation.