Getting Incorrect value of submonth in carbon
Asked Answered
M

1

9

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 
Millenary answered 30/4, 2021 at 5:33 Comment(0)
I
13

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.

Impressionist answered 30/4, 2021 at 5:51 Comment(1)
Side note to say, such overflow can sound weird but it's pretty standard, you'll get the same results with date functions in Java, JavaScript, etc.Gnathion

© 2022 - 2024 — McMap. All rights reserved.