/** * Try to parse a date interval specification string. * * @param string|DateInterval|PHPDateInterval|null $dateIntervalSpec [optional] A date interval specification, a * relative date and time string, a DateInterval or PHPDateInterval instance or null to create a zero * configuration. * @param mixed|null $default [optional] The default value returned on failure. * * @return string|mixed The parsed date interval specification or the default value on failure. */ public static function parse($dateIntervalSpec = null, $default = null) { // Return a zero specification if the specification is set to null if (empty($dateIntervalSpec)) { return DateIntervalSpec::createZero(); } // Parse strings if (is_string($dateIntervalSpec)) { // Check whether the string is already a valid specification if (static::isValid($dateIntervalSpec)) { return $dateIntervalSpec; } // Check whether the string has relative keywords if (DateTime::hasRelativeKeywords($dateIntervalSpec)) { try { // Try to parse the string as relative date and time $dateInterval = DateInterval::createFromDateString($dateIntervalSpec); // Get and return the date interval specification return $dateInterval->toSpecString(); } catch (Exception $ex) { } } } // Parse DateInterval objects if ($dateIntervalSpec instanceof DateInterval) { return $dateIntervalSpec->toSpecString(); } // Parse PHPDateInterval objects if ($dateIntervalSpec instanceof PHPDateInterval) { if (($spec = DateIntervalSpec::create($dateIntervalSpec->y, $dateIntervalSpec->m, null, $dateIntervalSpec->d, $dateIntervalSpec->h, $dateIntervalSpec->i, $dateIntervalSpec->s)) !== null) { return $spec; } } // Couldn't parse the string, return the default value return $default; }
/** * Create a ISO-8601 date interval specification string. * * @return string The date interval specification string. */ public function toSpecString() { return DateIntervalSpec::create($this->getYears(), $this->getMonths(), null, $this->getDays(), $this->getHours(), $this->getMinutes(), $this->getSeconds()); }