Search code examples
laravelphp-carbon

Carbon: comparing date instances is giving unexpected result


This problem is driving me crazy.

Here is my Carbon instance:

$carbonTemp = CarbonImmutable::createFromFormat('Y-m-d', $date);

What I want to do is just to understand if the date here is the last day of the week.

$carbonTemp->equalTo($carbonTemp->endOfWeek())

If $date = '2021-08-08' which is the last day of this week, the result above must be true, right?

It is giving me FALSE !!

Even though $carbonTemp->endOfWeek()->format('Y-m-d') is giving me '2021-08-08'.


Solution

  • endOfWeek() returns last day of week and time 23:59:59.999999. Therefore it is necessary to use endOfDay() method when creating date.

    $carbonTemp = CarbonImmutable::createFromFormat('Y-m-d', $date)->endOfDay();