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 'Custom' formatter for 'datetime' fields.
13 * id = "datetime_custom",
14 * label = @Translation("Custom"),
20 class DateTimeCustomFormatter extends DateTimeFormatterBase {
25 public static function defaultSettings() {
27 'date_format' => DATETIME_DATETIME_STORAGE_FORMAT,
28 ] + parent::defaultSettings();
34 public function viewElements(FieldItemListInterface $items, $langcode) {
37 foreach ($items as $delta => $item) {
39 if (!empty($item->date)) {
40 /** @var \Drupal\Core\Datetime\DrupalDateTime $date */
43 if ($this->getFieldSetting('datetime_type') == 'date') {
44 // A date without time will pick up the current time, use the default.
45 datetime_date_default_time($date);
47 $this->setTimeZone($date);
49 $output = $this->formatDate($date);
67 protected function formatDate($date) {
68 $format = $this->getSetting('date_format');
69 $timezone = $this->getSetting('timezone_override');
70 return $this->dateFormatter->format($date->getTimestamp(), 'custom', $format, $timezone != '' ? $timezone : NULL);
76 public function settingsForm(array $form, FormStateInterface $form_state) {
77 $form = parent::settingsForm($form, $form_state);
79 $form['date_format'] = [
80 '#type' => 'textfield',
81 '#title' => $this->t('Date/time format'),
82 '#description' => $this->t('See <a href="http://php.net/manual/function.date.php" target="_blank">the documentation for PHP date formats</a>.'),
83 '#default_value' => $this->getSetting('date_format'),
92 public function settingsSummary() {
93 $summary = parent::settingsSummary();
95 $date = new DrupalDateTime();
96 $this->setTimeZone($date);
97 $summary[] = $date->format($this->getSetting('date_format'), $this->getFormatSettings());