8

How can I print a custom date format in Twig? First of all my I am trying to edit the field.html.twig of the field called field_publication_date, in that file I find this variable {{ item.content }} which prints Jun, 12/06/2016 - 12:29.

This is what I have tried: {{ item.content.field_publication_date|format_date('M') }}

11

Try to use this -

{{ item.content.field_publication_date|date("M") }}

But, I think you will get your solution in

{{ item.content|date("M") }}

Where item.content contains the date string inside field--node--field-publication-date.html.twig.

  • 1
    format_date should be the function, referencing a date format from Drupal – Kevin Jan 17 '17 at 17:33
  • Got referenced from here- twig.sensiolabs.org/doc/2.x/filters/date.html – Ashish Deynap Jan 17 '17 at 17:34
  • Thank you. The first option worked for me {{ item.content.field_publication_date|date("M") }} – Ricardo Castañeda Jan 17 '17 at 17:51
  • 1
    If it is a date field, why aren't field formatter settings sufficient? Also if it is a timestamp, format_date is a Drupal twig filter you can pass custom date formats to: drupal.org/docs/8/theming/twig/… – Kevin Jan 17 '17 at 17:58
  • @kevin I pretended to use display suite and by token show the dates in different divs. But somehow the custom date didn't work for me. – Ricardo Castañeda Jan 17 '17 at 19:02
8

First, create the custom date format my_custom_date_format in the configuration section of the drupal admin.

Second, use the format_date Twig filter, like here:

{{ node.created.value|format_date('my_custom_date_format') }}

It might be necessary to convert the date to a unix timestamp, first. That will look like this:

{{ content.my_date_field.value|date('U')|format_date('my_custom_date_format') }}
  • 1
    The second code example didn't work for me, since "value" on the content array (content.field_date.value) was null. I suspect it shows up or not based on the display formatter used for that field. I had to use node.field_date.value|date('U') instead. – George Mar 13 '18 at 23:50
1

The \Drupal\datetime\Plugin\Field\FieldType\DateTimeItem has a value and a date property. The value is UTC and the date is computed. Use the date property to avoid having to deal with the timezone, and you can use a created format or a custom one:

{{ node.field_publication_date.date|format_date('custom', 'F j, Y') }}

Date format in Drupal:

{{ node.field_publication_date.date|format_date('my_custom_date_format') }}

  • Here's what worked for me: {{ node.field_event_date.date|date('U')|format_date('custom', 'F j, Y') }} – arnoldbird Mar 27 at 16:07
0

This worked for me. The date value with twig's own date() format function:

{{ content.field_arrival_date.value | date("Y/m/d") }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.