Search code examples
laraveldateformattostringphp-carbon

Laravel localized date formatting (pattern)


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


Solution

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