Laravel : 如何使用 Carbon 在视图中本地化日期

Laravel : How to localize dates within views with Carbon

我正在尝试在不同语言的视图中本地化 Carbon 日期,但到目前为止没有成功。

我从模型中检索日期并将它们发送到视图:

Route::get('/tables/setup', function(){
     $now=  Date::now('Europe/Paris');

     $active_tasks = GanttTask::whereDate('start_date', '<',  $now)
        ->whereDate('end_date', '>', $now)
        ->get();

     return view('my_view', compact('active_tasks'));

   });

并且可以轻松地在 'my_view' 中显示它们:

  @foreach($active_tasks as $active_task)

     {{$active_task->start_date->format('l j F Y H:i:s')}}  //Friday 26 January 2018 09:19:54

     @endforeach

但我无法用所需的语言呈现它们。

我尝试在路线或视图中添加 Carbon::setLocale('it'); 但没有效果。

编辑: 我的 blade 调用 {{$active_task->start_date->format('l j F Y H:i:s')}} 而不是 {{$active_task->format('l j F Y H:i:s')}}

时出现轻微错误

在 Carbon 中设置本地化格式之前,您需要使用 php 函数 setlocale

Unfortunately the base class DateTime does not have any localization support. To begin localization support a formatLocalized($format) method was added. The implementation makes a call to strftime using the current instance timestamp. If you first set the current locale with PHP function setlocale() then the string returned will be formatted in the correct locale.

来自文档的示例:

setlocale(LC_TIME, 'German');
echo $dt->formatLocalized('%A %d %B %Y');          // Mittwoch 21 Mai 1975
setlocale(LC_TIME, '');
echo $dt->formatLocalized('%A %d %B %Y');          // Wednesday 21 May 1975

好的,一切都解决了。

在视图顶部:

setlocale(LC_TIME, 'IT_it');

然后 blade 调用:

{{$active_task->start_date->formatLocalized('%A %d %B %Y')}}

全部归功于@Btl