View source
<?php
namespace Drupal\Tests\system\Functional\Datetime;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Tests\BrowserTestBase;
use Drupal\user\Entity\User;
class DrupalDateTimeTest extends BrowserTestBase {
protected static $modules = [];
protected $defaultTheme = 'stark';
protected function setUp() : void {
parent::setUp();
}
public function testSystemTimezone() {
$options = [
'query' => [
'date' => 'Tue+Sep+17+2013+21%3A35%3A31+GMT%2B0100+(BST)#',
],
];
$response = $this
->drupalGet('system/timezone/BST/3600/1', $options);
$this
->assertEquals('"Europe\\/London"', $response, 'Timezone AJAX callback successfully identifies and responds to a long-format date.');
}
public function testDateTimezone() {
$date_string = '2007-01-31 21:00:00';
$this
->config('system.date')
->set('timezone.user.configurable', 0)
->set('timezone.default', NULL)
->save();
$system_timezone = date_default_timezone_get();
$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.');
$date = new DrupalDateTime($date_string, 'America/Yellowknife');
$timezone = $date
->getTimezone()
->getName();
$this
->assertSame('America/Yellowknife', $timezone, 'DrupalDateTime uses the specified timezone if provided.');
$this
->config('system.date')
->set('timezone.default', 'Europe/Warsaw')
->save();
$date = new DrupalDateTime($date_string);
$timezone = $date
->getTimezone()
->getName();
$this
->assertSame('Europe/Warsaw', $timezone, 'DrupalDateTime uses the site timezone if provided.');
$this
->config('system.date')
->set('timezone.user.configurable', 1)
->save();
$test_user = $this
->drupalCreateUser([]);
$this
->drupalLogin($test_user);
$edit = [
'mail' => $test_user
->getEmail(),
'timezone' => 'Asia/Manila',
];
$this
->drupalGet('user/' . $test_user
->id() . '/edit');
$this
->submitForm($edit, 'Save');
\Drupal::entityTypeManager()
->getStorage('user')
->resetCache();
$this->container
->get('current_user')
->setAccount(User::load($test_user
->id()));
$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.');
}
public function testTimezoneFormat() {
$date = DrupalDateTime::createFromTimestamp(87654321, 'UTC');
$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.');
$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');
$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');
}
}