1

I use Drupal 8 and want the date of comments just show "xx time ago".

I added this code to mytheme.theme, but it does not work:

function mytheme_preprocess_comment(&$variables) { 
/** @var \Drupal\Core\Datetime\DateFormatterInterface $formatter */
$date_formatter = \Drupal::service('date.formatter');

$variables['foo'] = $date_formatter->formatDiff(REQUEST_TIME - 12345, REQUEST_TIME, [
'granularity' => 3,
'return_as_object' => TRUE,   ]); }

And I use {{ foo }} but that does not show "time ago" either. Other things I tried (and which didn't work either):

  • {{ created|date_modify }}
  • {{ created|time_deff }}
  • {{ created }}

Any help/hints about how I can do this?

Note: using the same logic as in my previous question (How can I use 'xx time ago' as date format?) and using MYTHEME_preprocess_comment instead (as suggested by Neograph734) does not seem to work for comments.

3

Have a look at what is mentioned on "Formatting the way the date/time is displayed in Drupal 8". Here is a quote from it:

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.

And this is the sample code mentioned below it:

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

I haven't tested this code (yet), but it looks pretty close to what you're asking for ...

| improve this answer | |
  • I'm not sure that the 'ago' part will be translated as it comes from the !datetime placeholder. – please_reboot Mar 20 '19 at 19:00

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.