DrupalDateTime example

$this->assertSession()->fieldValueEquals("{$field_name}[0][value][date]", '');
      $this->assertSession()->elementExists('xpath', '//*[@id="edit-' . $field_name . '-wrapper"]//label[contains(@class,"js-form-required")]');
      $this->assertSession()->fieldNotExists("{$field_name}[0][value][time]");
      // ARIA described-by.       $this->assertSession()->elementExists('xpath', '//input[@aria-describedby="edit-' . $field_name . '-0-value--description"]');
      $this->assertSession()->elementExists('xpath', '//div[@id="edit-' . $field_name . '-0-value--description"]');

      // Build up a date in the UTC timezone. Note that using this will also       // mimic the user in a different timezone simply entering '2012-12-31' via       // the UI.       $value = '2012-12-31 00:00:00';
      $date = new DrupalDateTime($value, DateTimeItemInterface::STORAGE_TIMEZONE);

      // Submit a valid date and ensure it is accepted.       $date_format = DateFormat::load('html_date')->getPattern();
      $time_format = DateFormat::load('html_time')->getPattern();

      $edit = [
        "{$field_name}[0][value][date]" => $date->format($date_format),
      ];
      $this->submitForm($edit, 'Save');
      preg_match('|entity_test/manage/(\d+)|', $this->getUrl()$match);
      $id = $match[1];
      
'status' => TRUE,
    ])->setComponent($field_name$this->displayOptions)
      ->save();
  }

  /** * Tests the "datetime_timestamp" widget. */
  public function testWidget() {
    // Build up a date in the UTC timezone.     $value = '2012-12-31 00:00:00';
    $date = new DrupalDateTime($value, 'UTC');

    // Update the timezone to the system default.     $date->setTimezone(timezone_open(date_default_timezone_get()));

    // Display creation form.     $this->drupalGet('entity_test/add');

    // Make sure the field description is properly displayed.     $this->assertSession()->pageTextContains('Description for timestamp field.');

    // Make sure the "datetime_timestamp" widget is on the page.


    return $form;
  }

  /** * {@inheritdoc} */
  public function settingsSummary() {
    $summary = parent::settingsSummary();

    $date = new DrupalDateTime();
    $this->setTimeZone($date);
    $summary[] = $date->format($this->getSetting('date_format')$this->getFormatSettings());

    return $summary;
  }

}
$date->setDefaultDateTime();
    $this->assertEquals('12:00:00', $date->format('H:i:s'));
  }

  /** * Tests that object methods are chainable. * * @covers ::__call */
  public function testChainable() {
    $tz = new \DateTimeZone(date_default_timezone_get());
    $date = new DrupalDateTime('now', $tz['langcode' => 'en']);

    $date->setTimestamp(12345678);
    $rendered = $date->render();
    $this->assertEquals('1970-05-24 07:21:18 Australia/Sydney', $rendered);

    $date->setTimestamp(23456789);
    $rendered = $date->setTimezone(new \DateTimeZone('America/New_York'))->render();
    $this->assertEquals('1970-09-29 07:46:29 America/New_York', $rendered);
  }

  /** * Tests that non-chainable methods work. * * @covers ::__call */
    // defaults for both.     if (!empty($default_value[0]['default_date_type']) || !empty($default_value[0]['default_end_date_type'])) {
      // A default value should be in the format and timezone used for date       // storage. All-day ranges are stored the same as date+time ranges. We       // only provide a default value for the first item, as do all fields.       // Otherwise, there is no way to clear out unwanted values on multiple       // value fields.       $storage_format = $definition->getSetting('datetime_type') == DateRangeItem::DATETIME_TYPE_DATE ? DateTimeItemInterface::DATE_STORAGE_FORMAT : DateTimeItemInterface::DATETIME_STORAGE_FORMAT;
      $default_values = [[]];

      if (!empty($default_value[0]['default_date_type'])) {
        $start_date = new DrupalDateTime($default_value[0]['default_date'], DateTimeItemInterface::STORAGE_TIMEZONE);
        $start_value = $start_date->format($storage_format);
        $default_values[0]['value'] = $start_value;
        $default_values[0]['start_date'] = $start_date;
      }

      if (!empty($default_value[0]['default_end_date_type'])) {
        $end_date = new DrupalDateTime($default_value[0]['default_end_date'], DateTimeItemInterface::STORAGE_TIMEZONE);
        $end_value = $end_date->format($storage_format);
        $default_values[0]['end_value'] = $end_value;
        $default_values[0]['end_date'] = $end_date;
      }

      
'administer taxonomy',
      'administer nodes',
      'bypass node access',
    ]));
  }

  /** * Tests taxonomy functionality with nodes prior to 1970. */
  public function testTaxonomyEarlyDateNode() {
    // Posts an article with a taxonomy term and a date prior to 1970.     $date = new DrupalDateTime('1969-01-01 00:00:00');
    $edit = [];
    $edit['title[0][value]'] = $this->randomMachineName();
    $edit['created[0][value][date]'] = $date->format('Y-m-d');
    $edit['created[0][value][time]'] = $date->format('H:i:s');
    $edit['body[0][value]'] = $this->randomMachineName();
    $edit['field_tags[target_id]'] = $this->randomMachineName();
    $this->drupalGet('node/add/article');
    $this->submitForm($edit, 'Save');
    // Checks that the node has been saved.     $node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
    $this->assertEquals($date->getTimestamp()$node->getCreatedTime(), 'Legacy node was saved with the right date.');
  }
$this->assertSame('+00:00', $typed_data->getDateTime()->getTimezone()->getName());
    $this->assertEquals(0, $typed_data->validate()->count());
    $typed_data->setValue(NULL);
    $this->assertNull($typed_data->getDateTime(), 'Date wrapper is null-able.');
    $this->assertEquals(0, $typed_data->validate()->count());
    $typed_data->setValue('invalid');
    $this->assertEquals(1, $typed_data->validate()->count(), 'Validation detected invalid value.');
    // Check implementation of DateTimeInterface.     $typed_data = $this->createTypedData(['type' => 'datetime_iso8601'], '2014-01-01T20:00:00+00:00');
    $this->assertInstanceOf(DrupalDateTime::class$typed_data->getDateTime());
    $this->assertSame('+00:00', $typed_data->getDateTime()->getTimezone()->getName());
    $typed_data->setDateTime(new DrupalDateTime('2014-01-02T20:00:00+00:00'));
    $this->assertSame('+00:00', $typed_data->getDateTime()->getTimezone()->getName());
    $this->assertEquals('2014-01-02T20:00:00+00:00', $typed_data->getValue());
    $typed_data->setValue(NULL);
    $this->assertNull($typed_data->getDateTime());

    // Date Time type; values without timezone offset.     $value = '2014-01-01T20:00';
    $typed_data = $this->createTypedData(['type' => 'datetime_iso8601']$value);
    $this->assertInstanceOf(DateTimeInterface::class$typed_data);
    $this->assertSame($value$typed_data->getValue(), 'Date value was fetched.');
    // @todo Uncomment this assertion in https://www.drupal.org/project/drupal/issues/2716891.
/** * Tests the "Active forum topics" block. */
  public function testActiveForumTopicsBlock() {
    $this->drupalLogin($this->adminUser);

    // Create 10 forum topics.     $topics = $this->createForumTopics(10);

    // Comment on the first 5 topics.     $date = new DrupalDateTime();
    for ($index = 0; $index < 5; $index++) {
      // Get the node from the topic title.       $node = $this->drupalGetNodeByTitle($topics[$index]);
      $date->modify('+1 minute');
      $comment = Comment::create([
        'entity_id' => $node->id(),
        'field_name' => 'comment_forum',
        'entity_type' => 'node',
        'node_type' => 'node_type_' . $node->bundle(),
        'subject' => $this->randomString(20),
        'comment_body' => $this->randomString(256),
        

    foreach (['textfield', 'textarea', 'hidden', 'tel', 'url'] as $type) {
      $form['disabled_container']['disabled_container_' . $type] = [
        '#type' => $type,
        '#title' => $type,
        '#default_value' => $type,
        '#test_hijack_value' => 'HIJACK',
      ];
    }

    // Date.     $date = new DrupalDateTime('1978-11-01 10:30:00', 'Europe/Berlin');
    // Starting with PHP 5.4.30, 5.5.15, JSON encoded DateTime objects include     // microseconds. Make sure that the expected value is correct for all     // versions by encoding and decoding it again instead of hardcoding it.     // See https://github.com/php/php-src/commit/fdb2709dd27c5987c2d2c8aaf0cdbebf9f17f643     $expected = json_decode(json_encode($date), TRUE);
    $form['disabled_container']['disabled_container_datetime'] = [
      '#type' => 'datetime',
      '#title' => 'datetime',
      '#default_value' => $date,
      '#expected_value' => $expected,
      '#test_hijack_value' => new DrupalDateTime('1978-12-02 11:30:00', 'Europe/Berlin'),
      
'post comments',
      'skip comment approval',
      'edit own comments',
    ]);
    $this->drupalLogin($this->adminUser);
    $this->setCommentPreview(DRUPAL_OPTIONAL);
    $this->setCommentForm(TRUE);
    $this->setCommentSubject(TRUE);
    $this->setCommentSettings('default_mode', CommentManagerInterface::COMMENT_MODE_THREADED, 'Comment paging changed.');

    $edit = [];
    $date = new DrupalDateTime('2008-03-02 17:23');
    $edit['subject[0][value]'] = $this->randomMachineName(8);
    $edit['comment_body[0][value]'] = $this->randomMachineName(16);
    $edit['uid'] = $web_user->getAccountName() . ' (' . $web_user->id() . ')';
    $edit['date[date]'] = $date->format('Y-m-d');
    $edit['date[time]'] = $date->format('H:i:s');
    $raw_date = $date->getTimestamp();
    $expected_text_date = $this->container->get('date.formatter')->formatInterval(\Drupal::time()->getRequestTime() - $raw_date);
    $expected_form_date = $date->format('Y-m-d');
    $expected_form_time = $date->format('H:i:s');
    $comment = $this->postComment($this->node, $edit['subject[0][value]']$edit['comment_body[0][value]'], TRUE);
    $this->drupalGet('comment/' . $comment->id() . '/edit');
    

  public static function days($required = FALSE, $month = NULL, $year = NULL) {
    // If we have a month and year, find the right last day of the month.     if (!empty($month) && !empty($year)) {
      $date = new DrupalDateTime($year . '-' . $month . '-01 00:00:00', 'UTC');
      $max = $date->format('t');
    }
    // If there is no month and year given, default to 31.     if (empty($max)) {
      $max = 31;
    }
    $none = ['' => ''];
    $range = range(1, $max);
    $range = array_combine($range$range);
    return !$required ? $none + $range : $range;
  }

  
/** * {@inheritdoc} */
  public static function processDefaultValue($default_value, FieldableEntityInterface $entity, FieldDefinitionInterface $definition) {
    $default_value = parent::processDefaultValue($default_value$entity$definition);

    if (isset($default_value[0]['default_date_type'])) {
      if ($definition->getSetting('datetime_type') === DateTimeItem::DATETIME_TYPE_DATE) {
        // A default date only value should be in the format used for date         // storage but in the user's local timezone.         $date = new DrupalDateTime($default_value[0]['default_date']date_default_timezone_get());
        $format = DateTimeItemInterface::DATE_STORAGE_FORMAT;
      }
      else {
        // A default date+time value should be in the format and timezone used         // for date storage.         $date = new DrupalDateTime($default_value[0]['default_date'], DateTimeItemInterface::STORAGE_TIMEZONE);
        $format = DateTimeItemInterface::DATETIME_STORAGE_FORMAT;
      }
      $value = $date->format($format);
      // We only provide a default value for the first item, as do all fields.       // Otherwise, there is no way to clear out unwanted values on multiple value
$this->assertSession()->fieldValueEquals("{$field_name}[0][value][date]", '');
      $this->assertSession()->fieldValueEquals("{$field_name}[0][end_value][date]", '');
      $this->assertSession()->elementExists('xpath', '//*[@id="edit-' . $field_name . '-wrapper"]//label[contains(@class, "js-form-required")]');
      $this->assertSession()->fieldNotExists("{$field_name}[0][value][time]");
      $this->assertSession()->fieldNotExists("{$field_name}[0][end_value][time]");
      $this->assertSession()->elementTextContains('xpath', '//fieldset[@id="edit-' . $field_name . '-0"]/legend', $field_label);
      $this->assertSession()->elementExists('xpath', '//fieldset[@aria-describedby="edit-' . $field_name . '-0--description"]');
      $this->assertSession()->elementExists('xpath', '//div[@id="edit-' . $field_name . '-0--description"]');

      // Build up dates in the UTC timezone.       $value = '2012-12-31 00:00:00';
      $start_date = new DrupalDateTime($value, 'UTC');
      $end_value = '2013-06-06 00:00:00';
      $end_date = new DrupalDateTime($end_value, 'UTC');

      // Submit a valid date and ensure it is accepted.       $date_format = DateFormat::load('html_date')->getPattern();
      $time_format = DateFormat::load('html_time')->getPattern();

      $edit = [
        "{$field_name}[0][value][date]" => $start_date->format($date_format),
        "{$field_name}[0][end_value][date]" => $end_date->format($date_format),
      ];
      
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    foreach ($values as &$item) {
      // @todo The structure is different whether access is denied or not, to       // be fixed in https://www.drupal.org/node/2326533.       if (isset($item['value']) && $item['value'] instanceof DrupalDateTime) {
        $date = $item['value'];
      }
      elseif (isset($item['value']['object']) && $item['value']['object'] instanceof DrupalDateTime) {
        $date = $item['value']['object'];
      }
      else {
        $date = new DrupalDateTime();
      }
      $item['value'] = $date->getTimestamp();
    }
    return $values;
  }

}
$form_state->set('datelistDateCallbackExecuted', TRUE);
  }

  /** * {@inheritdoc} */
  public function buildForm(array $form, FormStateInterface $form_state, string $date_callback = 'datelistDateCallbackTrusted') {

    $form['datelist_element'] = [
      '#title' => 'datelist test',
      '#type' => 'datelist',
      '#default_value' => new DrupalDateTime('2000-01-01 00:00:00'),
      '#date_part_order' => [
        'month',
        'day',
        'year',
        'hour',
        'minute', 'ampm',
      ],
      '#date_text_parts' => ['year'],
      '#date_year_range' => '2010:2020',
      '#date_increment' => 15,
      '#date_date_callbacks' => [[$this$date_callback]],
    ];
Home | Imprint | This part of the site doesn't use cookies.