3 namespace Drupal\datetime\Plugin\Field\FieldFormatter;
5 use Drupal\Core\Datetime\DrupalDateTime;
6 use Drupal\Core\Field\FieldItemListInterface;
7 use Drupal\Core\Form\FormStateInterface;
10 * Plugin implementation of the 'Default' formatter for 'datetime' fields.
13 * id = "datetime_default",
14 * label = @Translation("Default"),
20 class DateTimeDefaultFormatter extends DateTimeFormatterBase {
25 public static function defaultSettings() {
27 'format_type' => 'medium',
28 ] + parent::defaultSettings();
34 public function viewElements(FieldItemListInterface $items, $langcode) {
37 foreach ($items as $delta => $item) {
42 /** @var \Drupal\Core\Datetime\DrupalDateTime $date */
45 if ($this->getFieldSetting('datetime_type') == 'date') {
46 // A date without time will pick up the current time, use the default.
47 datetime_date_default_time($date);
50 // Create the ISO date in Universal Time.
51 $iso_date = $date->format("Y-m-d\TH:i:s") . 'Z';
53 $this->setTimeZone($date);
55 $output = $this->formatDate($date);
58 // Display the date using theme datetime.
69 'datetime' => $iso_date,
72 if (!empty($item->_attributes)) {
73 $elements[$delta]['#attributes'] += $item->_attributes;
74 // Unset field item attributes since they have been included in the
75 // formatter output and should not be rendered in the field template.
76 unset($item->_attributes);
87 protected function formatDate($date) {
88 $format_type = $this->getSetting('format_type');
89 $timezone = $this->getSetting('timezone_override') ?: $date->getTimezone()->getName();
90 return $this->dateFormatter->format($date->getTimestamp(), $format_type, '', $timezone != '' ? $timezone : NULL);
96 public function settingsForm(array $form, FormStateInterface $form_state) {
97 $form = parent::settingsForm($form, $form_state);
99 $time = new DrupalDateTime();
100 $format_types = $this->dateFormatStorage->loadMultiple();
102 foreach ($format_types as $type => $type_info) {
103 $format = $this->dateFormatter->format($time->getTimestamp(), $type);
104 $options[$type] = $type_info->label() . ' (' . $format . ')';
107 $form['format_type'] = [
109 '#title' => t('Date format'),
110 '#description' => t("Choose a format for displaying the date. Be sure to set a format appropriate for the field, i.e. omitting time for a field that only has a date."),
111 '#options' => $options,
112 '#default_value' => $this->getSetting('format_type'),
121 public function settingsSummary() {
122 $summary = parent::settingsSummary();
124 $date = new DrupalDateTime();
125 $summary[] = t('Format: @display', ['@display' => $this->formatDate($date, $this->getFormatSettings())]);