function DateTimeTest::testTimeZoneHandling

Same name and namespace in other branches
  1. 9 core/modules/system/tests/src/Functional/System/DateTimeTest.php \Drupal\Tests\system\Functional\System\DateTimeTest::testTimeZoneHandling()
  2. 10 core/modules/system/tests/src/Functional/System/DateTimeTest.php \Drupal\Tests\system\Functional\System\DateTimeTest::testTimeZoneHandling()
  3. 11.x core/modules/system/tests/src/Functional/System/DateTimeTest.php \Drupal\Tests\system\Functional\System\DateTimeTest::testTimeZoneHandling()

Test time zones and DST handling.

File

core/modules/system/tests/src/Functional/System/DateTimeTest.php, line 55

Class

DateTimeTest
Configure date and time settings. Test date formatting and time zone handling, including daylight saving time.

Namespace

Drupal\Tests\system\Functional\System

Code

public function testTimeZoneHandling() {
    // Setup date/time settings for Honolulu time.
    $config = $this->config('system.date')
        ->set('timezone.default', 'Pacific/Honolulu')
        ->set('timezone.user.configurable', 0)
        ->save();
    DateFormat::load('medium')->setPattern('Y-m-d H:i:s O')
        ->save();
    // Create some nodes with different authored-on dates.
    $date1 = '2007-01-31 21:00:00 -1000';
    $date2 = '2007-07-31 21:00:00 -1000';
    $this->drupalCreateContentType([
        'type' => 'article',
    ]);
    $node1 = $this->drupalCreateNode([
        'created' => strtotime($date1),
        'type' => 'article',
    ]);
    $node2 = $this->drupalCreateNode([
        'created' => strtotime($date2),
        'type' => 'article',
    ]);
    // Confirm date format and time zone.
    $this->drupalGet('node/' . $node1->id());
    $this->assertText('2007-01-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.');
    $this->drupalGet('node/' . $node2->id());
    $this->assertText('2007-07-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.');
    // Set time zone to Los Angeles time.
    $config->set('timezone.default', 'America/Los_Angeles')
        ->save();
    \Drupal::entityTypeManager()->getViewBuilder('node')
        ->resetCache([
        $node1,
        $node2,
    ]);
    // Confirm date format and time zone.
    $this->drupalGet('node/' . $node1->id());
    $this->assertText('2007-01-31 23:00:00 -0800', 'Date should be two hours ahead, with GMT offset of -8 hours.');
    $this->drupalGet('node/' . $node2->id());
    $this->assertText('2007-08-01 00:00:00 -0700', 'Date should be three hours ahead, with GMT offset of -7 hours.');
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.