Carbon get current and last month name

Published 1 week ago by lars6

Hi,

How would I get the current and last month fully written.

For example:

Januari

With carbon?

Already tried things like this:

{{ \Carbon\Carbon::now()->toFormattedDateString() }}

But that gives me more then only the month name.

Thanks

Best Answer (As Selected By lars6)
Cronix
$date = \Carbon\Carbon::now();
echo $date->format('F'); // July
echo $date->subMonth()->format('F'); // June
topvillas
Cronix
Cronix
1 week ago (118,990 XP)
$date = \Carbon\Carbon::now();
echo $date->format('F'); // July
echo $date->subMonth()->format('F'); // June
lars6
lars6
1 week ago (77,415 XP)

@topvillas @Cronix

Thanks, for some reason the locale is wrong in my blade files.

I've this in the boot method of my AppServiceprovider:

Carbon::setLocale('nl');

But I receive the default english translation.

In my controllers this is working correctly.

Any idea?

Snapey
Snapey
1 week ago (556,035 XP)

Can't help you with the locale issue, but beware, there is an issue with subMonth

Check this in tinker

>>> $dt=\Carbon\Carbon::parse('2017-03-30')
=> Carbon\Carbon {#707
     +"date": "2017-03-30 00:00:00.000000",
     +"timezone_type": 3,
     +"timezone": "UTC",
   }
>>> $dt->subMonth()
=> Carbon\Carbon {#707
     +"date": "2017-03-02 00:00:00.000000",
     +"timezone_type": 3,
     +"timezone": "UTC",
   }
>>>

Set the date to 30th March, subtract a month. February does not have 30th so date is set to 2nd March. In your case this and previous month could be the same

This is a known issue with the PHP DateTime class

better to adjust current month to the 1st and then subMonth

Cronix
Cronix
1 week ago (118,990 XP)

@Snapey good point on the broken php datetime stuff. I keep forgetting that long standing bug.

$date = Carbon::now();

echo $date->format('F'); // July
echo $date->startOfMonth()->subMonth()->format('F'); // June

//

$date = Carbon::parse('2017-03-30');

echo $date->format('F'); // March
echo $date->startOfMonth()->subMonth()->format('F'); // February

@lars6 I'm sorry, I don't know why blade is doing that. I've never needed to use locale in Laravel.

Sign In or create a forum account to participate in this discussion.