3 namespace Drupal\Component\Datetime;
5 use Drupal\Component\Utility\ToStringTrait;
10 * This class wraps the PHP DateTime class with more flexible initialization
11 * parameters, allowing a date to be created from an existing date object,
12 * a timestamp, a string with an unknown format, a string with a known
13 * format, or an array of date parts. It also adds an errors array
14 * and a __toString() method to the date object.
16 * This class is less lenient than the DateTime class. It changes
17 * the default behavior for handling date values like '2011-00-00'.
18 * The DateTime class would convert that value to '2010-11-30' and report
19 * a warning but not an error. This extension treats that as an error.
21 * As with the DateTime class, a date object may be created even if it has
22 * errors. It has an errors array attached to it that explains what the
23 * errors are. This is less disruptive than allowing datetime exceptions
24 * to abort processing. The calling script can decide what to do about
25 * errors using hasErrors() and getErrors().
27 * @method $this add(\DateInterval $interval)
28 * @method static array getLastErrors()
29 * @method $this modify(string $modify)
30 * @method $this setDate(int $year, int $month, int $day)
31 * @method $this setISODate(int $year, int $week, int $day = 1)
32 * @method $this setTime(int $hour, int $minute, int $second = 0, int $microseconds = 0)
33 * @method $this setTimestamp(int $unixtimestamp)
34 * @method $this setTimezone(\DateTimeZone $timezone)
35 * @method $this sub(\DateInterval $interval)
36 * @method int getOffset()
37 * @method int getTimestamp()
38 * @method \DateTimeZone getTimezone()
44 const FORMAT = 'Y-m-d H:i:s';
47 * A RFC7231 Compliant date.
49 * @see http://tools.ietf.org/html/rfc7231#section-7.1.1.1
51 * Example: Sun, 06 Nov 1994 08:49:37 GMT
53 const RFC7231 = 'D, d M Y H:i:s \G\M\T';
56 * An array of possible date parts.
58 protected static $dateParts = [
68 * The value of the time value passed to the constructor.
72 protected $inputTimeRaw = '';
75 * The prepared time, without timezone, for this date.
79 protected $inputTimeAdjusted = '';
82 * The value of the timezone passed to the constructor.
86 protected $inputTimeZoneRaw = '';
89 * The prepared timezone object used to construct this date.
93 protected $inputTimeZoneAdjusted = '';
96 * The value of the format passed to the constructor.
100 protected $inputFormatRaw = '';
103 * The prepared format, if provided.
107 protected $inputFormatAdjusted = '';
110 * The value of the language code passed to the constructor.
112 protected $langcode = NULL;
115 * An array of errors encountered when creating this date.
117 protected $errors = [];
120 * The DateTime object.
124 protected $dateTimeObject = NULL;
127 * Creates a date object from an input date object.
129 * @param \DateTime $datetime
131 * @param array $settings
135 * A new DateTimePlus object.
137 public static function createFromDateTime(\DateTime $datetime, $settings = []) {
138 return new static($datetime->format(static::FORMAT), $datetime->getTimezone(), $settings);
142 * Creates a date object from an array of date parts.
144 * Converts the input value into an ISO date, forcing a full ISO
145 * date even if some values are missing.
147 * @param array $date_parts
148 * An array of date parts, like ('year' => 2014, 'month' => 4).
149 * @param mixed $timezone
150 * (optional) \DateTimeZone object, time zone string or NULL. NULL uses the
151 * default system time zone. Defaults to NULL.
152 * @param array $settings
153 * (optional) A keyed array for settings, suitable for passing on to
157 * A new DateTimePlus object.
159 * @throws \InvalidArgumentException
160 * If the array date values or value combination is not correct.
162 public static function createFromArray(array $date_parts, $timezone = NULL, $settings = []) {
163 $date_parts = static::prepareArray($date_parts, TRUE);
164 if (static::checkArray($date_parts)) {
165 // Even with validation, we can end up with a value that the
166 // DateTime class won't handle, like a year outside the range
167 // of -9999 to 9999, which will pass checkdate() but
168 // fail to construct a date object.
169 $iso_date = static::arrayToISO($date_parts);
170 return new static($iso_date, $timezone, $settings);
173 throw new \InvalidArgumentException('The array contains invalid values.');
178 * Creates a date object from timestamp input.
180 * The timezone of a timestamp is always UTC. The timezone for a
181 * timestamp indicates the timezone used by the format() method.
183 * @param int $timestamp
185 * @param mixed $timezone
187 * @param array $settings
191 * A new DateTimePlus object.
193 * @throws \InvalidArgumentException
194 * If the timestamp is not numeric.
196 public static function createFromTimestamp($timestamp, $timezone = NULL, $settings = []) {
197 if (!is_numeric($timestamp)) {
198 throw new \InvalidArgumentException('The timestamp must be numeric.');
200 $datetime = new static('', $timezone, $settings);
201 $datetime->setTimestamp($timestamp);
206 * Creates a date object from an input format.
208 * @param string $format
209 * PHP date() type format for parsing the input. This is recommended
210 * to use things like negative years, which php's parser fails on, or
211 * any other specialized input with a known format. If provided the
212 * date will be created using the createFromFormat() method.
213 * @see http://php.net/manual/datetime.createfromformat.php
216 * @param mixed $timezone
218 * @param array $settings
219 * - validate_format: (optional) Boolean choice to validate the
220 * created date using the input format. The format used in
221 * createFromFormat() allows slightly different values than format().
222 * Using an input format that works in both functions makes it
223 * possible to a validation step to confirm that the date created
224 * from a format string exactly matches the input. This option
225 * indicates the format can be used for validation. Defaults to TRUE.
229 * A new DateTimePlus object.
231 * @throws \InvalidArgumentException
232 * If the a date cannot be created from the given format.
233 * @throws \UnexpectedValueException
234 * If the created date does not match the input value.
236 public static function createFromFormat($format, $time, $timezone = NULL, $settings = []) {
237 if (!isset($settings['validate_format'])) {
238 $settings['validate_format'] = TRUE;
241 // Tries to create a date from the format and use it if possible.
242 // A regular try/catch won't work right here, if the value is
243 // invalid it doesn't return an exception.
244 $datetimeplus = new static('', $timezone, $settings);
246 $date = \DateTime::createFromFormat($format, $time, $datetimeplus->getTimezone());
247 if (!$date instanceof \DateTime) {
248 throw new \InvalidArgumentException('The date cannot be created from a format.');
251 // Functions that parse date is forgiving, it might create a date that
252 // is not exactly a match for the provided value, so test for that by
253 // re-creating the date/time formatted string and comparing it to the input. For
254 // instance, an input value of '11' using a format of Y (4 digits) gets
255 // created as '0011' instead of '2011'.
256 if ($date instanceof DateTimePlus) {
257 $test_time = $date->format($format, $settings);
259 elseif ($date instanceof \DateTime) {
260 $test_time = $date->format($format);
262 $datetimeplus->setTimestamp($date->getTimestamp());
263 $datetimeplus->setTimezone($date->getTimezone());
265 if ($settings['validate_format'] && $test_time != $time) {
266 throw new \UnexpectedValueException('The created date does not match the input value.');
269 return $datetimeplus;
273 * Constructs a date object set to a requested date and timezone.
275 * @param string $time
276 * (optional) A date/time string. Defaults to 'now'.
277 * @param mixed $timezone
278 * (optional) \DateTimeZone object, time zone string or NULL. NULL uses the
279 * default system time zone. Defaults to NULL. Note that the $timezone
280 * parameter and the current timezone are ignored when the $time parameter
281 * either is a UNIX timestamp (e.g. @946684800) or specifies a timezone
282 * (e.g. 2010-01-28T15:00:00+02:00).
283 * @see http://php.net/manual/datetime.construct.php
284 * @param array $settings
285 * (optional) Keyed array of settings. Defaults to empty array.
286 * - langcode: (optional) String two letter language code used to control
287 * the result of the format(). Defaults to NULL.
288 * - debug: (optional) Boolean choice to leave debug values in the
289 * date object for debugging purposes. Defaults to FALSE.
291 public function __construct($time = 'now', $timezone = NULL, $settings = []) {
294 $this->langcode = !empty($settings['langcode']) ? $settings['langcode'] : NULL;
296 // Massage the input values as necessary.
297 $prepared_time = $this->prepareTime($time);
298 $prepared_timezone = $this->prepareTimezone($timezone);
302 if (!empty($prepared_time)) {
303 $test = date_parse($prepared_time);
304 if (!empty($test['errors'])) {
305 $this->errors = $test['errors'];
309 if (empty($this->errors)) {
310 $this->dateTimeObject = new \DateTime($prepared_time, $prepared_timezone);
313 catch (\Exception $e) {
314 $this->errors[] = $e->getMessage();
317 // Clean up the error messages.
318 $this->checkErrors();
322 * Renders the timezone name.
326 public function render() {
327 return $this->format(static::FORMAT) . ' ' . $this->getTimeZone()->getName();
331 * Implements the magic __call method.
333 * Passes through all unknown calls onto the DateTime object.
335 * @param string $method
336 * The method to call on the decorated object.
341 * The return value from the method on the decorated object. If the proxied
342 * method call returns a DateTime object, then return the original
343 * DateTimePlus object, which allows function chaining to work properly.
344 * Otherwise, the value from the proxied method call is returned.
347 * Thrown when the DateTime object is not set.
348 * @throws \BadMethodCallException
349 * Thrown when there is no corresponding method on the DateTime object to
352 public function __call($method, array $args) {
353 // @todo consider using assert() as per https://www.drupal.org/node/2451793.
354 if (!isset($this->dateTimeObject)) {
355 throw new \Exception('DateTime object not set.');
357 if (!method_exists($this->dateTimeObject, $method)) {
358 throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s()', get_class($this), $method));
361 $result = call_user_func_array([$this->dateTimeObject, $method], $args);
363 return $result === $this->dateTimeObject ? $this : $result;
367 * Returns the difference between two DateTimePlus objects.
369 * @param \Drupal\Component\Datetime\DateTimePlus|\DateTime $datetime2
370 * The date to compare to.
371 * @param bool $absolute
372 * Should the interval be forced to be positive?
374 * @return \DateInterval
375 * A DateInterval object representing the difference between the two dates.
377 * @throws \BadMethodCallException
378 * If the input isn't a DateTime or DateTimePlus object.
380 public function diff($datetime2, $absolute = FALSE) {
381 if ($datetime2 instanceof DateTimePlus) {
382 $datetime2 = $datetime2->dateTimeObject;
384 if (!($datetime2 instanceof \DateTime)) {
385 throw new \BadMethodCallException(sprintf('Method %s expects parameter 1 to be a \DateTime or \Drupal\Component\Datetime\DateTimePlus object', __METHOD__));
387 return $this->dateTimeObject->diff($datetime2, $absolute);
391 * Implements the magic __callStatic method.
393 * Passes through all unknown static calls onto the DateTime object.
395 public static function __callStatic($method, $args) {
396 if (!method_exists('\DateTime', $method)) {
397 throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s()', get_called_class(), $method));
399 return call_user_func_array(['\DateTime', $method], $args);
403 * Implements the magic __clone method.
405 * Deep-clones the DateTime object we're wrapping.
407 public function __clone() {
408 $this->dateTimeObject = clone($this->dateTimeObject);
412 * Prepares the input time value.
414 * Changes the input value before trying to use it, if necessary.
415 * Can be overridden to handle special cases.
418 * An input value, which could be a timestamp, a string,
419 * or an array of date parts.
424 protected function prepareTime($time) {
429 * Prepares the input timezone value.
431 * Changes the timezone before trying to use it, if necessary.
432 * Most importantly, makes sure there is a valid timezone
433 * object before moving further.
435 * @param mixed $timezone
436 * Either a timezone name or a timezone object or NULL.
438 * @return \DateTimeZone
439 * The massaged time zone.
441 protected function prepareTimezone($timezone) {
442 // If the input timezone is a valid timezone object, use it.
443 if ($timezone instanceof \DateTimezone) {
444 $timezone_adjusted = $timezone;
447 // Allow string timezone input, and create a timezone from it.
448 elseif (!empty($timezone) && is_string($timezone)) {
449 $timezone_adjusted = new \DateTimeZone($timezone);
452 // Default to the system timezone when not explicitly provided.
453 // If the system timezone is missing, use 'UTC'.
454 if (empty($timezone_adjusted) || !$timezone_adjusted instanceof \DateTimezone) {
455 $system_timezone = date_default_timezone_get();
456 $timezone_name = !empty($system_timezone) ? $system_timezone : 'UTC';
457 $timezone_adjusted = new \DateTimeZone($timezone_name);
460 // We are finally certain that we have a usable timezone.
461 return $timezone_adjusted;
465 * Prepares the input format value.
467 * Changes the input format before trying to use it, if necessary.
468 * Can be overridden to handle special cases.
470 * @param string $format
471 * A PHP format string.
474 * The massaged PHP format string.
476 protected function prepareFormat($format) {
481 * Examines getLastErrors() to see what errors to report.
483 * Two kinds of errors are important: anything that DateTime
484 * considers an error, and also a warning that the date was invalid.
485 * PHP creates a valid date from invalid data with only a warning,
486 * 2011-02-30 becomes 2011-03-03, for instance, but we don't want that.
488 * @see http://php.net/manual/time.getlasterrors.php
490 public function checkErrors() {
491 $errors = \DateTime::getLastErrors();
492 if (!empty($errors['errors'])) {
493 $this->errors = array_merge($this->errors, $errors['errors']);
495 // Most warnings are messages that the date could not be parsed
496 // which causes it to be altered. For validation purposes, a warning
497 // as bad as an error, because it means the constructed date does
498 // not match the input value.
499 if (!empty($errors['warnings'])) {
500 $this->errors[] = 'The date is invalid.';
503 $this->errors = array_values(array_unique($this->errors));
507 * Detects if there were errors in the processing of this date.
510 * TRUE if there were errors in the processing of this date, FALSE
513 public function hasErrors() {
514 return (boolean) count($this->errors);
518 * Gets error messages.
520 * Public function to return the error messages.
523 * An array of errors encountered when creating this date.
525 public function getErrors() {
526 return $this->errors;
530 * Creates an ISO date from an array of values.
532 * @param array $array
533 * An array of date values keyed by date part.
534 * @param bool $force_valid_date
535 * (optional) Whether to force a full date by filling in missing
536 * values. Defaults to FALSE.
539 * The date as an ISO string.
541 public static function arrayToISO($array, $force_valid_date = FALSE) {
542 $array = static::prepareArray($array, $force_valid_date);
544 if ($array['year'] !== '') {
545 $input_time = static::datePad(intval($array['year']), 4);
546 if ($force_valid_date || $array['month'] !== '') {
547 $input_time .= '-' . static::datePad(intval($array['month']));
548 if ($force_valid_date || $array['day'] !== '') {
549 $input_time .= '-' . static::datePad(intval($array['day']));
553 if ($array['hour'] !== '') {
554 $input_time .= $input_time ? 'T' : '';
555 $input_time .= static::datePad(intval($array['hour']));
556 if ($force_valid_date || $array['minute'] !== '') {
557 $input_time .= ':' . static::datePad(intval($array['minute']));
558 if ($force_valid_date || $array['second'] !== '') {
559 $input_time .= ':' . static::datePad(intval($array['second']));
567 * Creates a complete array from a possibly incomplete array of date parts.
569 * @param array $array
570 * An array of date values keyed by date part.
571 * @param bool $force_valid_date
572 * (optional) Whether to force a valid date by filling in missing
573 * values with valid values or just to use empty values instead.
577 * A complete array of date parts.
579 public static function prepareArray($array, $force_valid_date = FALSE) {
580 if ($force_valid_date) {
581 $now = new \DateTime();
583 'year' => $now->format('Y'),
605 * Checks that arrays of date parts will create a valid date.
607 * Checks that an array of date parts has a year, month, and day,
608 * and that those values create a valid date. If time is provided,
609 * verifies that the time values are valid. Sort of an
610 * equivalent to checkdate().
612 * @param array $array
613 * An array of datetime values keyed by date part.
616 * TRUE if the datetime parts contain valid values, otherwise FALSE.
618 public static function checkArray($array) {
621 // Check for a valid date using checkdate(). Only values that
622 // meet that test are valid.
623 if (array_key_exists('year', $array) && array_key_exists('month', $array) && array_key_exists('day', $array)) {
624 if (@checkdate($array['month'], $array['day'], $array['year'])) {
628 // Testing for valid time is reversed. Missing time is OK,
629 // but incorrect values are not.
630 foreach (['hour', 'minute', 'second'] as $key) {
631 if (array_key_exists($key, $array)) {
632 $value = $array[$key];
635 if (!preg_match('/^([1-2][0-3]|[01]?[0-9])$/', $value)) {
642 if (!preg_match('/^([0-5][0-9]|[0-9])$/', $value)) {
649 return $valid_date && $valid_time;
653 * Pads date parts with zeros.
655 * Helper function for a task that is often required when working with dates.
660 * (optional) Size expected, usually 2 or 4. Defaults to 2.
665 public static function datePad($value, $size = 2) {
666 return sprintf("%0" . $size . "d", $value);
670 * Formats the date for display.
672 * @param string $format
673 * Format accepted by date().
674 * @param array $settings
675 * - timezone: (optional) String timezone name. Defaults to the timezone
676 * of the date object.
678 * @return string|null
679 * The formatted value of the date or NULL if there were construction
682 public function format($format, $settings = []) {
684 // If there were construction errors, we can't format the date.
685 if ($this->hasErrors()) {
689 // Format the date and catch errors.
691 // Clone the date/time object so we can change the time zone without
692 // disturbing the value stored in the object.
693 $dateTimeObject = clone $this->dateTimeObject;
694 if (isset($settings['timezone'])) {
695 $dateTimeObject->setTimezone(new \DateTimeZone($settings['timezone']));
697 $value = $dateTimeObject->format($format);
699 catch (\Exception $e) {
700 $this->errors[] = $e->getMessage();
707 * Sets the default time for an object built from date-only data.
709 * The default time for a date without time can be anything, so long as it is
710 * consistently applied. If we use noon, dates in most timezones will have the
711 * same value for in both the local timezone and UTC.
713 public function setDefaultDateTime() {
714 $this->dateTimeObject->setTime(12, 0, 0);
718 * Gets a clone of the proxied PHP \DateTime object wrapped by this class.
721 * A clone of the wrapped PHP \DateTime object.
723 public function getPhpDateTime() {
724 return clone $this->dateTimeObject;