Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ederson's avatar

Carbon : Avoid Month overflow

I ve spent the last couple of hours searching but i didn't find a solution on the following issue

i use CarbonPeriod and i cannot avoid the month overflow

ex: CarbonPeriod(Carbon::parse("31-1-2020),'1 month,'$from->addMonths(10)

i want to get the last day of every month till October but in February the date overflow to March so i get 31-1-2020 2-3-2020 2-4-2020 etc

I tried in AppServiceProvider Carbon::useMonthsOverflow(false); which didn't work

i think i am missing something here

0 likes
6 replies
bugsysha's avatar

Just iterate over and change integer passed to addMonths method.

now()->addMonths(2)->endOfMonth()->toDateString();

or

now()->addMonths(2)->endOfMonth()->format('d-m-Y'); // formatted as you presented
Snapey's avatar
Snapey
Best Answer
Level 122

can you adapt to use lastOfMonth ?

use 1st of month, add a month at a time, and get lastOfMonth()

ederson's avatar

@snapey I ended up doing something like this .... I get the start ofthe month and then compare the day i want to the end of the month and adjust it accordingly

Considering there is an option to avoid the overflow in Carbon i expected to have the same in CarbonPeriod. I don't like my solution that much tbh

Thanks @bugsysha and @snapey

gcwilliams's avatar

Not sure there is a way to globally set overflow to off. But this way works on the actual date object:

$dt = CarbonImmutable::createFromDate(2020, 1, 1)
  ->toPeriod('2020-10-30', 1, 'month')
  ->settings(['monthOverflow' => false]);

foreach ($dt as $date) {
  echo $date->firstOfMonth() . " - ". $date->endOfMonth() . "\n";
}

The big thing is you need to start from the first of the month and not from the 31st of January. That will always skip over Feb. even with overflow turned off.

ederson's avatar

I did not know the toPeriod() method ! Thanks @gcwilliams i will try this too cause it look cleaner than my solution

Please or to participate in this conversation.