Laravel:如何使用Carbon在视图中本地化日期 [英] Laravel : How to localize dates within views with Carbon

查看:82
本文介绍了Laravel:如何使用Carbon在视图中本地化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to localize Carbon dates in a view in different languages with no success so far.

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

I retrieve dates from a Model and send them to a 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"中显示它们:

and can easily display them in '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

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

But I can not manage to render them in the desired language.

我尝试在路径或视图中添加Carbon::setLocale('it');无效.

I tried adding Carbon::setLocale('it'); in the route or in the view with no effect.

我的刀片服务器调用{{$active_task->start_date->format('l j F Y H:i:s')}}而不是{{$active_task->format('l j F Y H:i:s')}}

slight error in my blade call {{$active_task->start_date->format('l j F Y H:i:s')}} instead of {{$active_task->format('l j F Y H:i:s')}}

推荐答案

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

You need to use the php function setlocale before setting the localized format in Carbon.

不幸的是,基类DateTime没有任何本地化支持.为了开始本地化支持,添加了formatLocalized($ format)方法.该实现使用当前实例的时间戳对strftime进行调用.如果您首先使用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

这篇关于Laravel:如何使用Carbon在视图中本地化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆