Laravel 5 Carbon global Locale

前端 未结 3 1146
有刺的猬
有刺的猬 2020-12-10 12:28

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 d

相关标签:
3条回答
  • 2020-12-10 13:07

    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

    0 讨论(0)
  • 2020-12-10 13:11

    I configured it in the AppServiceProvider.

    class AppServiceProvider extends ServiceProvider
    {
        public function boot()
        {
            // Localization Carbon
    
            \Carbon\Carbon::setLocale(config('app.locale'));
        }
    }
    
    0 讨论(0)
  • 2020-12-10 13:14

    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

    0 讨论(0)
提交回复
热议问题