【问题标题】:Laravel 5 Carbon global LocaleLaravel 5 Carbon 全局语言环境
【发布时间】:2015-12-09 13:43:37
【问题描述】:

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

config('app.locale')

与 Carbon 合作。

您似乎可以使用以下任一方法来做到这一点:

Carbon::setLocale('fr')

setlocale(LC_TIME, 'theLocale');

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

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

【问题讨论】:

  • 问题是什么?你有没有得到任何错误或者它只是不起作用?你为调试做了什么?转储 getLocale、config 等输出?

标签: php laravel php-carbon


【解决方案1】:

所以这是我的错,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

【讨论】:

    【解决方案2】:

    我是在 AppServiceProvider 中配置的。

    class AppServiceProvider extends ServiceProvider
    {
        public function boot()
        {
            // Localization Carbon
    
            \Carbon\Carbon::setLocale(config('app.locale'));
        }
    }
    

    【讨论】:

      【解决方案3】:

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

      测试于: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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-29
        • 1970-01-01
        • 2015-06-13
        • 2017-11-01
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多