The “today / yesterday” format is still relevant today. So let’s try to implement it in Drupal 8/9. As you know, version 9 of Drupal received a new version of the Twig template engine – 2.1. Because of this, the logic and syntax of working with templates have changed a bit. At first I thought that this would not pose any problems, but after having studied most of the materials on this topic, I did not find very scant information, and even then for version 7 of Drupal.
After some experimentation, I got the following code (working).
For work with Views example:
{% if created.value|date("d/m/Y") == "today"|date("d/m/Y") %} today {% elseif created.value|date("d/m/Y") == "yesterday"|date("d/m/Y") %} yesterday {% endif %}
Note: Do not use the date format with hours and minutes as the default values for “yesterday” and “today” are “dd.mm.YYY : 00:00”.And your comparison operation will always be wrong
Work with twig template. Example: node.html.twig
{% if node.created.value|date("d F Y") == 'today'|date("d F Y") %} today {% elseif node.created.value|date("d F Y") == 'yesterday'|date("d F Y") %} yesterday {% endif %}
That’s all. Hope you find this helpful. Happy coding!
Similar Posts:
- How to get formatted node creation date in Drupal 8
- How to translate dates in Twig with drupal 8
- how to set date field programmatically drupal 8 / 9
- Helpful node methods in Drupal 8
- How to get view mode of node in Drupal 8 & 9