Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a twig date in french

Tags:

symfony

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...

like image 599
Paul Avatar asked Jun 19 '16 13:06

Paul


4 Answers

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.

like image 50
ben.IT Avatar answered Oct 11 '22 08:10

ben.IT


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')] }}
like image 33
E.Martinez Avatar answered Oct 11 '22 08:10

E.Martinez


Another good practice is:

{{ match.date|date("l")|trans }}

This way you can translate using your prefered translation file.

like image 43
Inform-all Avatar answered Oct 11 '22 07:10

Inform-all


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 }
like image 22
marc Avatar answered Oct 11 '22 09:10

marc