How to format dates based on locale?

安稳与你 提交于 2019-12-05 11:18:02

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.

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.

Sorry for butting in so late in the day, but I would like to add my own thoughts here. The best international date format that I have come up with is "%e %b %Y", e.g. 9 Mar 2012. I find this much more readable than the ISO format "%Y-%m-%d", e.g. 2012-03-09. According to the docs, the %x format should be locale sensitive, but it does not work for me, at least not on the iPhone. This may be because Safari is not passing the locale in the HTML headers, I do not know.

It is sometimes useful to use an array with different possible values to setlocale(). Especially to support different environments (windows, linux, ...)

setlocale(LC_TIME, array('fr', 'fr_FR', 'fr_FR.utf8', 'french', 'french_FRANCE', 'french_FRANCE.utf8'));
echo strftime("%A %d %B", strtotime(date("Y-m-d")));

As the documentation states:

If locale is an array or followed by additional parameters then each array element or parameter is tried to be set as new locale until success. This is useful if a locale is known under different names on different systems or for providing a fallback for a possibly not available locale.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!