Hello,
Carbon version: 2.34.0
PHP version: 7.4.3
I encountered an issue with the following code:
echo CarbonInterval::week(3)->days(3)->totalDays;
I expected to get:
24
But I actually get:
3
And then.
echo CarbonInterval::days(3)->week(3)->totalDays;
I expected to get:
24
But I actually get:
21
Thanks!
Hi,
I understand your point. I'm not sure to be able to fix it as week is a bit different than other units. All other units come from the inherited DateInterval while week is actually a wrapper for days * 7 just available as an helper to compose days-intervals. That means: CarbonInterval::week(3)->days(3) currently trigger CarbonInterval::days(3 * 7)->days(3) which set days count, then change days count.
To fix it we would have to store weeks in a duplicated field. And the new behavior may have unexpected consequences on existing applications. I must check it carefully.
Meanwhile, I recommend to use:
<?php
echo CarbonInterval::weeks(3)->add(3, 'days')->totalDays;
->add() will even work when supplying twice the same unit in the chain with no ambiguity.
Else there is daysExcludeWeeks:
echo CarbonInterval::weeks(3)->daysExcludeWeeks(3)->totalDays;
Meanwhile, I recommend to use:
<?php echo CarbonInterval::weeks(3)->add(3, 'days')->totalDays;
->add()will even work when supplying twice the same unit in the chain with no ambiguity.
Thanks for the recomendation.
Quick note to mention the new PHP 8 syntax that can be convenient here:
new CarbonInterval(years: 0, weeks: 3, days: 3)
With Carbon 2, you need to pass explicitly "0 years" because default interval is 1 year.
But with Carbon 3, default interval will become 0 seconds and so 3 weeks + 3 days can be created with:
new CarbonInterval(weeks: 3, days: 3)
I think this is the syntax we'll highlight in documentation for Carbon 3 and will simply promote it over chaining syntax.
New method will be available in 2.45:
echo CarbonInterval::week(3)->addDays(3)->totalDays;
See more on #2281