Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 Carbon global Locale

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?)

like image 372
Mathieu Urstein Avatar asked Sep 13 '15 12:09

Mathieu Urstein


People also ask

How do I change my locale in Laravel?

Laravel's gives you the option to change the locale for a single Http Request by executing the setLocale method on App Facade App::setLocale($locale); , But what if once the language is changed you don't want to worry about setting the Locale and this should be taken care by an automatic code logic.

Is Carbon included in Laravel?

In order to use Carbon, you'll need to import Carbon from the Carbon namespace. Luckily for us, Carbon is already included in Laravel.

What is Nesbot Carbon?

An API extension for DateTime that supports 281 different languages.


1 Answers

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

like image 182
Robby Alvian Jaya Mulia Avatar answered Oct 02 '22 07:10

Robby Alvian Jaya Mulia