Laravel : How to localize dates within views with Carbon

标签 laravel php-carbon

这个问题在这里已经有了答案:





What's the best way to localise a date on Laravel?

(8 个回答)


2年前关闭。




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

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

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');在路线或 View 中无效。

编辑:
我的 Blade 调用中出现轻微错误 {{$active_task->start_date->format('l j F Y H:i:s')}}而不是 {{$active_task->format('l j F Y H:i:s')}}

最佳答案

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

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

关于Laravel : How to localize dates within views with Carbon,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48463083/

相关文章:

php - Laravel Mail::send 无法在服务器上进行身份验证,但可以在本地工作

php - Laravel - 来自语言文件的 Foreach 循环?

php - Laravel session /存储在刷新时为空

php - 碳日期检查是否为指定日期

php - 当我删除帖子(营销事件)时,与已删除营销事件相关的付款仍在数据库中,我也想将其删除。 (拉拉维尔, Controller )

php - Laravel 的 Carbon 不显示日期名称

php - 为每个用户生成随机唯一代码

php - Eloquent:根据关系过滤记录

PHP:如何将 VARIANT DATE 转换为日期时间字符串

php - 从查询结果中将日期转换为碳实例