createFromTimestamp example

$form['#title'] = $this->t('Edit comment %title', [
          '%title' => $comment->getSubject(),
        ]);
      }
    }
    else {
      $status = ($this->currentUser->hasPermission('skip comment approval') ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED);
    }

    $date = '';
    if ($comment->id()) {
      $date = !empty($comment->date) ? $comment->date : DrupalDateTime::createFromTimestamp($comment->getCreatedTime());
    }

    // The uid field is only displayed when a user with the permission     // 'administer comments' is editing an existing comment from an     // authenticated user.     $owner = $comment->getOwner();
    $form['author']['uid'] = [
      '#type' => 'entity_autocomplete',
      '#target_type' => 'user',
      '#default_value' => $owner->isAnonymous() ? NULL : $owner,
      // A comment can be made anonymous by leaving this field empty therefore
public static function get($value, array $params = [])
    {
        if ($value instanceof Time) {
            return $value;
        }

        if ($value instanceof DateTime) {
            return Time::createFromInstance($value);
        }

        if (is_numeric($value)) {
            return Time::createFromTimestamp($value);
        }

        if (is_string($value)) {
            return Time::parse($value);
        }

        return $value;
    }
}


        $cache  = CacheFactory::getHandler($config);
        $caches = $cache->getCacheInfo();
        $tbody  = [];

        foreach ($caches as $key => $field) {
            $tbody[] = [
                $key,
                clean_path($field['server_path']),
                number_to_size($field['size']),
                Time::createFromTimestamp($field['date']),
            ];
        }

        $thead = [
            CLI::color('Name', 'green'),
            CLI::color('Server Path', 'green'),
            CLI::color('Size', 'green'),
            CLI::color('Date', 'green'),
        ];

        CLI::table($tbody$thead);
    }

  public function testTimestamp($input, array $initial, array $transform) {
    // Initialize a new date object.     $date = DateTimePlus::createFromTimestamp($input$initial['timezone']);
    $this->assertDateTimestamp($date$input$initial$transform);
  }

  /** * Tests creating dates from datetime strings. * * @param string $input * Input argument for DateTimePlus(). * @param array $initial * @see testTimestamp() * @param array $transform * @see testTimestamp() * * @dataProvider providerTestDateTimestamp */
$typed_data->setValue($new_value);
    $this->assertSame($typed_data->getValue()$new_value, 'Timestamp value was changed and set.');
    $this->assertEquals(0, $typed_data->validate()->count());
    $typed_data->setValue(NULL);
    $this->assertNull($typed_data->getDateTime(), 'Timestamp 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' => 'timestamp'], REQUEST_TIME);
    $this->assertInstanceOf(DrupalDateTime::class$typed_data->getDateTime());
    $typed_data->setDateTime(DrupalDateTime::createFromTimestamp(REQUEST_TIME + 1));
    $this->assertEquals(REQUEST_TIME + 1, $typed_data->getValue());
    $typed_data->setValue(NULL);
    $this->assertNull($typed_data->getDateTime());

    // DurationIso8601 type.     $value = 'PT20S';
    $typed_data = $this->createTypedData(['type' => 'duration_iso8601']$value);
    $this->assertInstanceOf(DurationInterface::class$typed_data);
    $this->assertSame($value$typed_data->getValue(), 'DurationIso8601 value was fetched.');
    $this->assertEquals(0, $typed_data->validate()->count());
    $typed_data->setValue('P40D');
    

class TimestampDatetimeWidget extends WidgetBase {

  /** * {@inheritdoc} */
  public function formElement(FieldItemListInterface $items$delta, array $element, array &$form, FormStateInterface $form_state) {
    $date_format = DateFormat::load('html_date')->getPattern();
    $time_format = DateFormat::load('html_time')->getPattern();
    $default_value = isset($items[$delta]->value) ? DrupalDateTime::createFromTimestamp($items[$delta]->value) : '';
    $element['value'] = $element + [
      '#type' => 'datetime',
      '#default_value' => $default_value,
      '#date_year_range' => '1902:2037',
    ];

    $element['value']['#description'] = $element['#description'] !== ''
    ? $element['#description']
    : $this->t('Format: %format. Leave blank to use the time of form submission.',
    ['%format' => Datetime::formatExample($date_format . ' ' . $time_format)]);

    


    if (empty($langcode)) {
      $langcode = $this->languageManager->getCurrentLanguage()->getId();
    }

    // Create a DrupalDateTime object from the timestamp and timezone.     $create_settings = [
      'langcode' => $langcode,
      'country' => $this->country(),
    ];
    $date = DrupalDateTime::createFromTimestamp($timestamp$this->timezones[$timezone]$create_settings);

    // If we have a non-custom date format use the provided date format pattern.     if ($type !== 'custom') {
      if ($date_format = $this->dateFormat($type$langcode)) {
        $format = $date_format->getPattern();
      }
    }

    // Fall back to the 'medium' date format type if the format string is     // empty, either from not finding a requested date format or being given an     // empty custom format string.
    // end up using the user timezone.     $date = new DrupalDateTime($date_string);
    $timezone = $date->getTimezone()->getName();
    $this->assertSame('Asia/Manila', $timezone, 'DrupalDateTime uses the user timezone, if configurable timezones are used and it is set.');
  }

  /** * Tests the ability to override the time zone in the format method. */
  public function testTimezoneFormat() {
    // Create a date in UTC     $date = DrupalDateTime::createFromTimestamp(87654321, 'UTC');

    // Verify that the date format method displays the default time zone.     $this->assertEquals('1972/10/11 12:25:21 UTC', $date->format('Y/m/d H:i:s e'), 'Date has default UTC time zone and correct date/time.');

    // Verify that the format method can override the time zone.     $this->assertEquals('1972/10/11 08:25:21 America/New_York', $date->format('Y/m/d H:i:s e', ['timezone' => 'America/New_York']), 'Date displayed overridden time zone and correct date/time');

    // Verify that the date format method still displays the default time zone     // for the date object.     $this->assertEquals('1972/10/11 12:25:21 UTC', $date->format('Y/m/d H:i:s e'), 'Date still has default UTC time zone and correct date/time');
  }

}
'%timezone' => $timezone,
      ]));

      // Verify that the 'datetime_time_ago' formatter works for intervals in the       // past. First update the test entity so that the date difference always       // has the same interval. Since the database always stores UTC, and the       // interval will use this, force the test date to use UTC and not the local       // or user timezone.       $timestamp = REQUEST_TIME - 87654321;
      $entity = EntityTest::load($id);
      $field_name = $this->fieldStorage->getName();
      $date = DrupalDateTime::createFromTimestamp($timestamp, 'UTC');
      $entity->{$field_name}->value = $date->format($date_format);
      $entity->save();

      $this->displayOptions['type'] = 'datetime_time_ago';
      $this->displayOptions['settings'] = [
        'future_format' => '@interval in the future',
        'past_format' => '@interval in the past',
        'granularity' => 3,
      ];
      $display_repository->getViewDisplay($this->field->getTargetEntityTypeId()$this->field->getTargetBundle(), 'full')
        ->setComponent($field_name$this->displayOptions)
        

  protected $value;

  /** * {@inheritdoc} */
  public function getDateTime() {
    if (isset($this->value)) {
      return DrupalDateTime::createFromTimestamp($this->value);
    }
  }

  /** * {@inheritdoc} */
  public function setDateTime(DrupalDateTime $dateTime$notify = TRUE) {
    $this->value = $dateTime->getTimestamp();
    // Notify the parent of any changes.     if ($notify && isset($this->parent)) {
      $this->parent->onChange($this->name);
    }
$fieldStorage->save();
    $field = FieldConfig::create([
      'field_storage' => $fieldStorage,
      'bundle' => 'page',
      'required' => TRUE,
    ]);
    $field->save();

    // Create some nodes.     $this->dates = [
      // Tomorrow.       DrupalDateTime::createFromTimestamp($now + 86400, DateTimeItemInterface::STORAGE_TIMEZONE)->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT),
      // Today.       DrupalDateTime::createFromTimestamp($now, DateTimeItemInterface::STORAGE_TIMEZONE)->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT),
      // Yesterday.       DrupalDateTime::createFromTimestamp($now - 86400, DateTimeItemInterface::STORAGE_TIMEZONE)->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT),
    ];

    $this->nodes = [];
    foreach ($this->dates as $date) {
      $this->nodes[] = $this->drupalCreateNode([
        $this->fieldName => [
          'value' => $date,
        ],
$actual = $this->serializer->serialize($normalized, 'json');
    $this->assertSame($expected$actual, 'A normalized array serializes to JSON when "json" is requested');
    // Test 'ajax'.     $actual = $this->serializer->serialize($this->entity, 'ajax');
    $this->assertSame($expected$actual, 'Entity serializes to JSON when "ajax" is requested.');
    $actual = $this->serializer->serialize($normalized, 'ajax');
    $this->assertSame($expected$actual, 'A normalized array serializes to JSON when "ajax" is requested');

    // Generate the expected xml in a way that allows changes to entity property     // order.     $expected_created = [
      'value' => DateTimePlus::createFromTimestamp($this->entity->created->value, 'UTC')->format(\DateTime::RFC3339),
      'format' => \DateTime::RFC3339,
    ];

    $expected = [
      'id' => '<id><value>' . $this->entity->id() . '</value></id>',
      'uuid' => '<uuid><value>' . $this->entity->uuid() . '</value></uuid>',
      'langcode' => '<langcode><value>en</value></langcode>',
      'name' => '<name><value>' . $this->values['name'] . '</value></name>',
      'type' => '<type><value>entity_test_mulrev</value></type>',
      'created' => '<created><value>' . $expected_created['value'] . '</value><format>' . $expected_created['format'] . '</format></created>',
      'user_id' => '<user_id><target_id>' . $this->user->id() . '</target_id><target_type>' . $this->user->getEntityTypeId() . '</target_type><target_uuid>' . $this->user->uuid() . '</target_uuid><url>' . $this->user->toUrl()->toString() . '</url></user_id>',
      
Home | Imprint | This part of the site doesn't use cookies.