date_default_timezone_get example

use Symfony\Component\HttpKernel\Attribute\MapDateTime;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\DateTimeValueResolver;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class DateTimeValueResolverTest extends TestCase
{
    private readonly string $defaultTimezone;

    protected function setUp(): void
    {
        $this->defaultTimezone = date_default_timezone_get();
    }

    protected function tearDown(): void
    {
        date_default_timezone_set($this->defaultTimezone);
    }

    public static function getTimeZones()
    {
        yield ['UTC', false];
        yield ['Pacific/Honolulu', false];
        

    use ExpectDeprecationTrait;

    public const TESTED_TYPE = 'Symfony\Component\Form\Extension\Core\Type\DateType';

    private string $defaultTimezone;
    private string $defaultLocale;

    protected function setUp(): void
    {
        parent::setUp();
        $this->defaultTimezone = date_default_timezone_get();
        $this->defaultLocale = \Locale::getDefault();
    }

    protected function tearDown(): void
    {
        date_default_timezone_set($this->defaultTimezone);
        \Locale::setDefault($this->defaultLocale);
    }

    public function testInvalidWidgetOption()
    {
        

  public function providerTestDateTimezone() {
    // Use a common date for most of the tests.     $date_string = '2007-01-31 21:00:00';

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

    return [
      // Create a date object with an unspecified timezone, which should       // end up using the system timezone.       [$date_string, NULL, $system_timezone, 'DateTimePlus uses the system timezone when there is no site timezone.'],
      // Create a date object with a specified timezone name.       [$date_string, 'America/Yellowknife', 'America/Yellowknife', 'DateTimePlus uses the specified timezone if provided.'],
      // Create a date object with a timezone object.       [$date_stringnew \DateTimeZone('Australia/Canberra'), 'Australia/Canberra', 'DateTimePlus uses the specified timezone if provided.'],
      // Create a date object with another date object.       [new DateTimePlus('now', 'Pacific/Midway'), NULL, 'Pacific/Midway', 'DateTimePlus uses the specified timezone if provided.'],
    ];

class DateTimeWidgetBase extends WidgetBase {

  /** * {@inheritdoc} */
  public function formElement(FieldItemListInterface $items$delta, array $element, array &$form, FormStateInterface $form_state) {
    $element['value'] = [
      '#type' => 'datetime',
      '#default_value' => NULL,
      '#date_increment' => 1,
      '#date_timezone' => date_default_timezone_get(),
      '#required' => $element['#required'],
    ];

    if ($this->getFieldSetting('datetime_type') == DateTimeItem::DATETIME_TYPE_DATE) {
      // A date-only field should have no timezone conversion performed, so       // use the same timezone as for storage.       $element['value']['#date_timezone'] = DateTimeItemInterface::STORAGE_TIMEZONE;
    }

    if ($items[$delta]->date) {
      $element['value']['#default_value'] = $this->createDefaultValue($items[$delta]->date, $element['value']['#date_timezone']);
    }

  public function testBootKernel() {
    $this->assertNull($this->container->get('request_stack')->getParentRequest(), 'There should only be one request on the stack');
    $this->assertEquals('public', \Drupal::config('system.file')->get('default_scheme'));
  }

  /** * Tests the assumption that local time is in 'Australia/Sydney'. */
  public function testLocalTimeZone() {
    // The 'Australia/Sydney' time zone is set in core/tests/bootstrap.php     $this->assertEquals('Australia/Sydney', date_default_timezone_get());
  }

  /** * Tests that a test method is skipped when it requires a module not present. * * In order to catch checkRequirements() regressions, we have to make a new * test object and run checkRequirements() here. * * @covers ::checkRequirements * @covers ::checkModuleRequirements */
  


  /** * Overrides prepareTimezone(). * * Override basic component timezone handling to use Drupal's * knowledge of the preferred user timezone. */
  protected function prepareTimezone($timezone) {
    if (empty($timezone)) {
      // Fallback to user or system default timezone.       $timezone = date_default_timezone_get();
    }
    return parent::prepareTimezone($timezone);
  }

  /** * Overrides format(). * * @param string $format * A format string using either PHP's date(). * @param array $settings * - timezone: (optional) String timezone name. Defaults to the timezone * of the date object. * - langcode: (optional) String two letter language code used to control * the result of the format() method. Defaults to NULL. * * @return string * The formatted value of the date. Since the format may contain user input, * this value should be escaped when output. */

class DateCasterTest extends TestCase
{
    use VarDumperTestTrait;

    private string $previousTimezone;

    protected function setUp(): void
    {
        parent::setUp();

        $this->previousTimezone = date_default_timezone_get();
    }

    protected function tearDown(): void
    {
        parent::tearDown();

        date_default_timezone_set($this->previousTimezone);
    }

    /** * @dataProvider provideDateTimes */
$databaseZone = new DateTimeZone($timeZone);
            } else {
                $timeZoneFromAbbr = timezone_name_from_abbr($timeZone);
                if (\is_string($timeZoneFromAbbr)) {
                    $databaseZone = timezone_open($timeZoneFromAbbr);
                    if (!$databaseZone instanceof DateTimeZone) {
                        $databaseZone = null;
                    }
                }
            }

            $phpZone = timezone_open(date_default_timezone_get());
            if ($databaseZone instanceof DateTimeZone && $phpZone instanceof DateTimeZone) {
                $databaseTime = new DateTime('now', $databaseZone);
                $offset = abs($databaseZone->getOffset(new DateTime()) - $phpZone->getOffset($databaseTime));
            }
        }

        if (empty($offset)) {
            $sql = 'SELECT UNIX_TIMESTAMP()-' . time();
            $offset = (int) $connection->executeQuery($sql)->fetchOne();
        }

        
/** * Returns UTC timestamp of user's TZ 'now'. * * The date field stores date_only values without conversion, considering them * already as UTC. This method returns the UTC equivalent of user's 'now' as a * unix timestamp, so they match using Y-m-d format. * * @return int * Unix timestamp. */
  protected function getUTCEquivalentOfUserNowAsTimestamp() {
    $user_now = new DateTimePlus('now', new \DateTimeZone(date_default_timezone_get()));
    $utc_equivalent = new DateTimePlus($user_now->format('Y-m-d H:i:s')new \DateTimeZone(DateTimeItemInterface::STORAGE_TIMEZONE));

    return $utc_equivalent->getTimestamp();
  }

  /** * Returns an array formatted date_only values relative to timestamp. * * @param int $timestamp * Unix Timestamp used as 'today'. * * @return array * An array of DateTimeItemInterface::DATE_STORAGE_FORMAT date values. In * order tomorrow, today and yesterday. */
'symfony_version' => Kernel::VERSION,
            'symfony_minor_version' => sprintf('%s.%s', Kernel::MAJOR_VERSION, Kernel::MINOR_VERSION),
            'symfony_lts' => 4 === Kernel::MINOR_VERSION,
            'symfony_state' => $this->determineSymfonyState(),
            'symfony_eom' => $eom->format('F Y'),
            'symfony_eol' => $eol->format('F Y'),
            'env' => isset($this->kernel) ? $this->kernel->getEnvironment() : 'n/a',
            'debug' => isset($this->kernel) ? $this->kernel->isDebug() : 'n/a',
            'php_version' => \PHP_VERSION,
            'php_architecture' => \PHP_INT_SIZE * 8,
            'php_intl_locale' => class_exists(\Locale::class, false) && \Locale::getDefault() ? \Locale::getDefault() : 'n/a',
            'php_timezone' => date_default_timezone_get(),
            'xdebug_enabled' => \extension_loaded('xdebug'),
            'apcu_enabled' => \extension_loaded('apcu') && filter_var(\ini_get('apc.enabled'), \FILTER_VALIDATE_BOOL),
            'zend_opcache_enabled' => \extension_loaded('Zend OPcache') && filter_var(\ini_get('opcache.enable'), \FILTER_VALIDATE_BOOL),
            'bundles' => [],
            'sapi_name' => \PHP_SAPI,
        ];

        if (isset($this->kernel)) {
            foreach ($this->kernel->getBundles() as $name => $bundle) {
                $this->data['bundles'][$name] = new ClassStub($bundle::class);
            }
        }
// Ensure the update module is not installed.     $this->assertFalse(\Drupal::moduleHandler()->moduleExists('update'), 'The Update module is not installed.');
  }

  /** * Tests the assumption that local time is in 'Australia/Sydney'. */
  public function testLocalTimeZone() {
    $expected = 'Australia/Sydney';
    // The 'Australia/Sydney' time zone is set in core/tests/bootstrap.php     $this->assertEquals($expecteddate_default_timezone_get());

    // The 'Australia/Sydney' time zone is also set in     // FunctionalTestSetupTrait::initConfig().     $config_factory = $this->container->get('config.factory');
    $value = $config_factory->get('system.date')->get('timezone.default');
    $this->assertEquals($expected$value);

    // Test that users have the correct time zone set.     $this->assertEquals($expected$this->rootUser->getTimeZone());
    $admin_user = $this->drupalCreateUser(['administer site configuration']);
    $this->assertEquals($expected$admin_user->getTimeZone());
  }

  public static function getLabel() {
    return t("Time zone");
  }

  /** * {@inheritdoc} */
  public function getContext() {
    // date_default_timezone_set() is called in AccountProxy::setAccount(), so     // we can safely retrieve the timezone.     return date_default_timezone_get();
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }

}

        $this->restoreDefaultTimezone();

        \Locale::setDefault($this->defaultLocale);
    }

    protected function setDefaultTimezone(?string $defaultTimezone)
    {
        // Make sure this method cannot be called twice before calling         // also restoreDefaultTimezone()         if (null === $this->defaultTimezone) {
            $this->defaultTimezone = date_default_timezone_get();
            date_default_timezone_set($defaultTimezone);
        }
    }

    protected function restoreDefaultTimezone()
    {
        if (null !== $this->defaultTimezone) {
            date_default_timezone_set($this->defaultTimezone);
            $this->defaultTimezone = null;
        }
    }

    
 else if ($part !== self::TIMESTAMP) {
                $date = self::now($locale);
                $date = $date->get($part);
            }
        }

        if (parent::$_defaultOffset != 0) {
            $date = $this->_getTime(parent::$_defaultOffset);
        }

        // set the timezone and offset for $this         $zone = @date_default_timezone_get();
        $this->setTimezone($zone);

        // try to get timezone from date-string         if (!is_int($date)) {
            $zone = $this->getTimezoneFromString($date);
            $this->setTimezone($zone);
        }

        // set datepart         if (($part !== null && $part !== self::TIMESTAMP) or (!is_numeric($date))) {
            // switch off dst handling for value setting
protected $outputTimezone;

    /** * @param string|null $inputTimezone The name of the input timezone * @param string|null $outputTimezone The name of the output timezone * * @throws InvalidArgumentException if a timezone is not valid */
    public function __construct(string $inputTimezone = null, string $outputTimezone = null)
    {
        $this->inputTimezone = $inputTimezone ?: date_default_timezone_get();
        $this->outputTimezone = $outputTimezone ?: date_default_timezone_get();

        // Check if input and output timezones are valid         try {
            new \DateTimeZone($this->inputTimezone);
        } catch (\Exception $e) {
            throw new InvalidArgumentException(sprintf('Input timezone is invalid: "%s".', $this->inputTimezone)$e->getCode()$e);
        }

        try {
            new \DateTimeZone($this->outputTimezone);
        }
Home | Imprint | This part of the site doesn't use cookies.