How to Localize Time Format in Laravel and Carbon

3895
Share:
how-to-localize-time-format-in-laravel-and-carbon

Problem

I develop a Laravel application which need to show date in localized format. The 'date' I'm talking about is database record which defined as $dates in its model.

However, client only need the date, not the whole site as the whole site is already in desired language. I've read Laravel documentation on their website and found nothing about localizing date format. They only shows how to make a translation there.

Workaround

The date field which need to be localized is already mutated as Carbon instance by define the field as $dates in its model. So, the my next logical move is to search on Carbon's documentation. Luckily enough, Carbon provide a method to support this requirement (check http://carbon.nesbot.com/docs/#api-localization). So I guess by setting the locale somewhere in Laravel and change the calls ->format('j F Y') to be ->formatLocalized('%e %B %Y') should be enough.

  1. Open app/Providers/AppServiceProvider.php
  2. On the boot() function, add this line:
            setlocale(LC_TIME, 'id_ID.utf8');
  3. Change every function ->format('j F Y') to be ->formatLocalized('%e %B %Y').

Notice the parameter in formatLocalized() function differs from what being used in format(). This is due to Carbon implements formatLocalized() using strftime. You can check all available formats here: http://www.php.net/strftime

 

Tags
Share:

0 comment

Leave a reply

Your email address will not be published. Required fields are marked *