Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel and Carbon - DiffInDays If Statement

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

like image 872
Matthew Avatar asked Dec 22 '17 20:12

Matthew


People also ask

Does Carbon come with Laravel?

Luckily for us, Carbon is already included in Laravel.


2 Answers

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

like image 175
Alexey Mezenin Avatar answered Sep 22 '22 14:09

Alexey Mezenin


You can use:

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

in place of

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

This is becuase 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');
}

In addition looking at your logic I think it's too complicated. I think it would be enough to use:

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

the first condition is not necessary I believe

Also in case you are using Laravel 5.5 you should rather use:

Illuminate\Support\Carbon

instead of

Carbon\Carbon

in case you wanted to add some custom methods to this class.

like image 23
Marcin Nabiałek Avatar answered Sep 19 '22 14:09

Marcin Nabiałek