Laravel 5 Carbon全球区域

Mat*_*ein 11 php laravel php-carbon

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

config('app.locale')
Run Code Online (Sandbox Code Playgroud)

与碳合作.

看起来你可以通过使用以下两种方法来实现:

Carbon::setLocale('fr')
Run Code Online (Sandbox Code Playgroud)

要么

setlocale(LC_TIME, 'theLocale');
Run Code Online (Sandbox Code Playgroud)

所以我尝试过使用中间件或提供商,但没有成功.

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

Rob*_*lia 24

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

测试: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)
Run Code Online (Sandbox Code Playgroud)

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

// 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"
Run Code Online (Sandbox Code Playgroud)

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


Mat*_*ein 16

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

setlocale();
Run Code Online (Sandbox Code Playgroud)

Carbon::setLocale('fr')
Run Code Online (Sandbox Code Playgroud)

方法仅适用于

->diffForHumans()
Run Code Online (Sandbox Code Playgroud)

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

locale -a
Run Code Online (Sandbox Code Playgroud)

在你的控制台上

其次,你必须使用

->formatLocalized()
Run Code Online (Sandbox Code Playgroud)

方法代替

->format()
Run Code Online (Sandbox Code Playgroud)

方法

最后所有有用的方法都是如此

->toDateString()
->toFormattedDateString()
->toTimeString()
->toDateTimeString()
->toDayDateTimeString()
Run Code Online (Sandbox Code Playgroud)

没有本地化

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

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


小智 15

我在AppServiceProvider中配置它.

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

        \Carbon\Carbon::setLocale(config('app.locale'));
    }
}
Run Code Online (Sandbox Code Playgroud)