function DateTimePlusTest::testValidateFormat

Same name and namespace in other branches
  1. 8.9.x core/tests/Drupal/Tests/Component/Datetime/DateTimePlusTest.php \Drupal\Tests\Component\Datetime\DateTimePlusTest::testValidateFormat()
  2. 10 core/tests/Drupal/Tests/Component/Datetime/DateTimePlusTest.php \Drupal\Tests\Component\Datetime\DateTimePlusTest::testValidateFormat()
  3. 11.x core/tests/Drupal/Tests/Component/Datetime/DateTimePlusTest.php \Drupal\Tests\Component\Datetime\DateTimePlusTest::testValidateFormat()

Tests the $settings['validate_format'] parameter in ::createFromFormat().

File

core/tests/Drupal/Tests/Component/Datetime/DateTimePlusTest.php, line 838

Class

DateTimePlusTest
@coversDefaultClass <a href="/api/drupal/core%21lib%21Drupal%21Component%21Datetime%21DateTimePlus.php/class/DateTimePlus/9" title="Wraps DateTime()." class="local">\Drupal\Component\Datetime\DateTimePlus</a> @group Datetime

Namespace

Drupal\Tests\Component\Datetime

Code

public function testValidateFormat() {
    // Check that an input that does not strictly follow the input format will
    // produce the desired date. In this case the year string '11' doesn't
    // precisely match the 'Y' formatter parameter, but PHP will parse it
    // regardless. However, when formatted with the same string, the year will
    // be output with four digits. With the ['validate_format' => FALSE]
    // $settings, this will not thrown an exception.
    $date = DateTimePlus::createFromFormat('Y-m-d H:i:s', '11-03-31 17:44:00', 'UTC', [
        'validate_format' => FALSE,
    ]);
    $this->assertEquals('0011-03-31 17:44:00', $date->format('Y-m-d H:i:s'));
    // Parse the same date with ['validate_format' => TRUE] and make sure we
    // get the expected exception.
    $this->expectException(\UnexpectedValueException::class);
    $date = DateTimePlus::createFromFormat('Y-m-d H:i:s', '11-03-31 17:44:00', 'UTC', [
        'validate_format' => TRUE,
    ]);
}

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