How To Localize Formatted Dates with Laravel And Carbon

profile picture

How To Localize Formatted Dates with Laravel And Carbon

It's the second time in my carreer as a Laravel Developer that I had to struggle against this, so I decided to write the solution down for my future self πŸ˜…

First of all, here's what we are trying to achieve:

now()->format('F');

// expected : Janvier (french)

// result : January

The first thing to know is that when you're using ->format(), Carbon actually uses default PHP date formating, so you must tell PHP to use an available locale from the system.

To list all current locales on your system, simply type locale -a in your terminal.

To tell PHP to use on the avilable locale, you can simply add this line in your AppServiceProvider:

public function boot()
{
    setlocale(LC_TIME, 'fr_FR', 'fr', 'FR', 'French', 'fr_FR.UTF-8');
    Carbon::setLocale('fr'); // This is only needed to use ->diffForHumans()
}

Next, be careful about the ->format() method. It won't handle the localization. Instead, you must use ->formatLocalized().

BUT if you use ->formatLocalized(), you must use other parsing letters that are listed here.

And that's it!

now()->formatLocalized('%B');

// result : Janvier
laravel
locale
date
carbon

about me

profile picture

I consider myself as an IT Business Artisan. Or Consultant CTO. I'm a self-taught Web Developper, coach and teacher. My main work is helping and guiding digital startups.

more about me

follow me

newsletter

A weekly email with the latests articles

support my work

Start trading on binance
  • BTC

    BTC

    18SY81ejLGFuJ9KMWQu5zPrDGuR5rDiauM

  • ETH

    ETH

    0x519e0eaa9bc83018bb306880548b79fc0794cd08

  • Monero

    XMR

    895bSneY4eoZjsr2hN2CAALkUrMExHEV5Pbg8TJb6ejnMLN7js1gLAXQySqbSbfzjWHQpQhQpvFtojbkdZQZmM9qCFz7BXU

recent posts

QBUS - MQTT Quick Tutorial

1
11 months ago

DDOS By Web Crawlers

1
1 year ago

Something Given

1
1 year ago

2024 © My Dynamic Production SRL All rights Reserved.