Laravel 5 Carbon global Locale

So this is my bad, Carbon is actually using the php

setlocale();

the

Carbon::setLocale('fr')

method is only for the

->diffForHumans()

method. Notice that the php setlocale() reference to the locale stored on your OS to choose one of the installed one use

locale -a

on your console

secondly, you have to use

->formatLocalized()

method instead of

->format()

method

and lastly all the usefull methods like

->toDateString()
->toFormattedDateString()
->toTimeString()
->toDateTimeString()
->toDayDateTimeString()

are not being localized

and lastly you have to use these parsing letters

http://php.net/manual/en/function.strftime.php


Translating a carbon date using global localized format

Tested in: Laravel 5.8, Laravel 6, Laravel 8


In config/app.php

'locale' => 'id', // The default is 'en', but this time I want localize them to Indonesian (ID)

Then, to make locale output do something like this:

// WITHOUT LOCALE
Carbon\Carbon::parse('2019-03-01')->format('d F Y'); //Output: "01 March 2019"
now()->subMinute(5)->diffForHumans(); // Output: "5 minutes ago"

// WITH LOCALE
Carbon\Carbon::parse('2019-03-01')->translatedFormat('d F Y'); // Output: "01 Maret 2019"
now()->subMinute(5)->diffForHumans(); // Output: "5 menit yang lalu"

For more information about converting localize dates you can see on below link https://carbon.nesbot.com/docs/#api-localization


I configured it in the AppServiceProvider.

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // Localization Carbon

        \Carbon\Carbon::setLocale(config('app.locale'));
    }
}