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) {
35 // @todo Evaluate removing this method in
36 // https://www.drupal.org/node/2793143 to determine if the behavior and
37 // markup in the base class implementation can be used instead.
40 foreach ($items as $delta => $item) {
41 if (!empty($item->date)) {
42 /** @var \Drupal\Core\Datetime\DrupalDateTime $date */
45 $elements[$delta] = $this->buildDate($date);
55 protected function formatDate($date) {
56 $format = $this->getSetting('date_format');
57 $timezone = $this->getSetting('timezone_override');
58 return $this->dateFormatter->format($date->getTimestamp(), 'custom', $format, $timezone != '' ? $timezone : NULL);
64 public function settingsForm(array $form, FormStateInterface $form_state) {
65 $form = parent::settingsForm($form, $form_state);
67 $form['date_format'] = [
68 '#type' => 'textfield',
69 '#title' => $this->t('Date/time format'),
70 '#description' => $this->t('See <a href="http://php.net/manual/function.date.php" target="_blank">the documentation for PHP date formats</a>.'),
71 '#default_value' => $this->getSetting('date_format'),
80 public function settingsSummary() {
81 $summary = parent::settingsSummary();
83 $date = new DrupalDateTime();
84 $this->setTimeZone($date);
85 $summary[] = $date->format($this->getSetting('date_format'), $this->getFormatSettings());