Skip to main content

You can create a new date/time format by navigating to:

Admin -> Configuration -> Regional and Language -> Date and Time format and click on 'Add Format'.

Once you’ve created date format, you can control the way date is displayed on the node using preprocess function.

In {theme_name}.theme file, add the following lines

/**
 * 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');
}

Note - date_text is the name of date format created.

 

Whereas, to create the date format for 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 Mon, 26/07/2021 - 16:05.  This can be changed so the format looks like 2 weeks 3 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>')
                              );
}

 

The Drupal::service function can also be used to apply the format to a non node date field.  Such as creating a custom module

  /**
   * Format the amount of time since the last migration for an area
   *
   * @param [String] $changed
   *
   * @return String
   */
  public function generate_formatted_date($changed) {
    $date = '';
    if ($changed != '') {
      $date = \Drupal::service('date.formatter')->formatInterval(REQUEST_TIME - $changed);
    }
    return $date;
  }

 

Related articles