Reputation: 731
I'm trying to set the same global locale of laravel which is :
config('app.locale')
to work with Carbon.
It seems like you can do it by using either :
Carbon::setLocale('fr')
or
setlocale(LC_TIME, 'theLocale');
So I have tried using middleware or providers but was not successful.
(why is this not a default feature of laravel?)
Upvotes: 20
Views: 54886
Reputation: 1397
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
Upvotes: 43
Reputation: 426
I configured it in the AppServiceProvider.
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
// Localization Carbon
\Carbon\Carbon::setLocale(config('app.locale'));
}
}
Upvotes: 19
Reputation: 731
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
Upvotes: 28