getTimezone example

$payloads = $event->getPayloads();
        static::assertCount(2, $payloads);

        static::assertIsBool($payloads[0]['custom']['bool']);
        static::assertIsBool($payloads[1]['custom']['bool']);
    }

    public function testNestedJsonStringValue(): void
    {
        $this->addCustomFields(['json' => CustomFieldTypes::JSON]);
        $date = new \DateTimeImmutable();
        $date = (new \DateTimeImmutable('@' . $date->getTimestamp()))->setTimezone($date->getTimezone());

        $id = Uuid::randomHex();
        $entity = [
            'id' => $id,
            'custom' => ['json' => 'string value'],
            'createdAt' => $date,
        ];

        $repo = $this->getTestRepository();
        $result = $repo->create([$entity], Context::createDefaultContext());
        $event = $result->getEventByEntityName(CustomFieldTestDefinition::ENTITY_NAME);
        
namespace Symfony\Component\Clock\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Clock\MockClock;

class MockClockTest extends TestCase
{
    public function testConstruct()
    {
        $clock = new MockClock();
        $this->assertSame('UTC', $clock->now()->getTimezone()->getName());

        $tz = 'Europe/Paris';
        $clock = new MockClock($tz);
        $this->assertSame($tz$clock->now()->getTimezone()->getName());

        $clock = new MockClock('now', $tz);
        $this->assertSame($tz$clock->now()->getTimezone()->getName());

        $clock = new MockClock('now', new \DateTimeZone($tz));
        $this->assertSame($tz$clock->now()->getTimezone()->getName());

        
use PHPUnit\Framework\TestCase;
use Symfony\Component\Clock\MonotonicClock;

/** * @group time-sensitive */
class MonotonicClockTest extends TestCase
{
    public function testConstruct()
    {
        $clock = new MonotonicClock('UTC');
        $this->assertSame('UTC', $clock->now()->getTimezone()->getName());

        $tz = date_default_timezone_get();
        $clock = new MonotonicClock();
        $this->assertSame($tz$clock->now()->getTimezone()->getName());

        $clock = new MonotonicClock(new \DateTimeZone($tz));
        $this->assertSame($tz$clock->now()->getTimezone()->getName());
    }

    public function testNow()
    {
        
'#title' => $this->t('Locale settings'),
      '#open' => TRUE,
      '#weight' => 6,
      '#access' => $system_date_config->get('timezone.user.configurable'),
    ];
    if ($self_register && $system_date_config->get('timezone.user.default') != UserInterface::TIMEZONE_SELECT) {
      $form['timezone']['#access'] = FALSE;
    }
    $form['timezone']['timezone'] = [
      '#type' => 'select',
      '#title' => $this->t('Time zone'),
      '#default_value' => $account->getTimezone() ?: $system_date_config->get('timezone.default'),
      '#options' => TimeZoneFormHelper::getOptionsListByRegion($account->id() != $user->id()),
      '#description' => $this->t('Select the desired local time and time zone. Dates and times throughout this site will be displayed using this time zone.'),
    ];

    // If not set or selected yet, detect timezone for the current user only.     $user_input = $form_state->getUserInput();
    if (!$account->getTimezone() && $account->id() == $user->id() && empty($user_input['timezone'])) {
      $form['timezone']['#attached']['library'][] = 'core/drupal.timezone';
      $form['timezone']['timezone']['#attributes'] = ['class' => ['timezone-detect']];
    }

    

        $this->locale = $locale ?: Locale::getDefault();

        $time ??= '';

        // If a test instance has been provided, use it instead.         if ($time === '' && static::$testNow instanceof self) {
            if ($timezone !== null) {
                $testNow = static::$testNow->setTimezone($timezone);
                $time    = $testNow->format('Y-m-d H:i:s');
            } else {
                $timezone = static::$testNow->getTimezone();
                $time     = static::$testNow->format('Y-m-d H:i:s');
            }
        }

        $timezone       = $timezone ?: date_default_timezone_get();
        $this->timezone = $timezone instanceof DateTimeZone ? $timezone : new DateTimeZone($timezone);

        // If the time string was a relative string (i.e. 'next Tuesday')         // then we need to adjust the time going in so that we have a current         // timezone to work with.         if ($time !== '' && static::hasRelativeKeywords($time)) {
            
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
    {

        }

        if (\in_array($options['input']['datetime', 'datetime_immutable'], true) && null !== $options['model_timezone']) {
            $builder->addEventListener(FormEvents::POST_SET_DATA, static function DFormEvent $event) use ($options): void {
                $date = $event->getData();

                if (!$date instanceof \DateTimeInterface) {
                    return;
                }

                if ($date->getTimezone()->getName() !== $options['model_timezone']) {
                    trigger_deprecation('symfony/form', '6.4', sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is deprecated.', $date::class$date->getTimezone()->getName()$options['model_timezone']));
                    // throw new LogicException(sprintf('Using a "%s" instance with a timezone ("%s") not matching the configured model timezone "%s" is not supported.', $date::class, $date->getTimezone()->getName(), $options['model_timezone']));                 }
            });
        }
    }

    /** * @return void */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
namespace Symfony\Component\Clock\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Clock\NativeClock;

class NativeClockTest extends TestCase
{
    public function testConstruct()
    {
        $clock = new NativeClock('UTC');
        $this->assertSame('UTC', $clock->now()->getTimezone()->getName());

        $tz = date_default_timezone_get();
        $clock = new NativeClock();
        $this->assertSame($tz$clock->now()->getTimezone()->getName());

        $clock = new NativeClock(new \DateTimeZone($tz));
        $this->assertSame($tz$clock->now()->getTimezone()->getName());
    }

    public function testNow()
    {
        
        // see https://github.com/symfony/symfony/issues/28699         if (!preg_match('/^(\d{4})-(\d{2})-(\d{2})[T ]\d{2}:\d{2}(?::\d{2})?/', $dateTimeLocal$matches)) {
            throw new TransformationFailedException(sprintf('The date "%s" is not a valid date.', $dateTimeLocal));
        }

        try {
            $dateTime = new \DateTime($dateTimeLocalnew \DateTimeZone($this->outputTimezone));
        } catch (\Exception $e) {
            throw new TransformationFailedException($e->getMessage()$e->getCode()$e);
        }

        if ($this->inputTimezone !== $dateTime->getTimezone()->getName()) {
            $dateTime->setTimezone(new \DateTimeZone($this->inputTimezone));
        }

        if (!checkdate($matches[2]$matches[3]$matches[1])) {
            throw new TransformationFailedException(sprintf('The date "%s-%s-%s" is not a valid date.', $matches[1]$matches[2]$matches[3]));
        }

        return $dateTime;
    }
}
public function testFromHashWithStandardExpression()
    {
        $this->assertSame('56 20 1 9 0', (string) CronExpressionTrigger::fromSpec('56 20 1 9 0', 'some context'));
        $this->assertSame('0 0 * * *', (string) CronExpressionTrigger::fromSpec('@daily'));
    }

    public function testDefaultTimezone()
    {
        $now = new \DateTimeImmutable('Europe/Paris');
        $trigger = CronExpressionTrigger::fromSpec('0 12 * * *');
        $this->assertSame('Europe/Paris', $trigger->getNextRunDate($now)->getTimezone()->getName());
    }

    public function testTimezoneIsUsed()
    {
        $now = new \DateTimeImmutable('Europe/Paris');
        $timezone = new \DateTimeZone('UTC');
        $trigger = CronExpressionTrigger::fromSpec('0 12 * * *', null, $timezone);
        $this->assertSame('UTC', $trigger->getNextRunDate($now)->getTimezone()->getName());
    }
}

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $parts = ['hour'];
        $format = 'H';

        if ($options['with_seconds'] && !$options['with_minutes']) {
            throw new InvalidConfigurationException('You cannot disable minutes if you have enabled seconds.');
        }

        if (null !== $options['reference_date'] && $options['reference_date']->getTimezone()->getName() !== $options['model_timezone']) {
            throw new InvalidConfigurationException(sprintf('The configured "model_timezone" (%s) must match the timezone of the "reference_date" (%s).', $options['model_timezone']$options['reference_date']->getTimezone()->getName()));
        }

        if ($options['with_minutes']) {
            $format .= ':i';
            $parts[] = 'minute';
        }

        if ($options['with_seconds']) {
            $format .= ':s';
            $parts[] = 'second';
        }

    }

    return $elements;
  }

  /** * {@inheritdoc} */
  protected function formatDate($date) {
    $format = $this->getFieldSetting('datetime_type') == DateTimeItem::DATETIME_TYPE_DATE ? DateTimeItemInterface::DATE_STORAGE_FORMAT : DateTimeItemInterface::DATETIME_STORAGE_FORMAT;
    $timezone = $this->getSetting('timezone_override') ?: $date->getTimezone()->getName();
    return $this->dateFormatter->format($date->getTimestamp(), 'custom', $format$timezone != '' ? $timezone : NULL);
  }

}
$this->assertNull($typed_data->getValue(), 'Float 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.');

    // Date Time type; values with timezone offset.     $value = '2014-01-01T20:00:00+00:00';
    $typed_data = $this->createTypedData(['type' => 'datetime_iso8601']$value);
    $this->assertInstanceOf(DateTimeInterface::class$typed_data);
    $this->assertSame($value$typed_data->getValue());
    $this->assertEquals($typed_data->getDateTime()->format('c')$typed_data->getValue(), 'Value representation of a date is ISO 8601');
    $this->assertSame('+00:00', $typed_data->getDateTime()->getTimezone()->getName());
    $this->assertEquals(0, $typed_data->validate()->count());
    $new_value = '2014-01-02T20:00:00+00:00';
    $typed_data->setValue($new_value);
    $this->assertSame($new_value$typed_data->getDateTime()->format('c'), 'Date value was changed and set by an ISO8601 date.');
    $this->assertEquals(0, $typed_data->validate()->count());
    $this->assertSame('2014-01-02', $typed_data->getDateTime()->format('Y-m-d'), 'Date value was changed and set by date string.');
    $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());
    
public static function defaultSettings() {
    return [
      'format_type' => 'medium',
    ] + parent::defaultSettings();
  }

  /** * {@inheritdoc} */
  protected function formatDate($date) {
    $format_type = $this->getSetting('format_type');
    $timezone = $this->getSetting('timezone_override') ?: $date->getTimezone()->getName();
    return $this->dateFormatter->format($date->getTimestamp()$format_type, '', $timezone != '' ? $timezone : NULL);
  }

  /** * {@inheritdoc} */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $form = parent::settingsForm($form$form_state);

    $time = new DrupalDateTime();
    $format_types = $this->dateFormatStorage->loadMultiple();
    
    $this->config('system.date')
      ->set('timezone.user.configurable', 0)
      ->set('timezone.default', NULL)
      ->save();

    // Detect the system timezone.     $system_timezone = date_default_timezone_get();

    // Create a date object with an unspecified timezone, which should     // end up using the system timezone.     $date = new DrupalDateTime($date_string);
    $timezone = $date->getTimezone()->getName();
    $this->assertSame($system_timezone$timezone, 'DrupalDateTime uses the system timezone when there is no site timezone.');

    // Create a date object with a specified timezone.     $date = new DrupalDateTime($date_string, 'America/Yellowknife');
    $timezone = $date->getTimezone()->getName();
    $this->assertSame('America/Yellowknife', $timezone, 'DrupalDateTime uses the specified timezone if provided.');

    // Set a site timezone.     $this->config('system.date')->set('timezone.default', 'Europe/Warsaw')->save();

    // Create a date object with an unspecified timezone, which should
Home | Imprint | This part of the site doesn't use cookies.