briannesbitt / Carbon

A simple PHP API extension for DateTime.
https://carbon.nesbot.com/
MIT License
16.59k stars 1.28k forks source link

`CarbonInterval`'s `days` property return false #3018

Open daniser opened 6 months ago

daniser commented 6 months ago

Hello,

I encountered an issue with the following code:

echo (new \DateTime('2024-05-08'))->diff(new \DateTime('2024-05-11'))->days;

3

echo (new \Carbon\Carbon('2024-05-08'))->diff(new \Carbon\Carbon('2024-05-11'))->days;

false

Carbon version: 3.3.1

PHP version: 8.3.4

I expected to get:

3

But I actually get:

false

Thanks!

fxbt commented 6 months ago

Before the 3.0, the Carbon::diff method simply returned a \DateInterval but now there is an intermediate CarbonInterval object that is created with an interval_spec string.

As stated in the DateInterval phpdoc

If the DateInterval object was created by DateTimeImmutable::diff() or DateTime::diff(), then this is the total number of full days between the start and end dates. Otherwise, days will be false.

It's a problem for the days property, it's never set and unfortunately it can't be set manually. I tried a lot of things but I don't think there is an easy solution to handle this directly in the vendor

@daniser You can replace all the Carbon::diff in your code with the Carbon::diffAsDateInterval method to keep the same behaviour, or you can use the Carbon::diffInDays method but you'll get a float so don't forget to cast it if you need an integer

kylekatarnls commented 6 months ago

You can also use ->format('%a') instead of ->days it's got overridden recently to behave the same way it would with a diff DateInterval