protected function DateTimePlus::constructFromFormat

Creates a date object from an input format.

1 call to DateTimePlus::constructFromFormat()
DateTimePlus::__construct in drupal/core/lib/Drupal/Component/Datetime/DateTimePlus.php
Constructs a date object set to a requested date and timezone.

File

drupal/core/lib/Drupal/Component/Datetime/DateTimePlus.php, line 390
Definition of Drupal\Component\Datetime\DateTimePlus

Class

DateTimePlus
Extends DateTime().

Namespace

Drupal\Component\Datetime

Code

protected function constructFromFormat() {

  // Tries to create a date from the format and use it if possible.
  // A regular try/catch won't work right here, if the value is
  // invalid it doesn't return an exception.
  try {
    parent::__construct('', $this->inputTimeZoneAdjusted);
    $date = parent::createFromFormat($this->inputFormatAdjusted, $this->inputTimeAdjusted, $this->inputTimeZoneAdjusted);
    if (!$date instanceof \DateTime) {
      throw new \Exception('The date cannot be created from a format.');
    }
    else {
      $this
        ->setTimestamp($date
        ->getTimestamp());
      $this
        ->setTimezone($date
        ->getTimezone());
      try {

        // The createFromFormat function is forgiving, it might
        // create a date that is not exactly a match for the provided
        // value, so test for that. For instance, an input value of
        // '11' using a format of Y (4 digits) gets created as
        // '0011' instead of '2011'.
        // Use the parent::format() because we do not want to use
        // the IntlDateFormatter here.
        if ($this->validateFormat && parent::format($this->inputFormatAdjusted) != $this->inputTimeRaw) {
          throw new \Exception('The created date does not match the input value.');
        }
      } catch (\Exception $e) {
        $this->errors[] = $e
          ->getMessage();
      }
    }
  } catch (\Exception $e) {
    $this->errors[] = $e
      ->getMessage();
  }
}