3 namespace Drupal\views\Plugin\views\field;
5 use Drupal\Core\Datetime\DateFormatterInterface;
6 use Drupal\Core\Form\FormStateInterface;
7 use Drupal\views\ResultRow;
8 use Symfony\Component\DependencyInjection\ContainerInterface;
11 * A handler to provide proper displays for time intervals.
13 * @ingroup views_field_handlers
15 * @ViewsField("time_interval")
17 class TimeInterval extends FieldPluginBase {
20 * The date formatter service.
22 * @var \Drupal\Core\Datetime\DateFormatterInterface
24 protected $dateFormatter;
27 * Constructs a TimeInterval plugin object.
29 * @param array $configuration
30 * A configuration array containing information about the plugin instance.
31 * @param string $plugin_id
32 * The plugin_id for the plugin instance.
33 * @param mixed $plugin_definition
34 * The plugin implementation definition.
35 * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
36 * The date formatter service.
38 public function __construct(array $configuration, $plugin_id, $plugin_definition, DateFormatterInterface $date_formatter) {
39 $this->dateFormatter = $date_formatter;
40 parent::__construct($configuration, $plugin_id, $plugin_definition);
46 public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
51 $container->get('date.formatter')
58 protected function defineOptions() {
59 $options = parent::defineOptions();
61 $options['granularity'] = ['default' => 2];
69 public function buildOptionsForm(&$form, FormStateInterface $form_state) {
70 parent::buildOptionsForm($form, $form_state);
72 $form['granularity'] = [
73 '#type' => 'textfield',
74 '#title' => $this->t('Granularity'),
75 '#description' => $this->t('How many different units to display in the string.'),
76 '#default_value' => $this->options['granularity'],
83 public function render(ResultRow $values) {
84 $value = $values->{$this->field_alias};
85 return $this->dateFormatter->formatInterval($value, isset($this->options['granularity']) ? $this->options['granularity'] : 2);