Carbon setLocale not working Laravel
Asked Answered
T

7

8

Ive read several stackoverflows about set locale. I tested locale -a in the terminal to see if my locale was in there, and it was. The following rule of code is added in the appServiceProvider:

public function boot()
{
    Carbon::setLocale($this->app->getLocale());
}

The $this->app->getLocale() returns "nl"

Anyone know why Carbon still shows Sunday instead of Zondag for example?

Throttle answered 2/8, 2018 at 8:58 Comment(0)
S
9

You might want to use setLocale(LC_TIME, $this->app->getLocale()) somewhere at the start of your application.

Then if you wish to have the localized date format with local names use the formatLocalized function

Carbon::now()->formatLocalized('%d %B %Y');

See http://php.net/manual/en/function.strftime.php for parameter for formatting

Sikkim answered 2/8, 2018 at 9:8 Comment(6)
{{$var->start_at->formatLocalized('d-m-Y')}} that doesnt seem to work, it just echo's d-m-y as a stringThrottle
did you add the LC_TIME setting before running that template?Sikkim
It's in my appserviceprovider, so yea the command should run while the app startsThrottle
oh wait, formatLocalized uses a different format. Try %d %B %YSikkim
It seems the problem was Carbon::setLocale, when i used just setLocale it worked, thanks! was reading over it in your postThrottle
formatLocalized() is not working now since PHP 8, use translatedFormat() insteadLafontaine
Y
34

Translating a carbon date using global localized format

Tested in: Laravel 5.8, Laravel 6, Laravel 8


In config/app.php

'locale' => 'id', // The default is 'en', but this time I want localize them to Indonesian (ID)

Then, to make locale output do something like this:

// WITHOUT LOCALE
Carbon\Carbon::parse('2019-03-01')->format('d F Y'); //Output: "01 March 2019"
now()->subMinute(5)->diffForHumans(); // Output: "5 minutes ago"

// WITH LOCALE
Carbon\Carbon::parse('2019-03-01')->translatedFormat('d F Y'); // Output: "01 Maret 2019"
now()->subMinute(5)->diffForHumans(); // Output: "5 menit yang lalu"

For more information about converting localize dates you can see on below link https://carbon.nesbot.com/docs/#api-localization

Yettayetti answered 7/11, 2019 at 7:28 Comment(2)
This should be used for Laravel 8Milburt
Note that if you use Laravel 5.5+, the locale will be automatically set according to current last App:setLocale execution. So diffForHumans, isoFormat, translatedFormat and localized properties such as ->dayName or ->monthName will be localized transparently.Dorsum
S
9

You might want to use setLocale(LC_TIME, $this->app->getLocale()) somewhere at the start of your application.

Then if you wish to have the localized date format with local names use the formatLocalized function

Carbon::now()->formatLocalized('%d %B %Y');

See http://php.net/manual/en/function.strftime.php for parameter for formatting

Sikkim answered 2/8, 2018 at 9:8 Comment(6)
{{$var->start_at->formatLocalized('d-m-Y')}} that doesnt seem to work, it just echo's d-m-y as a stringThrottle
did you add the LC_TIME setting before running that template?Sikkim
It's in my appserviceprovider, so yea the command should run while the app startsThrottle
oh wait, formatLocalized uses a different format. Try %d %B %YSikkim
It seems the problem was Carbon::setLocale, when i used just setLocale it worked, thanks! was reading over it in your postThrottle
formatLocalized() is not working now since PHP 8, use translatedFormat() insteadLafontaine
U
6

Researching I have found two alternative options:

$date = Carbon::now();
$date->locale('de')->translatedFormat('d F Y');

and:

$date = Carbon::now();
$carbonDateFactory = new CarbonFactory([
  'locale' => 'de_DE',
  'timezone' => 'Europe/Paris',
]);
$carbonDateFactory->make($date)->isoFormat('d MMMM YYYY');

and the ISO compatible format symbols are here

Unstriped answered 23/8, 2022 at 8:7 Comment(0)
A
2

In your AppServiceProvider's register function:

setlocale(LC_TIME, 'nl_NL.utf8');
Carbon::setLocale(config('app.locale'));

Then use translatedFormat() instead of format() or formatLocalized() which is deprecated.

This uses the date() patern which works like format() but translates the string using the current locale.

read more here and here.

Astonishment answered 22/12, 2022 at 11:44 Comment(1)
This really works! Thanks!Softcover
C
0

I solved this by calling setLocale on multiple classes:

$locale = 'nl_NL';
\Carbon\Carbon::setLocale($locale);
\Carbon\CarbonImmutable::setLocale($locale);
\Carbon\CarbonPeriod::setLocale($locale);
\Carbon\CarbonInterval::setLocale($locale);
\Illuminate\Support\Carbon::setLocale($locale);

There's also this ServiceProvider that does the same.

Clayclaybank answered 8/12, 2022 at 17:27 Comment(0)
S
0

If you use newer version of Laravel with php8+ and Carbon 2 and use UTC as default timezone (like they suggest) you will encounter some issues using translatedFormat as it's not gonna convert hours.

Here is a suggestion, i use a Carbon macro to simplify. In AppServiceProvider.php boot method, you should add this (using french locale) :

        //set defaults for Carbon --------------------------------------------------------------------------------------
        setlocale(LC_TIME, app()->getLocale());
        date_default_timezone_set(config('app.timezone'));
        Carbon::setLocale(app()->getLocale());
        //for displaying dates with good timezone translation, we force to french !
        $userSettings = [
            'locale' => 'fr',
            'timezone' => 'Europe/Paris',
            'format' => 'd M Y H:i'
        ];
        //register a macro to be a shortcut for displaying dates !

        Carbon::macro('display', function () use ($userSettings) {
            return $this->copy()->locale($userSettings['locale'])->tz($userSettings['timezone'])->translatedFormat($userSettings['format']);
        });
        //-------------------------------------------------------------------------------------- set defaults for Carbon

Then when you work with a Carbon UTC date (as this is the default timezone), you can use the macro to convert it to your locale and timezone before calling translatedFormat. Example in a blade file where $message->created_at is my Carbon date.

<div class="fs-6 text-muted">{{$message->created_at->display()}}</div>
Sverdlovsk answered 1/6, 2023 at 9:12 Comment(0)
B
-2

try this : setLocale(LC_TIME, app()->getLocale());

Berkeley answered 27/12, 2018 at 14:24 Comment(1)
The correct answer was given months ago. There is no need to repeat it.Dugong

© 2022 - 2024 — McMap. All rights reserved.