Carbon setLocale not working Laravel

14,055

Solution 1

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

Solution 2

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

Share:
14,055

Related videos on Youtube

Nick Audenaerde
Author by

Nick Audenaerde

Webdesigner who started to learn php

Updated on June 04, 2022

Comments

  • Nick Audenaerde
    Nick Audenaerde almost 2 years

    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?

  • Nick Audenaerde
    Nick Audenaerde almost 6 years
    {{$var->start_at->formatLocalized('d-m-Y')}} that doesnt seem to work, it just echo's d-m-y as a string
  • Tschallacka
    Tschallacka almost 6 years
    did you add the LC_TIME setting before running that template?
  • Nick Audenaerde
    Nick Audenaerde almost 6 years
    It's in my appserviceprovider, so yea the command should run while the app starts
  • Tschallacka
    Tschallacka almost 6 years
    oh wait, formatLocalized uses a different format. Try %d %B %Y
  • Nick Audenaerde
    Nick Audenaerde almost 6 years
    It seems the problem was Carbon::setLocale, when i used just setLocale it worked, thanks! was reading over it in your post
  • trincot
    trincot over 5 years
    The correct answer was given months ago. There is no need to repeat it.