使用 Carbon 的 Laravel 中未显示阿拉伯日期

Arabic Date is not showing in Laravel using Carbon

我想使用 Carbon 以阿拉伯语格式显示日期和星期。但它显示的是英文。

Carbon::setlocale("ar");
echo Carbon::parse()->format('D d F Y');

结果:Sun 12 May 2019

Expected result: it should show day and month in arabic.

Carbon::setLocale() 仅适用于 diffForHumans 方法,否则它使用 gloabl PHP 日期时间局部变量。所以如果你想使用阿拉伯语你必须调用

setLocale(LC_TIME, $locale);

然后使用 Carbon 方法 formatlocalized()

Carbon\Carbon::now()->formatLocalized($format);

请注意,PHP 可识别不止一种阿拉伯语语言环境,因此您必须从 this list

中选择一种

只需确保选择安装在您正在使用的服务器上的一个,否则 setLocale() 方法将失败并且 return false。

您可以改用这个包Date

此包包含以下语言的语言文件:

  • 阿尔巴尼亚语
  • 阿拉伯语
  • 阿塞拜疆语
  • 孟加拉语
  • 巴斯克语
  • 白俄罗斯语
  • 波斯尼亚语

还有更多!

安装

composer require jenssegers/date

用法

use Jenssegers\Date\Date;
Date::setLocale('nl');
echo Date::now()->format('l j F Y H:i:s'); // zondag 28 april 2013 21:58:16
echo Date::parse('-1 day')->diffForHumans(); // 1 dag geleden

将 config/app.php 区域设置更改为您的语言,然后应用此代码:

或者您可以通过以下方式动态更改应用区域设置:

app()->setLocale('ar');

然后

\Carbon\Carbon::now()->translatedFormat('l')

\Carbon\Carbon::createFromDate($now->year, $now->month, $day)->translatedFormat('l')

等等...

  1. 在控制器顶部导入 Carbon(使用 Carbon\Carbon;)。

  2. 像这样在函数中使用 Carbon :

    public function index()
    {
        Carbon::setLocale('ar');
    
        // Your Code Here...
    }
    
  3. 在您看来使用日期是这样的:

    <p>
      {{ \Carbon\Carbon::parse($user->created_at)->translatedFormat('l j F Y H:i:s') }}
    </p>