Search code examples
phplaravelphp-carbon

PHP Carbon diffInDays false did not return negative


So I have to calculate the dif of date between two dates. One of the result should be in negative but it doesn't work as it return positive. Here my code.

My table data

$date1 = "2016-09-17"
$date2 = "2016-08-23"

My blade

@foreach($table as $row)
   <td>{{ $row->date1 }}</td>
   <td>{{ $row->date2}}</td>
   <td>{{ Carbon::parse($row->date2)->diffInDays(Carbon::parse($row->date1),false) + 1 }}</td>
@endforeach

Guide and help will be appreciated.


Solution

  • Assuming that the problem occurs when comparing the two dates provided, I can see why the error occurs.

    diffInDays calculates the "distance in days" from the left value, to the provided value, so:

    The difference between date2 and date1 is in fact positive. From 2016-08-23 to 2016-09-17 there is a positive amount of days into the future. However, if you would to flip the order of date2 and date1, you would get the result you want.

    Try:

    Carbon::parse($row->date1)->diffInDays(Carbon::parse($row->date2),false) + 1 }}