Support Center

How to format a Date field programmatically in Drupal 8

Last Updated: Aug 14, 2016 06:00PM EEST
Please use the function template_preprocess_node into your .theme file to prepare a timestamp variable for your node template based on your Date field.

Prepare variable for your node templates


function THEMENAME_preprocess_node__NODETYPE(&$variables) {
  if (isset($variables['content']['FIELDNAME'])) {
    $date = $variables['node']->get('FIELDNAME')->first()->getValue()['value'];
    $date = new DateTime($date);
    $date = $date->getTimestamp();
    $variables['VARIABLE'] = $date;
  }
}
 

Example


function scholarly_preprocess_node__mt_event(&$variables) {
  if (isset($variables['content']['field_mt_event_date'])) {
    $date = $variables['node']->get('field_mt_event_date')->first()->getValue()['value'];
    $date = new DateTime($date);
    $date = $date->getTimestamp();
    $variables['event_date'] = $date;
  }
}​


Use format_date filter in your node template

{{ VARIABLE | format_date('custom', 'M')}}
​


Example


​{{ event_date | format_date('custom', 'M') }}


Regrading the PHP date formats 'D, d M Y', please check this documentation page http://www.php.net/manual/en/datetime.formats.date.php

Contact Us

[email protected]
http://assets2.desk.com/
false
morethanthemes
Loading
seconds ago
a minute ago
minutes ago
an hour ago
hours ago
a day ago
days ago
about
false
Invalid characters found
/customer/en/portal/articles/autocomplete