What's the best way to localise a date on Laravel? What's the best way to localise a date on Laravel? laravel laravel

What's the best way to localise a date on Laravel?


Using a library as Laravel-Date you will just need to set the language of the app in the Laravel app config file and use its functions to format the date as you want.

Set the language in /app/config/app.php

'locale' => 'es',

I've found this library pretty useful and clean. To use it, you can write something like the example in the library readme file. I leave the results in spanish.

echo Date::now()->format('l j F Y H:i:s'); // domingo 28 abril 2013 21:58:16echo Date::parse('-1 day')->diffForHumans(); // 1 día atrás

This is the link to the repository:

https://github.com/jenssegers/laravel-date

To install this library you can follow the instructions detailed in the following link:

https://github.com/jenssegers/laravel-date#installation


When you retrieve a date off a model in Laravel, you get back a Carbon object:https://github.com/briannesbitt/Carbon

If you refer to the Carbon documentation, it tells you how you can get a locale formatted Date:

Unfortunately the base class DateTime does not have any localization support. To begin localization support a formatLocalized($format) method has been added. The implementation makes a call to strftime using the current instance timestamp. If you first set the current locale with setlocale() then the string returned will be formatted in the correct locale.

setlocale(LC_TIME, 'German');                     echo $dt->formatLocalized('%A %d %B %Y');          // Donnerstag 25 Dezember 1975setlocale(LC_TIME, '');                           echo $dt->formatLocalized('%A %d %B %Y');          // Thursday 25 December 1975

So basically, just use formatLocalized('M') instead of format('M')


It is also a good idea to set locale globally for each request (eg. in filters.php) when using Carbon date instances.

App::before(function($request) {    setlocale(LC_TIME, 'sk_SK.utf8');});

and then proceed as usual

$dt->formatLocalized('%b'); // $dt is carbon instance

See format options here and list of locales here.