0

I would like to set Laravel and Carbon so that, based on the current locale selected by the user, dates will be formatted with the correct pattern. I thought it was enough to set LC_TIME on the desired locale and then use the Carbon method toDateString to get the correct format but, regardless the LC_TIME setted, it always return a date string in the format yyyy-mm-dd.

Expected results:
- If Italian selected, then mm/dd/yyyy
- If English selected, then yyyy-mm-dd
- and so on

I'm using Laravel 5.5 and Carbon 1.36.1

Albirex
  • 283
  • 1
  • 2
  • 13

2 Answers2

4
Carbon::now()->isoFormat('L');

Gives you the current standard digit-format date for the current locale (20/5/2020 for "it_IT", 5/20/2020 for "en_US").

And you can customize this format for a given locale in translations:

Translator::get('en')->setTranslations([
  'formats' => [
    'L' => 'YYYY-MM-DD',
  ],
]);
KyleK
  • 4,643
  • 17
  • 33
2

Recently I had the same problem with an old Laravel app and we solved it by storing the format of the localised dates in a separate language file:

resources/lang/en/dates.php

return [
    'full' => 'Y-m-d'
];

resources/lang/it/dates.php

return [
    'full' => 'm/d/Y'
];

When formatting a date, just use the config() helper to fetch the format provided for the language set in config/app.php, use $date->format(trans('dates.full')) and it will return the proper localised date.

If you so fancy you can use a macro (which was added in 1.26.0) too, to simplify this process:

Carbon::macro('localisedFormat', function ($key) {
    return $this->format(trans("dates.{$key}"));
});

and access it via

$date->localisedFormat('full');
Dan
  • 5,140
  • 2
  • 15
  • 30