7

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'));

   });

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.

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

EDIT: 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')}}

Sebastien D
  • 4,369
  • 4
  • 18
  • 46

2 Answers2

9

You need to use the php function setlocale before setting the localized format in 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.

Examples from the docs:

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
  • Ok I see the mistake about using `format()` . Changed my code with now effect so far but I keep trying – Sebastien D Jan 26 '18 at 14:35
  • Arg! 'German' was not a valid language in my php config. That's why it didn't work on the first try. Weird example they gave! – Sebastien D Jan 26 '18 at 14:48
  • You can list the installed locales with `locale -a`. To install a new one, [see this answer](https://askubuntu.com/a/76106/323990). – totymedli Mar 28 '18 at 04:57
  • It is late to answer but for those who come later to this question. the setlocale() will only apply changes to the formatLocalized() method. To translate months' names I created a gist here that I think its the only way to be able to localize Carbon's custom formats.https://gist.github.com/ebrahimahmadi/ac9b08c857065d36c1fcefb0ea8e5733 – Ebi Dec 23 '20 at 19:21
  • 1
    P.S. Deprecated as of PHP8.1. isoFormat() should be used instead – Didzis May 24 '23 at 05:17
1

Ok, everything is fixed.

In the top of the view:

setlocale(LC_TIME, 'IT_it');

And then the blade call:

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

All credits to @Btl

Sebastien D
  • 4,369
  • 4
  • 18
  • 46