Laravel and Carbon - DiffInDays If Statement

Matthew picture Matthew · Dec 22, 2017 · Viewed 8.8k times · Source

I think I have a relatively simple question, I just think I'm misunderstanding an aspect of it.

I have an index page where in one of the table cells I have an if statement:

 @if (Carbon\Carbon::parse($shipment->due_date)->diffInDays(false) > 0 && Carbon\Carbon::parse($shipment->due_date)->diffInDays(false) < 10)

Where the falses are is where I would like to declare that if the day is in the future, say like tomorrow compared to today, I will have a -1 returned, whereas if I refer to yesterday, I will have a 1 returned.

The problem is I am trying to use the docs but they are lining up for me no matter what sort of way I try them: http://carbon.nesbot.com/docs/#api-humandiff

However I should mention that on the same layout I can do this:

{{Carbon\Carbon::parse($shipment->due_date)->diffInDays()}}

and return the number of days in the past or future (even though both are positive) so I know the above works (in a way, but I still need the positive or negative mentioned).

Answer

Alexey Mezenin picture Alexey Mezenin · Dec 22, 2017

You need to provide a Carbon date as the first parameter for diffInDays(). So, the logic will be:

Carbon\Carbon::parse($shipment->due_date)->diffInDays(now(), false)

Or:

now()->diffInDays(Carbon\Carbon::parse($shipment->due_date), false)

Depending on what exactly you're trying to achieve.

false as the second parameter makes the method return signed value (positive or negative).