Drupal - Change article date format
So after spending more time than I care to admit looking into this, I've come up with two solutions to this.
Solution 1
One way to do it is with the date function that darol100 mentioned in his answer. Modifying his example for my case, in my node--article.html.twig
file, I changed:
{% trans %}Submitted by {{ author_name }} on {{ date }}{% endtrans %}
to
{% set createdDate = node.getCreatedTime|date('j F Y') %}
{% trans %}Submitted by {{ author_name }} on {{ createdDate }} {% endtrans %}
The advantage to this approach is that it's easy and quick. The disadvantage is I'm not using Drupal's built-in date format system.
Solution 2
In order to use Drupal's date format system, I first created my custom format at admin/config/regional/date-time
. Then I edited node--article.html.twig
as follows:
{% set createdDate = node.getCreatedTime|format_date('my_custom_format') %}
{% trans %}Submitted by {{ author_name }} on {{ createdDate }} {% endtrans %}
This assumes I named my custom format "My Custom Format", which results in the machine name my_custom_format
.
While this solution requires an extra step, I feel it's the more Drupal way to do it.
I learned about it on this page about Drupal's Twig Filters.
If you want to change the date format base on article content type level. You can edit/add the following code post.published_at|date
and use a filter to alter the date format.
node--article.html.twig
{# Here are few example #}
{{ post.published_at|date(format='j F Y') }} {# Output = 10 March 2001#}
{{ post.published_at|date(format="F j, Y, g:i a") }} {# Output = March 10, 2001, 5:16 pm#}
{{ post.published_at|date(format='m/d/Y') }} {# Output 10/3/2001 #}
Twig use the same naming code as php date format. For more information about twig date formats visit - http://twig.sensiolabs.org/doc/filters/date.html
I'm more for Chris's solution 2. As he says it IS more the drupal way... but it's not the best option yet.
format_date() has been deprecated and will be removed before Drupal 9... meaning that one day, you'll do a drupal update and this will break.
Instead, it's better to do this in your .theme file in a preprocess function.
function [theme_name]_preprocess_node(&$variables) {
$variables['date'] = \Drupal::service('date.formatter')->format($variables['node']->getCreatedTime(), 'my_custom_format');
}