Laravel Carbon localization not working (get local

2019-05-08 20:48发布

问题:

Using Laravel 5.3,

In my method I use

setlocale(LC_TIME, 'hr-HR');
dd(Carbon::now()->formatLocalized('%A'));

but I get Sunday instead of CroatianWordForSunday.

I tried using Carbon::setLocale('hr') instead setlocale() but I still get Sunday.

In my config/app.php file I have set 'locale' => 'hr'.

Thing to note is that Carbon's diffForHumans() method is successfully translated if I use Carbon::setLocale('hr').

In the end all I'm trying to do is convert number 8 to August but in Croatian. I could always just manually change January to Siječanj and so on but it would be nice if it could be done using some PHP's or Carbon's method to keep my code concise.

回答1:

Are you sure the hr_HR (and not hr-HR !) locale is installed on your system?

Supposing your server runs on an Unix environment, what do you see when you tape locale -a in a terminal?

If you do not see it, then you should try to install it first. Depending of your system, you could try:

$ sudo locale-gen hr_HR.UTF-8
$ sudo dpkg-reconfigure locales

According to the documentation of PHP strftime (Carbon is calling this function) :

This example will work if you have the respective locales installed in your system.

I succeeded to have the Carbon translation works in french using those lines in App\Providers\AppServiceProvider boot's method:

use Config;
use Carbon\Carbon;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        setlocale(LC_ALL, Config::get('app.lc_all'));
        Carbon::setLocale(Config::get('app.locale'));
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

With the following config settings :

// [...]
'locale' => env('APP_LOCALE', 'en'),
'lc_all' => env('APP_LC_ALL', 'en_US.UTF-8'), // Pay attention to the locale name!
// [...]

Then using the .env file :

APP_LOCALE = fr
APP_LC_ALL = fr_FR.UTF-8