blog-banner

Formatting the Way the date/time is displayed in Drupal 8

  • Drupal 8
  • Drupal Planet

You can create a new date/time format by navigating to Admin -> Configuration -> Regional and Language -> Date and Time format and clicking on 'Add Format'. Once you’ve created the date format, you can control the way the date is displayed on the node using preprocess function.

In theme_name.theme file, add the following lines. This would override the way the date is displayed in the node.

/**
* Implements hook_preprocess_node
*/
function THEME_NAME_preprocess_node(&$variables) {
  // Getting the node creation time stamp from the node object.
  $date = $variables['node']->getCreatedTime();
  // Here you can use drupal's format_date() function, or some custom PHP date formatting.
  $variables['date'] = \Drupal::service('date.formatter')->format($date, 'date_text');
}

     date_text: Name of date format created.

Date format for Comment(time ago?):

You can change the date format for comment using template_preprocess_comment(). For example, normally in comments, the comment created time is displayed like Thu, 12/17/2015 - 23:04. We can change the format to look like 3 weeks 5 Days ago.

/**
* Implements hook_preprocess_comment
*/
function THEME_NAME_preprocess_comment(&$variables) {
  // Getting the node creation time stamp from the comment object.
  $date = $variables['comment']->getCreatedTime();
  // Here you can use drupal's format_date() function, or some custom php date formatting.
  $variables['created'] = \Drupal::service('date.formatter')->formatInterval(REQUEST_TIME - $date);
  $variables['submitted'] = t('@username commented !datetime', array('@username' => $variables['author'], '!datetime' => '<span class="comments-ago">' . $variables['created'] . ' ago </span>'));
}
Get awesome tech content in your inbox