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

This is how my app/Providers/AppServiceProvider.php looks like

public function boot()
{
    setlocale(LC_ALL, "sv_SE.UTF-8");
    Carbon::setLocale(config('app.locale')); // 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:

php artisan tinker
$date = Carbon\Carbon::now();
$date->formatLocalized('%B'); // Output: juni

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

Note the localzied dates does not use the same characters in the format parameter string.

Enjoy!