I test the time around 2018-3-29~2018-3-31:
$month = Carbon::now()->subMonth(1);
the result is 3, but it should be 2.why this? Thanks
If today is 2018-03-29
SubMonth makes that 2018-02-29
2018 is not a leap year, so DateTime automatically corrects that to 2018-03-01
This is well-documented DateTime behavior that has existed for a very long time.
To fix this use:
$month = Carbon::now()->firstOfMonth()->subMonth();
Or use Carbon::useMonthsOverflow(false);
Read more here: http://carbon.nesbot.com/docs/#api-addsub
Or $month = Carbon::now()->subMonthsNoOverflow(1);
Most helpful comment
If today is 2018-03-29
SubMonth makes that 2018-02-29
2018 is not a leap year, so DateTime automatically corrects that to 2018-03-01
This is well-documented DateTime behavior that has existed for a very long time.