setTimezone example


          'value' => 'en',
        ],
      ],
      'name' => [
        [
          'value' => 'Llama',
        ],
      ],
      'created' => [
        [
          'value' => (new \DateTime())->setTimestamp(123456789)->setTimezone(new \DateTimeZone('UTC'))->format(\DateTime::RFC3339),
          'format' => \DateTime::RFC3339,
        ],
      ],
      'changed' => [
        [
          'value' => (new \DateTime())->setTimestamp($this->entity->getChangedTime())->setTimezone(new \DateTimeZone('UTC'))->format(\DateTime::RFC3339),
          'format' => \DateTime::RFC3339,
        ],
      ],
      'default_langcode' => [
        [
          

    public function setDate(\DateTimeInterface $date)static
    {
        if ($date instanceof \DateTime) {
            $date = \DateTimeImmutable::createFromMutable($date);
        }

        $date = $date->setTimezone(new \DateTimeZone('UTC'));
        $this->headers->set('Date', $date->format('D, d M Y H:i:s').' GMT');

        return $this;
    }

    /** * Returns the age of the response in seconds. * * @final */
    public function getAge(): int
    {
$this->assertSession()->fieldValueEquals("{$field_name}[0][value][date]", '');
    $this->assertSession()->fieldValueEquals("{$field_name}[0][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 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()));

    // 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),
      "{$field_name}[0][value][time]" => $date->format($time_format),
    ];
    $this->submitForm($edit, 'Save');
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl()$match);
    
$transformer = new DateTimeToStringTransformer();

        $this->assertSame('', $transformer->transform(null));
    }

    public function testTransformWithDifferentTimezones()
    {
        $transformer = new DateTimeToStringTransformer('Asia/Hong_Kong', 'America/New_York', 'Y-m-d H:i:s');

        $input = new \DateTime('2010-02-03 12:05:06 America/New_York');
        $output = $input->format('Y-m-d H:i:s');
        $input->setTimezone(new \DateTimeZone('Asia/Hong_Kong'));

        $this->assertEquals($output$transformer->transform($input));
    }

    public function testTransformDateTimeImmutable()
    {
        $transformer = new DateTimeToStringTransformer('Asia/Hong_Kong', 'America/New_York', 'Y-m-d H:i:s');

        $input = new \DateTimeImmutable('2010-02-03 12:05:06 America/New_York');
        $output = $input->format('Y-m-d H:i:s');
        $input = $input->setTimezone(new \DateTimeZone('Asia/Hong_Kong'));

        

      'links' => [
        'self' => ['href' => $self_url],
      ],
      'data' => [
        'id' => $file->uuid(),
        'type' => 'file--file',
        'links' => [
          'self' => ['href' => $self_url],
        ],
        'attributes' => [
          'created' => (new \DateTime())->setTimestamp($file->getCreatedTime())->setTimezone(new \DateTimeZone('UTC'))->format(\DateTime::RFC3339),
          'changed' => (new \DateTime())->setTimestamp($file->getChangedTime())->setTimezone(new \DateTimeZone('UTC'))->format(\DateTime::RFC3339),
          'filemime' => 'text/plain',
          'filename' => $expected_as_filename ? $expected_filename : 'example.txt',
          'filesize' => strlen($this->testFileData),
          'langcode' => 'en',
          'status' => $expected_status,
          'uri' => [
            'value' => 'public://foobar/' . $expected_filename,
            'url' => base_path() . $this->siteDirectory . '/files/foobar/' . rawurlencode($expected_filename),
          ],
          'drupal_internal__fid' => (int) $file->id(),
        ],

      'links' => [
        'self' => ['href' => $self_url],
      ],
      'data' => [
        'id' => $this->entity->uuid(),
        'type' => 'entity_test_computed_field--entity_test_computed_field',
        'links' => [
          'self' => ['href' => $self_url],
        ],
        'attributes' => [
          'created' => (new \DateTime())->setTimestamp($this->entity->get('created')->value)->setTimezone(new \DateTimeZone('UTC'))->format(\DateTime::RFC3339),
          'name' => 'Llama',
          'drupal_internal__id' => 1,
          'computed_string_field' => NULL,
          'computed_test_cacheable_string_field' => 'computed test cacheable string field',
        ],
        'relationships' => [
          'computed_reference_field' => [
            'data' => NULL,
            'links' => [
              'related' => ['href' => $self_url . '/computed_reference_field'],
              'self' => ['href' => $self_url . '/relationships/computed_reference_field'],
            ],
'langcode' => [
        ['value' => 'en'],
      ],
      'name' => [
        ['value' => $this->values['name']],
      ],
      'type' => [
        ['value' => 'entity_test_mulrev'],
      ],
      'created' => [
        [
          'value' => (new \DateTime())->setTimestamp((int) $this->entity->get('created')->value)->setTimezone(new \DateTimeZone('UTC'))->format(\DateTime::RFC3339),
          'format' => \DateTime::RFC3339,
        ],
      ],
      'user_id' => [
        [
          // id() will return the string value as it comes from the database.           'target_id' => (int) $this->user->id(),
          'target_type' => $this->user->getEntityTypeId(),
          'target_uuid' => $this->user->uuid(),
          'url' => $this->user->toUrl()->toString(),
        ],
      ],
if ($this->twig->hasExtension($extension::class)) {
                continue;
            }
            $this->twig->addExtension($extension);
        }
        if ($this->twig->hasExtension(CoreExtension::class) && $this->platformTwig->hasExtension(CoreExtension::class)) {
            /** @var CoreExtension $coreExtensionInternal */
            $coreExtensionInternal = $this->twig->getExtension(CoreExtension::class);
            /** @var CoreExtension $coreExtensionGlobal */
            $coreExtensionGlobal = $this->platformTwig->getExtension(CoreExtension::class);

            $coreExtensionInternal->setTimezone($coreExtensionGlobal->getTimezone());
            $coreExtensionInternal->setDateFormat(...$coreExtensionGlobal->getDateFormat());
            $coreExtensionInternal->setNumberFormat(...$coreExtensionGlobal->getNumberFormat());
        }
    }

    /** * @param array<string, mixed> $data * * @throws StringTemplateRenderingException */
    public function render(string $templateSource, array $data, Context $context, bool $htmlEscape = true): string
    {

          'value' => 'Llama',
        ],
      ],
      'langcode' => [
        [
          'value' => 'en',
        ],
      ],
      'created' => [
        [
          'value' => (new \DateTime())->setTimestamp((int) $this->entity->get('created')->value)->setTimezone(new \DateTimeZone('UTC'))->format(\DateTime::RFC3339),
          'format' => \DateTime::RFC3339,
        ],
      ],
      'user_id' => [
        [
          'target_id' => (int) $author->id(),
          'target_type' => 'user',
          'target_uuid' => $author->uuid(),
          'url' => $author->toUrl()->toString(),
        ],
      ],
      
// determine the timezone     if (false !== $timezone) {
        if (null === $timezone) {
            $timezone = $env->getExtension(CoreExtension::class)->getTimezone();
        } elseif (!$timezone instanceof \DateTimeZone) {
            $timezone = new \DateTimeZone($timezone);
        }
    }

    // immutable dates     if ($date instanceof \DateTimeImmutable) {
        return false !== $timezone ? $date->setTimezone($timezone) : $date;
    }

    if ($date instanceof \DateTimeInterface) {
        $date = clone $date;
        if (false !== $timezone) {
            $date->setTimezone($timezone);
        }

        return $date;
    }

    
'links' => [
        'self' => ['href' => $self_url],
      ],
      'data' => [
        'id' => $this->entity->uuid(),
        'type' => 'comment--comment',
        'links' => [
          'self' => ['href' => $self_url],
        ],
        'attributes' => [
          'created' => '1973-11-29T21:33:09+00:00',
          'changed' => (new \DateTime())->setTimestamp($this->entity->getChangedTime())->setTimezone(new \DateTimeZone('UTC'))->format(\DateTime::RFC3339),
          'comment_body' => [
            'value' => 'The name "llama" was adopted by European settlers from native Peruvians.',
            'format' => 'plain_text',
            'processed' => "<p>The name &quot;llama&quot; was adopted by European settlers from native Peruvians.</p>\n",
          ],
          'default_langcode' => TRUE,
          'entity_type' => 'entity_test',
          'field_name' => 'comment',
          'homepage' => NULL,
          'langcode' => 'en',
          'name' => NULL,
          
public function transform(mixed $dateTime): string
    {
        if (null === $dateTime) {
            return '';
        }

        if (!$dateTime instanceof \DateTimeInterface) {
            throw new TransformationFailedException('Expected a \DateTimeInterface.');
        }

        $dateTime = \DateTimeImmutable::createFromInterface($dateTime);
        $dateTime = $dateTime->setTimezone(new \DateTimeZone($this->outputTimezone));

        return $dateTime->format($this->generateFormat);
    }

    /** * Transforms a date string in the configured timezone into a DateTime object. * * @param string $value A value as produced by PHP's date() function * * @throws TransformationFailedException If the given value is not a string, * or could not be transformed */
$storage_format = DateTimeItemInterface::DATETIME_STORAGE_FORMAT;
    }

    $storage_timezone = new \DateTimezone(DateTimeItemInterface::STORAGE_TIMEZONE);

    foreach ($values as &$item) {
      if (!empty($item['value']) && $item['value'] instanceof DrupalDateTime) {
        /** @var \Drupal\Core\Datetime\DrupalDateTime $date */
        $date = $item['value'];

        // Adjust the date for storage.         $item['value'] = $date->setTimezone($storage_timezone)->format($storage_format);
      }
    }
    return $values;
  }

  /** * Creates a date object for use as a default value. * * This will take a default value, apply the proper timezone for display in * a widget, and set the default time for date-only fields. * * @param \Drupal\Core\Datetime\DrupalDateTime $date * The UTC default date. * @param string $timezone * The timezone to apply. * * @return \Drupal\Core\Datetime\DrupalDateTime * A date object for use as a default value in a field widget. */
if ( 'U' === $format || 'G' === $format ) {
        $time = $datetime->getTimestamp();

        // Returns a sum of timestamp with timezone offset. Ideally should never be used.         if ( ! $gmt ) {
            $time += $datetime->getOffset();
        }
    } elseif ( $translate ) {
        $time = wp_date( $format$datetime->getTimestamp()$gmt ? new DateTimeZone( 'UTC' ) : null );
    } else {
        if ( $gmt ) {
            $datetime = $datetime->setTimezone( new DateTimeZone( 'UTC' ) );
        }

        $time = $datetime->format( $format );
    }

    /** * Filters the localized time a post was written. * * @since 2.6.0 * * @param string|int $time Formatted date string or Unix timestamp if `$format` is 'U' or 'G'. * @param string $format Format to use for retrieving the time the post was written. * Accepts 'G', 'U', or PHP date format. * @param bool $gmt Whether to retrieve the GMT time. */
public function testSupportsDenormalization() {
    $this->assertTrue($this->normalizer->supportsDenormalization($this->data->reveal(), Timestamp::class));
  }

  /** * @covers ::normalize */
  public function testNormalize() {
    $random_rfc_3339_string = $this->randomMachineName();

    $drupal_date_time = $this->prophesize(TimestampNormalizerTestDrupalDateTime::class);
    $drupal_date_time->setTimezone(new \DateTimeZone('UTC'))
      ->willReturn($drupal_date_time->reveal());
    $drupal_date_time->format(\DateTime::RFC3339)
      ->willReturn($random_rfc_3339_string);

    $this->data->getDateTime()
      ->willReturn($drupal_date_time->reveal());

    $normalized = $this->normalizer->normalize($this->data->reveal());
    $this->assertSame($random_rfc_3339_string$normalized);
  }

  
Home | Imprint | This part of the site doesn't use cookies.