public static DateTimePlus::createFromFormat($format, $time, $timezone = NULL, $settings = array())
Creates a date object from an input format.
string $format: PHP date() type format for parsing the input. This is recommended to use things like negative years, which php's parser fails on, or any other specialized input with a known format. If provided the date will be created using the createFromFormat() method. @see http://php.net/manual/datetime.createfromformat.php
mixed $time: @see __construct()
mixed $timezone: @see __construct()
array $settings:
@see __construct()
static A new DateTimePlus object.
\Exception If the a date cannot be created from the given format, or if the created date does not match the input value.
public static function createFromFormat($format, $time, $timezone = NULL, $settings = array()) { if (!isset($settings['validate_format'])) { $settings['validate_format'] = TRUE; } // 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. $datetimeplus = new static('', $timezone, $settings); $date = \DateTime::createFromFormat($format, $time, $datetimeplus->getTimezone()); if (!$date instanceof \DateTime) { throw new \Exception('The date cannot be created from a format.'); } else { // Functions that parse date is forgiving, it might create a date that // is not exactly a match for the provided value, so test for that by // re-creating the date/time formatted string and comparing it to the input. For // instance, an input value of '11' using a format of Y (4 digits) gets // created as '0011' instead of '2011'. if ($date instanceof DateTimePlus) { $test_time = $date->format($format, $settings); } elseif ($date instanceof \DateTime) { $test_time = $date->format($format); } $datetimeplus->setTimestamp($date->getTimestamp()); $datetimeplus->setTimezone($date->getTimezone()); if ($settings['validate_format'] && $test_time != $time) { throw new \Exception('The created date does not match the input value.'); } } return $datetimeplus; }
© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Component!Datetime!DateTimePlus.php/function/DateTimePlus::createFromFormat/8.1.x