19

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

4

3 回答 3

33

使用全球本地化格式翻译碳日期

测试:Laravel 5.8、Laravel 6、Laravel 8


在 config/app.php

'locale' => 'id', // The default is 'en', but this time I want localize them to Indonesian (ID)

然后,要使语言环境输出执行以下操作:

// WITHOUT LOCALE
Carbon\Carbon::parse('2019-03-01')->format('d F Y'); //Output: "01 March 2019"
now()->subMinute(5)->diffForHumans(); // Output: "5 minutes ago"

// WITH LOCALE
Carbon\Carbon::parse('2019-03-01')->translatedFormat('d F Y'); // Output: "01 Maret 2019"
now()->subMinute(5)->diffForHumans(); // Output: "5 menit yang lalu"

有关转换本地化日期的更多信息,您可以在以下链接中查看 https://carbon.nesbot.com/docs/#api-localization

于 2019-10-18T08:42:53.093 回答
25

所以这是我的错,Carbon 实际上是在使用 php

setlocale();

Carbon::setLocale('fr')

方法仅适用于

->diffForHumans()

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

locale -a

在您的控制台上

其次,你必须使用

->formatLocalized()

方法而不是

->format()

方法

最后是所有有用的方法,比如

->toDateString()
->toFormattedDateString()
->toTimeString()
->toDateTimeString()
->toDayDateTimeString()

没有被本地化

最后你必须使用这些解析字母

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

于 2015-09-15T19:38:47.883 回答
18

我在 AppServiceProvider 中配置了它。

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

        \Carbon\Carbon::setLocale(config('app.locale'));
    }
}
于 2017-03-26T16:19:47.270 回答