Laravel 5 Carbon global Locale

↘锁芯ラ 提交于 2019-11-30 02:36:22

问题


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


回答1:


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




回答2:


I configured it in the AppServiceProvider.

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

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



回答3:


in AppServiceProvider

public function register()
{

    // For example im gonna locale all dates to Indonesian (ID)
    config(['app.locale' => 'id']);
    \Carbon\Carbon::setLocale('id');
}

then to make locale output do something like this

// Without locale, the output gonna be like this    
Carbon\Carbon::parse('2019-03-01')->format('d F Y'); //Output: "01 March 2019"

// With locale
Carbon\Carbon::parse('2019-03-01')->translatedFormat('d F Y'); //Output: "01 Maret 2019"

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



来源:https://stackoverflow.com/questions/32549845/laravel-5-carbon-global-locale

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