Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format dates based on locale?

In a template I display the day and month of a specific date :

<div class="jour"><?php echo date('d',strtotime($content->getCreatedAt())) ?></div>
<div class="mois"><?php echo date('M',strtotime($content->getCreatedAt())) ?></div>

This works fine, problem is the month name is in English. Where do I specify that I want the month names in another locale, French for instance ?

like image 357
Manu Avatar asked Oct 13 '10 14:10

Manu


People also ask

How will you format a date based on a locale after you have obtained a DateFormat object?

To format a date for the current Locale, use one of the static factory methods: myString = DateFormat. getDateInstance(). format(myDate);

How do I find the locale of a date?

Use the toLocaleString() method to get a date and time in the user's locale format, e.g. date. toLocaleString() . The toLocaleString method returns a string representing the given date according to language-specific conventions.


2 Answers

Symfony has a format_date helper among the Date helpers that is i18n-aware. The formats are unfortunately badly documented, see this link for a hint on them.

like image 190
Maerlyn Avatar answered Sep 23 '22 01:09

Maerlyn


default_culture only applies for the symfony internationalisation framework, not for native PHP functions. If you want to change this setting project wide, I would do so in config/ProjectConfiguration.class.php, using setlocale, and then use strftime rather than date:

// config/ProjectConfigration.class.php
setlocale(LC_TIME, 'fr_FR');

// *Success.php
<div class="jour"><?php echo strftime('%d',strtotime($content->getCreatedAt())) ?></div>
<div class="mois"><?php echo strftime('%b',strtotime($content->getCreatedAt())) ?></div>

Note that this requires locale settings to be enabled on your machine. To check, do var_dump(setlocale(LC_ALL, 'fr_FR')); If the result is false, you cannot use setlocale to do this and probably need to write the translation code yourself. Furthermore, you will need to have the correct locale installed on your system. To check what locales are installed, do locale -a at the command line.

like image 22
lonesomeday Avatar answered Sep 19 '22 01:09

lonesomeday