Carbon formatLocalized not working in Blade
Asked Answered
B

5

5

In a Blade view I have this code

{{ \Carbon\Carbon::setLocale("es") }} {{ $registro->fecha_desde->format("l j F Y") }}<br /> {{ $registro->fecha_desde->formatLocalized("%A %d %B %Y") }}<br /> {{ $registro->fecha_desde->diffForHumans() }}

This does not work, it returns:

Friday 30 December 2016
Friday 30 December 2016
dentro de 1 semana 

So, format() and formatLocalized always returns the date in english format. diffForHumans returns the date localized (in spanish in this case).

Am I missing something? cant believe "Carbon's formatLocalized" is not returning localized formated dates....

Benzedrine answered 20/12, 2016 at 23:12 Comment(1)
Official Nesbot Carbon docs.Recycle
A
7

I found two ways to output dates in other language. add this in the AppServiceProvider

    Carbon::setLocale('es');
    setlocale(LC_TIME,'es_ES');

//This output dates in spanish

In App.php put 'es' instead 'en'. now you can use FormatLocalized and all Carbon Functions will be in the language that you assign in setLocale.

Note: If you're using Oracle DB add:

 setlocale(LC_TIME, config('app.locale'));

instead:

setlocale(LC_TIME,'es_ES');
Admeasure answered 10/9, 2018 at 17:31 Comment(0)
B
5

Found it. The problems is \Carbon::setlocale()

This looks ugly but works:

{{ setlocale(LC_ALL, 'es_MX', 'es', 'ES') }}
{{ $registro->fecha_desde->formatLocalized("%A %d %B %Y") }}

Output:

es viernes 30 diciembre 2016
Benzedrine answered 20/12, 2016 at 23:22 Comment(1)
so, do you simply removed Carbon::setLocale() from app service provider?Collage
D
2

Open AppServiceProvider.php Call class of carbon use Carbon\Carbon;

public function boot()
{
  Carbon::setUTF8(true);
  Carbon::setLocale(config('app.locale'));
  setlocale(LC_TIME, config('app.locale'));
}

in the config folder open app.php

set 'locale' => 'es',

on ubuntu

public function boot()
{
   Carbon::setUTF8(true);
   Carbon::setLocale(config('app.locale'));
   setlocale(LC_TIME,'');
} 
Dunite answered 30/1, 2018 at 22:15 Comment(2)
Method setUTF8 is deprecatedRecycle
In Laravel 8, you better create a middleware in case you want to use App::currentLocale() (which is dynamic) instead of config('app.locale') (which is static)Stovall
C
0

to view formats with additional accents, you have to enable UTF8 encoding, before formatting:

\Carbon::setUTF8(true);
Cellaret answered 3/11, 2017 at 10:28 Comment(0)
C
0

Nowadays it's better to use ->isoFormat('dddd DD MMMM YYYY') instead of ->formatLocalized('%A %d %B %Y') because formatLocalized() is deprecated.

So it can look like this:

{{ setlocale(LC_ALL, 'es_MX', 'es', 'ES') }}
{{ $registro->fecha_desde->isoFormat('dddd DD MMMM YYYY') }}
Colwell answered 4/1 at 20:24 Comment(1)
Another option is to use translatedFormat() which uses the php date formats as listed here: php.net/manual/en/datetime.format.phpAmarillas

© 2022 - 2024 — McMap. All rights reserved.