Laravel and Carbon - DiffInDays If Statement
Asked Answered
H

2

16

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

Homogeneity answered 22/12, 2017 at 20:1 Comment(0)
G
39

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

Gasoline answered 22/12, 2017 at 20:4 Comment(2)
you're saving my day . . .Glandular
you are champion AlexeyTaphole
T
2

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.

Tamandua answered 22/12, 2017 at 20:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.