I'm facing a really weird issue with Carbon in laravel... i'm trying to get a specific date like this:
$now = Carbon::now()->setTimezone('America/Costa_Rica');
$currentYear = $now->copy()->year;
$febmon = $now->copy()->month(2)->startOfMonth();
dd($febmon);
It's supposed to return: 2018-02-01 00:00:00.0 America/Costa_Rica (-06:00)
But instead i'm getting this: 2018-03-01 00:00:00.0 America/Costa_Rica (-06:00)
I have already tried with all other month numbers, and works perfect but February... no idea what is wrong. Thanks in advance
Ok i found the issue, my mistake but if anyone is facing this simple but odd issue:
I'm basing the date depending on now()
and i'm setting the month(2)
before i set the startOfMonth()
And because today is 30 then it's passing to the next month in February, which is March since February doesn't have 30 days, all i had to do is set startOfMonth()
first... so it will take the right date.
Here is the right way:
$now = Carbon::now()->setTimezone('America/Costa_Rica');
$febmon = $now->copy()->startOfMonth()->month(2); //Specify the month at last, and set the startOfMonth() first.
dd($febmon);