DateTimeTimeAgoFormatter.php

Same filename in other branches
  1. 8.9.x core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeTimeAgoFormatter.php
  2. 10 core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeTimeAgoFormatter.php
  3. 11.x core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeTimeAgoFormatter.php

Namespace

Drupal\datetime\Plugin\Field\FieldFormatter

File

core/modules/datetime/src/Plugin/Field/FieldFormatter/DateTimeTimeAgoFormatter.php

View source
<?php

namespace Drupal\datetime\Plugin\Field\FieldFormatter;

use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldFormatter\TimestampAgoFormatter;

/**
 * Plugin implementation of the 'Time ago' formatter for 'datetime' fields.
 *
 * @FieldFormatter(
 *   id = "datetime_time_ago",
 *   label = @Translation("Time ago"),
 *   field_types = {
 *     "datetime"
 *   }
 * )
 */
class DateTimeTimeAgoFormatter extends TimestampAgoFormatter {
    
    /**
     * {@inheritdoc}
     */
    public function viewElements(FieldItemListInterface $items, $langcode) {
        $elements = [];
        foreach ($items as $delta => $item) {
            $date = $item->date;
            $output = [];
            if (!empty($item->date)) {
                $output = $this->formatDate($date);
            }
            $elements[$delta] = $output;
        }
        return $elements;
    }
    
    /**
     * Formats a date/time as a time interval.
     *
     * @param \Drupal\Core\Datetime\DrupalDateTime|object $date
     *   A date/time object.
     *
     * @return array
     *   The formatted date/time string using the past or future format setting.
     */
    protected function formatDate(DrupalDateTime $date) {
        return parent::formatTimestamp($date->getTimestamp());
    }

}

Classes

Title Deprecated Summary
DateTimeTimeAgoFormatter Plugin implementation of the 'Time ago' formatter for 'datetime' fields.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.