Laravel Carbon localization not working (get localized name of month from number)

流过昼夜 提交于 2019-12-07 07:04:55

问题


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


来源:https://stackoverflow.com/questions/40073696/laravel-carbon-localization-not-working-get-localized-name-of-month-from-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!