How to localize dates in PHP with Laravel and Carbon

Getting localized dates in PHP and Laravel is quite easy once you know how it works. Just setting the locale in app/config.php seems not to do the trick.

Check the locales that your system has available with this command.

locale -a

The output will show you a list of installed locales, like this:

C
C.UTF-8
en_US.utf8
POSIX

If you are on Ubuntu it’s easy to install, in my case Swedish (sv):

sudo apt-get install language-pack-sv

In your app/Providers/AppServiceProvider.php

public function boot()
{
    setLocale(LC_TYPE, 'sv');
    Carbon::setLocale('sv');
}

Important to notice that Carbon::setLocale() is not enough, as you may first think, you need to set both.

If you first set the current locale with PHP function setlocale() then the string returned will be formatted in the correct locale.

diffForHumans() has also been localized. You can set the Carbon locale by using the static Carbon::setLocale() functio

https://carbon.nesbot.com/docs/#api-localization

Here is the format parameter string:
http://php.net/manual/en/function.strftime.php

A quick check if it works:

echo Carbon::now()->formatLocalized('%B'); // Output: juni

You can also use formatLocalized in your Blade-templates if you have defined the field as dates in your model.

Enjoy!