For those working with dates in Laravel, especially when adjusting by months or years where the day might overflow, Carbon’s subMonthNoOverflow
and addMonthNoOverflow
methods are indispensable. They ensure the month ends properly without spilling over into unexpected dates.
use Carbon\CarbonImmutable;
$date = CarbonImmutable::create(2024, 3, 31);
echo $date->addMonth();
// Outputs: 2024-03-02, because February only has 29 days
echo $date->addMonthNoOverflow();
// Outputs: 2024-02-29, stays at the end of the month
$date = CarbonImmutable::create(2024, 3, 31);
echo $date->subMonth();
// Outputs: 2024-3-2
echo $date->subMonthNoOverflow();
// Outputs: 2024-2-29, consistent as there's no overflow