php Laravel 5 Carbon 全球语言环境

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32549845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:03:22  来源:igfitidea点击:

Laravel 5 Carbon global Locale

phplaravelphp-carbon

提问by Mathieu Urstein

I'm trying to set the same global locale of laravel which is :

我正在尝试设置 Laravel 的相同全局语言环境,即:

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

(为什么这不是 laravel 的默认功能?)

回答by Mathieu Urstein

So this is my bad, Carbon is actually using the php

所以这是我的坏处,Carbon 实际上使用的是 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

方法。请注意,php setlocale() 引用存储在您的操作系统上的语言环境以选择已安装的一种使用

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

http://php.net/manual/en/function.strftime.php

回答by glembo

I configured it in the AppServiceProvider.

我在 AppServiceProvider 中配置了它。

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

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

回答by Robby Alvian Jaya Mulia

in AppServiceProvider

在 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://carbon.nesbot.com/docs/#api-localization