Carbon: 馃悰 Carbon Interval is giving me wrong output when using week and day together

Created on 18 May 2020  路  4Comments  路  Source: briannesbitt/Carbon


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!

bug

All 4 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kylekatarnls picture kylekatarnls  路  5Comments

rohstar picture rohstar  路  4Comments

MaxGiting picture MaxGiting  路  4Comments

dboyadzhiev picture dboyadzhiev  路  4Comments

joomartin picture joomartin  路  4Comments