Skip to content

Instantly share code, notes, and snippets.

@alphex
Created September 9, 2019 14:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alphex/f1c2b42a95b432c174654a8ee8225ecd to your computer and use it in GitHub Desktop.
Save alphex/f1c2b42a95b432c174654a8ee8225ecd to your computer and use it in GitHub Desktop.
Handing date formatting in D8 twig

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') }}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment