In my twig view I want to display a date:
{{ match.date|date("l d F - H:i") }}
This date is displayed in english:
Wednesday 15 June - 15:30
I would like to display it in french...
I tried to add setlocale(LC_TIME, "fr_FR");
before to call the view but the date is still displayed in english...
I am using format_datetime
twig filter with locale
and pattern
arguments as follow:
{{ service.date|format_datetime(locale='fr',pattern="EEEE dd MMMM YYYY") }}
which outputs for example:
vendredi 27 novembre 2020
lundi 02 novembre 2020
vendredi 30 octobre 2020
see this resource for date pattern.
You can work with hash (key-value array) and match it with the date object you are manipulating.
For example, to get the day of the week of today in words:
{% set trans_day_hash = {
"Monday": "Lundi",
"Tuesday": "Mardi",
"Wednesday": "Mercredi",
"Thursday": "Jeudi",
"Friday": "Vendredi",
"Saturday": "Samedi",
"Sunday": "Dimanche"
}
%}
{{ trans_day_hash["now"|date('l')] }}
Another good practice is:
{{ match.date|date("l")|trans }}
This way you can translate using your prefered translation file.
The date
filter in Twig is not well suited for localized date formatting, as it is based on PHP's DateTime::format
. One option would be to use the localizeddate
filter instead, provided by the Intl Extension.
This extension is not delivered on a default Symfony installation. You will find it in the official Twig extensions repository :
composer require twig/extensions
Then, just declare this extension as a service in services.yml
for instance :
services:
twig.extension.intl:
class: Twig_Extensions_Extension_Intl
tags:
- { name: twig.extension }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With