Drupal 8 – Formatting a Date Field in Twig
Here are the four easiest ways I’ve found to show dates via Twig inside of a node template.
They all result in the same output.
Use the field’s formatter settings; include wrappers
1 |
{{ content.field_blog_date }} |
This is the only example that includes wrappers. The rest output just the date.
Use the field’s formatter settings
1 |
{{ content.field_blog_date.0 }} |
This will use the format defined in Content type » Manage Displays » Your View Mode.
Use Twig date filter + a defined Drupal date format
1 |
{{ node.field_blog_date.value|date('U')|format_date('short_mdyyyy') }} |
I have defined, via the Drupal UI, a date format. Here’s the config for it:
uuid: 1a50c79f-96df-45de-9a21-32e0d8327806
langcode: en
status: true
dependencies: { }
id: short_mdyyyy
label: 'Short - m/d/yyyy'
locked: false
pattern: n/j/Y
Use Twig date filter
1 |
{{ node.field_blog_date.value|date('n/j/Y') }} |
2 Comments
Quentin
{% set finPromo = node.field_fin_prix_special.value|date(‘d M Y’) %}
{% set today = “now”|date(‘d M Y’) %}
{% if content.field_fin_prix_special|render %}
{% if finPromo < today %}
{{ content.field_prix_special }}
Fin de promo le {{ content.field_fin_prix_special.0 }}
{% else %}
{{ content.field_prix }}
{% endif %}
{% endif %}
How i can compare 2 date in Template ? and what it return me the date of today for my field date custom
thank you
Matías
Thanks! You saved my day with {{ node.field_blog_date.value|date(‘n/j/Y’) }}