public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null) { // Build the date interval specification string $dateIntervalSpec = DateInterval::PERIOD_PREFIX; // Check whether the weeks parameter is used, append the number of days if (!empty($weeks)) { $days += (int) ($weeks * DateTime::DAYS_PER_WEEK); } // Reading all non-zero date parts $date = array_filter(array(DateInterval::PERIOD_YEARS => $years, DateInterval::PERIOD_MONTHS => $months, DateInterval::PERIOD_DAYS => $days)); // Reading all non-zero time parts $time = array_filter(array(DateInterval::PERIOD_HOURS => $hours, DateInterval::PERIOD_MINUTES => $minutes, DateInterval::PERIOD_SECONDS => $seconds)); // Make sure at least one part is available if (empty($date) && empty($time)) { $date = array(DateInterval::PERIOD_YEARS => 0); } // Append each date part to the specification string foreach ($date as $key => $value) { $dateIntervalSpec .= $value . $key; } // Append each time part to the specification string if available if (!empty($time)) { // Prefix the time designator $dateIntervalSpec .= DateInterval::PERIOD_TIME_PREFIX; // Append each time part to the specification string foreach ($time as $key => $value) { $dateIntervalSpec .= $value . $key; } } // Return the spec if it's valid, return null otherwise return DateIntervalSpecUtils::isValid($dateIntervalSpec) ? $dateIntervalSpec : null; }
/** * Parse a date interval. A new instance may be created. * * This method allows better fluent syntax because it makes method chaining possible. * * @param PHPDateInterval|PHPDateInterval|string|null $dateInterval [optional] A DateInterval or PHPDateInterval * instance, a date interval specification, or null to use a zero specification. * * @return static A DateInterval instance, or null on failure. */ public static function parse($dateInterval) { // Return the object if it's already a DateInterval instance if ($dateInterval instanceof self) { return $dateInterval; } // Parse PHPDateInterval objects if ($dateInterval instanceof parent) { return new static($dateInterval, $dateInterval->invert); } // Return a zero specification if the specification is set to null if ($dateInterval === null) { return static::createZero(); } // Try to parse the string as date interval specification, return null on failure if (($dateIntervalSpec = DateIntervalSpecUtils::parse($dateInterval, null)) !== null) { // Create and return a new date interval instance based on the parsed specification return new static($dateIntervalSpec); } // Couldn't parse the date interval instance, return null return null; }