Carbon get current and last month name

Published 11 months ago by Lars-Janssen

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 Lars-Janssen)
Cronix
$date = \Carbon\Carbon::now();
echo $date->format('F'); // July
echo $date->subMonth()->format('F'); // June
topvillas
Cronix
Cronix
11 months ago (481,440 XP)
$date = \Carbon\Carbon::now();
echo $date->format('F'); // July
echo $date->subMonth()->format('F'); // June
Lars-Janssen

@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
11 months ago (897,155 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
11 months ago (481,440 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.

dozGrou

That might be a bit late, but to use format in blade you should use formatLocalized()

Please sign in or create an account to participate in this conversation.