Search code examples
phplaravelphp-carbon

Getting Incorrect value of submonth in carbon


Please go through the below code

Why getting 3rd month two times instead of 2nd month. Code

('current ' . Carbon::now()->format('Y-m-d'));//2021-04-30
('sub 1 -'.Carbon::now()->subMonths(1)->format('Y-m-d'));
('sub 2 -'.Carbon::now()->subMonths(2)->format('Y-m-d'));
('sub 3 -'.Carbon::now()->subMonths(3)->format('Y-m-d'));

Result

current 2021-04-30
sub 1 - 2021-03-30 
sub 2 - 2021-03-02 
sub 3 - 2021-01-30 

Expected Result

current 2021-04-30 
sub 1 - 2021-03-30 
sub 2 - 2021-02-02 
sub 3 - 2021-01-30 

Solution

  • This is actually expected behaviour for Carbon. Carbon uses the PHP DateTime class, and there can be overflow from the addition and subtraction functions.

    sub 2 - 2021-03-02 is actually being calculated by the date 2021-02-30, which doesn't exist, therefore overflowing to 2021-03-02.

    Take a look here to see the effects https://carbon.nesbot.com/docs/#api-addsub

    To fix this behaviour, you can use the addMonthNoOverflow, addMonthsNoOverflow, subMonthNoOverflow and subMonthsNoOverflow methods.