You are here

public static function DateTimePlus::createFromArray in Drupal 8

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Component/Datetime/DateTimePlus.php \Drupal\Component\Datetime\DateTimePlus::createFromArray()
  2. 10 core/lib/Drupal/Component/Datetime/DateTimePlus.php \Drupal\Component\Datetime\DateTimePlus::createFromArray()

Creates a date object from an array of date parts.

Converts the input value into an ISO date, forcing a full ISO date even if some values are missing.

Parameters

array $date_parts: An array of date parts, like ('year' => 2014, 'month' => 4).

mixed $timezone: (optional) \DateTimeZone object, time zone string or NULL. NULL uses the default system time zone. Defaults to NULL.

array $settings: (optional) A keyed array for settings, suitable for passing on to __construct().

Return value

static A new DateTimePlus object.

Throws

\InvalidArgumentException If the array date values or value combination is not correct.

2 calls to DateTimePlus::createFromArray()
DateTimePlusTest::testDateArrays in core/tests/Drupal/Tests/Component/Datetime/DateTimePlusTest.php
Test creating dates from string and array input.
DateTimePlusTest::testInvalidDateArrays in core/tests/Drupal/Tests/Component/Datetime/DateTimePlusTest.php
Test creating dates from invalid array input.

File

core/lib/Drupal/Component/Datetime/DateTimePlus.php, line 163

Class

DateTimePlus
Wraps DateTime().

Namespace

Drupal\Component\Datetime

Code

public static function createFromArray(array $date_parts, $timezone = NULL, $settings = []) {
  $date_parts = static::prepareArray($date_parts, TRUE);
  if (static::checkArray($date_parts)) {

    // Even with validation, we can end up with a value that the
    // DateTime class won't handle, like a year outside the range
    // of -9999 to 9999, which will pass checkdate() but
    // fail to construct a date object.
    $iso_date = static::arrayToISO($date_parts);
    return new static($iso_date, $timezone, $settings);
  }
  else {
    throw new \InvalidArgumentException('The array contains invalid values.');
  }
}