function_name
stringlengths
2
38
file_path
stringlengths
15
82
focal_code
stringlengths
232
4.12k
file_content
stringlengths
930
234k
language
stringclasses
1 value
function_component
dict
metadata
dict
get
Carbon/src/Carbon/AbstractTranslator.php
public static function get(?string $locale = null): static { $locale = $locale ?: 'en'; $key = static::class === Translator::class ? $locale : static::class.'|'.$locale; $count = \count(static::$singletons); // Remember only the last 10 translators created if ($count > 10) { foreach (\array_slice(array_keys(static::$singletons), 0, $count - 10) as $index) { unset(static::$singletons[$index]); } } static::$singletons[$key] ??= new static($locale); return static::$singletons[$key]; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\MessageFormatter\MessageFormatterMapper; use Closure; use ReflectionException; use ReflectionFunction; use ReflectionProperty; use Symfony\Component\Translation\Formatter\MessageFormatterInterface; use Symfony\Component\Translation\Loader\ArrayLoader; use Symfony\Component\Translation\Translator as SymfonyTranslator; use Throwable; abstract class AbstractTranslator extends SymfonyTranslator { public const REGION_CODE_LENGTH = 2; /** * Translator singletons for each language. * * @var array */ protected static array $singletons = []; /** * List of custom localized messages. * * @var array */ protected array $messages = []; /** * List of custom directories that contain translation files. * * @var string[] */ protected array $directories = []; /** * Set to true while constructing. */ protected bool $initializing = false; /** * List of locales aliases. * * @var array<string, string> */ protected array $aliases = [ 'me' => 'sr_Latn_ME', 'scr' => 'sh', ]; /** * Return a singleton instance of Translator. * * @param string|null $locale optional initial locale ("en" - english by default) * * @return static */ public static function get(?string $locale = null): static { $locale = $locale ?: 'en'; $key = static::class === Translator::class ? $locale : static::class.'|'.$locale; $count = \count(static::$singletons); // Remember only the last 10 translators created if ($count > 10) { foreach (\array_slice(array_keys(static::$singletons), 0, $count - 10) as $index) { unset(static::$singletons[$index]); } } static::$singletons[$key] ??= new static($locale); return static::$singletons[$key]; } public function __construct($locale, ?MessageFormatterInterface $formatter = null, $cacheDir = null, $debug = false) { $this->initialize($locale, $formatter, $cacheDir, $debug); } /** * Returns the list of directories translation files are searched in. */ public function getDirectories(): array { return $this->directories; } /** * Set list of directories translation files are searched in. * * @param array $directories new directories list * * @return $this */ public function setDirectories(array $directories): static { $this->directories = $directories; return $this; } /** * Add a directory to the list translation files are searched in. * * @param string $directory new directory * * @return $this */ public function addDirectory(string $directory): static { $this->directories[] = $directory; return $this; } /** * Remove a directory from the list translation files are searched in. * * @param string $directory directory path * * @return $this */ public function removeDirectory(string $directory): static { $search = rtrim(strtr($directory, '\\', '/'), '/'); return $this->setDirectories(array_filter( $this->getDirectories(), static fn ($item) => rtrim(strtr($item, '\\', '/'), '/') !== $search, )); } /** * Reset messages of a locale (all locale if no locale passed). * Remove custom messages and reload initial messages from matching * file in Lang directory. */ public function resetMessages(?string $locale = null): bool { if ($locale === null) { $this->messages = []; $this->catalogues = []; $this->modifyResources(static function (array $resources): array { foreach ($resources as &$list) { array_splice($list, 1); } return $resources; }); return true; } $this->assertValidLocale($locale); foreach ($this->getDirectories() as $directory) { $file = \sprintf('%s/%s.php', rtrim($directory, '\\/'), $locale); $data = @include $file; if ($data !== false) { $this->messages[$locale] = $data; unset($this->catalogues[$locale]); $this->modifyResources(static function (array $resources) use ($locale): array { unset($resources[$locale]); return $resources; }); $this->addResource('array', $this->messages[$locale], $locale); return true; } } return false; } /** * Returns the list of files matching a given locale prefix (or all if empty). * * @param string $prefix prefix required to filter result * * @return array */ public function getLocalesFiles(string $prefix = ''): array { $files = []; foreach ($this->getDirectories() as $directory) { $directory = rtrim($directory, '\\/'); foreach (glob("$directory/$prefix*.php") as $file) { $files[] = $file; } } return array_unique($files); } /** * Returns the list of internally available locales and already loaded custom locales. * (It will ignore custom translator dynamic loading.) * * @param string $prefix prefix required to filter result * * @return array */ public function getAvailableLocales(string $prefix = ''): array { $locales = []; foreach ($this->getLocalesFiles($prefix) as $file) { $locales[] = substr($file, strrpos($file, '/') + 1, -4); } return array_unique(array_merge($locales, array_keys($this->messages))); } protected function translate(?string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string { if ($domain === null) { $domain = 'messages'; } $catalogue = $this->getCatalogue($locale); $format = $this instanceof TranslatorStrongTypeInterface ? $this->getFromCatalogue($catalogue, (string) $id, $domain) : $this->getCatalogue($locale)->get((string) $id, $domain); // @codeCoverageIgnore if ($format instanceof Closure) { // @codeCoverageIgnoreStart try { $count = (new ReflectionFunction($format))->getNumberOfRequiredParameters(); } catch (ReflectionException) { $count = 0; } // @codeCoverageIgnoreEnd return $format( ...array_values($parameters), ...array_fill(0, max(0, $count - \count($parameters)), null) ); } return parent::trans($id, $parameters, $domain, $locale); } /** * Init messages language from matching file in Lang directory. * * @param string $locale * * @return bool */ protected function loadMessagesFromFile(string $locale): bool { return isset($this->messages[$locale]) || $this->resetMessages($locale); } /** * Set messages of a locale and take file first if present. * * @param string $locale * @param array $messages * * @return $this */ public function setMessages(string $locale, array $messages): static { $this->loadMessagesFromFile($locale); $this->addResource('array', $messages, $locale); $this->messages[$locale] = array_merge( $this->messages[$locale] ?? [], $messages ); return $this; } /** * Set messages of the current locale and take file first if present. * * @param array $messages * * @return $this */ public function setTranslations(array $messages): static { return $this->setMessages($this->getLocale(), $messages); } /** * Get messages of a locale, if none given, return all the * languages. */ public function getMessages(?string $locale = null): array { return $locale === null ? $this->messages : $this->messages[$locale]; } /** * Set the current translator locale and indicate if the source locale file exists * * @param string $locale locale ex. en */ public function setLocale($locale): void { $locale = preg_replace_callback('/[-_]([a-z]{2,}|\d{2,})/', function ($matches) { // _2-letters or YUE is a region, _3+-letters is a variant $upper = strtoupper($matches[1]); if ($upper === 'YUE' || $upper === 'ISO' || \strlen($upper) <= static::REGION_CODE_LENGTH) { return "_$upper"; } return '_'.ucfirst($matches[1]); }, strtolower($locale)); $previousLocale = $this->getLocale(); if ($previousLocale === $locale && isset($this->messages[$locale])) { return; } unset(static::$singletons[$previousLocale]); if ($locale === 'auto') { $completeLocale = setlocale(LC_TIME, '0'); $locale = preg_replace('/^([^_.-]+).*$/', '$1', $completeLocale); $locales = $this->getAvailableLocales($locale); $completeLocaleChunks = preg_split('/[_.-]+/', $completeLocale); $getScore = static fn ($language) => self::compareChunkLists( $completeLocaleChunks, preg_split('/[_.-]+/', $language), ); usort($locales, static fn ($first, $second) => $getScore($second) <=> $getScore($first)); $locale = $locales[0]; } if (isset($this->aliases[$locale])) { $locale = $this->aliases[$locale]; } // If subtag (ex: en_CA) first load the macro (ex: en) to have a fallback if (str_contains($locale, '_') && $this->loadMessagesFromFile($macroLocale = preg_replace('/^([^_]+).*$/', '$1', $locale)) ) { parent::setLocale($macroLocale); } if (!$this->loadMessagesFromFile($locale) && !$this->initializing) { return; } parent::setLocale($locale); } /** * Show locale on var_dump(). * * @return array */ public function __debugInfo() { return [ 'locale' => $this->getLocale(), ]; } public function __serialize(): array { return [ 'locale' => $this->getLocale(), ]; } public function __unserialize(array $data): void { $this->initialize($data['locale'] ?? 'en'); } private function initialize($locale, ?MessageFormatterInterface $formatter = null, $cacheDir = null, $debug = false): void { parent::setLocale($locale); $this->initializing = true; $this->directories = [__DIR__.'/Lang']; $this->addLoader('array', new ArrayLoader()); parent::__construct($locale, new MessageFormatterMapper($formatter), $cacheDir, $debug); $this->initializing = false; } private static function compareChunkLists($referenceChunks, $chunks) { $score = 0; foreach ($referenceChunks as $index => $chunk) { if (!isset($chunks[$index])) { $score++; continue; } if (strtolower($chunks[$index]) === strtolower($chunk)) { $score += 10; } } return $score; } /** @codeCoverageIgnore */ private function modifyResources(callable $callback): void { try { $resourcesProperty = new ReflectionProperty(SymfonyTranslator::class, 'resources'); $resources = $resourcesProperty->getValue($this); $resourcesProperty->setValue($this, $callback($resources)); } catch (Throwable) { // Clear resources if available, if not, then nothing to clean } } }
PHP
{ "end_line": 89, "name": "get", "signature": "public static function get(?string $locale = null): static", "start_line": 73 }
{ "class_name": "AbstractTranslator", "class_signature": "class AbstractTranslator", "namespace": "Carbon" }
resetMessages
Carbon/src/Carbon/AbstractTranslator.php
public function resetMessages(?string $locale = null): bool { if ($locale === null) { $this->messages = []; $this->catalogues = []; $this->modifyResources(static function (array $resources): array { foreach ($resources as &$list) { array_splice($list, 1); } return $resources; }); return true; } $this->assertValidLocale($locale); foreach ($this->getDirectories() as $directory) { $file = \sprintf('%s/%s.php', rtrim($directory, '\\/'), $locale); $data = @include $file; if ($data !== false) { $this->messages[$locale] = $data; unset($this->catalogues[$locale]); $this->modifyResources(static function (array $resources) use ($locale): array { unset($resources[$locale]); return $resources; }); $this->addResource('array', $this->messages[$locale], $locale); return true; } } return false; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\MessageFormatter\MessageFormatterMapper; use Closure; use ReflectionException; use ReflectionFunction; use ReflectionProperty; use Symfony\Component\Translation\Formatter\MessageFormatterInterface; use Symfony\Component\Translation\Loader\ArrayLoader; use Symfony\Component\Translation\Translator as SymfonyTranslator; use Throwable; abstract class AbstractTranslator extends SymfonyTranslator { public const REGION_CODE_LENGTH = 2; /** * Translator singletons for each language. * * @var array */ protected static array $singletons = []; /** * List of custom localized messages. * * @var array */ protected array $messages = []; /** * List of custom directories that contain translation files. * * @var string[] */ protected array $directories = []; /** * Set to true while constructing. */ protected bool $initializing = false; /** * List of locales aliases. * * @var array<string, string> */ protected array $aliases = [ 'me' => 'sr_Latn_ME', 'scr' => 'sh', ]; /** * Return a singleton instance of Translator. * * @param string|null $locale optional initial locale ("en" - english by default) * * @return static */ public static function get(?string $locale = null): static { $locale = $locale ?: 'en'; $key = static::class === Translator::class ? $locale : static::class.'|'.$locale; $count = \count(static::$singletons); // Remember only the last 10 translators created if ($count > 10) { foreach (\array_slice(array_keys(static::$singletons), 0, $count - 10) as $index) { unset(static::$singletons[$index]); } } static::$singletons[$key] ??= new static($locale); return static::$singletons[$key]; } public function __construct($locale, ?MessageFormatterInterface $formatter = null, $cacheDir = null, $debug = false) { $this->initialize($locale, $formatter, $cacheDir, $debug); } /** * Returns the list of directories translation files are searched in. */ public function getDirectories(): array { return $this->directories; } /** * Set list of directories translation files are searched in. * * @param array $directories new directories list * * @return $this */ public function setDirectories(array $directories): static { $this->directories = $directories; return $this; } /** * Add a directory to the list translation files are searched in. * * @param string $directory new directory * * @return $this */ public function addDirectory(string $directory): static { $this->directories[] = $directory; return $this; } /** * Remove a directory from the list translation files are searched in. * * @param string $directory directory path * * @return $this */ public function removeDirectory(string $directory): static { $search = rtrim(strtr($directory, '\\', '/'), '/'); return $this->setDirectories(array_filter( $this->getDirectories(), static fn ($item) => rtrim(strtr($item, '\\', '/'), '/') !== $search, )); } /** * Reset messages of a locale (all locale if no locale passed). * Remove custom messages and reload initial messages from matching * file in Lang directory. */ public function resetMessages(?string $locale = null): bool { if ($locale === null) { $this->messages = []; $this->catalogues = []; $this->modifyResources(static function (array $resources): array { foreach ($resources as &$list) { array_splice($list, 1); } return $resources; }); return true; } $this->assertValidLocale($locale); foreach ($this->getDirectories() as $directory) { $file = \sprintf('%s/%s.php', rtrim($directory, '\\/'), $locale); $data = @include $file; if ($data !== false) { $this->messages[$locale] = $data; unset($this->catalogues[$locale]); $this->modifyResources(static function (array $resources) use ($locale): array { unset($resources[$locale]); return $resources; }); $this->addResource('array', $this->messages[$locale], $locale); return true; } } return false; } /** * Returns the list of files matching a given locale prefix (or all if empty). * * @param string $prefix prefix required to filter result * * @return array */ public function getLocalesFiles(string $prefix = ''): array { $files = []; foreach ($this->getDirectories() as $directory) { $directory = rtrim($directory, '\\/'); foreach (glob("$directory/$prefix*.php") as $file) { $files[] = $file; } } return array_unique($files); } /** * Returns the list of internally available locales and already loaded custom locales. * (It will ignore custom translator dynamic loading.) * * @param string $prefix prefix required to filter result * * @return array */ public function getAvailableLocales(string $prefix = ''): array { $locales = []; foreach ($this->getLocalesFiles($prefix) as $file) { $locales[] = substr($file, strrpos($file, '/') + 1, -4); } return array_unique(array_merge($locales, array_keys($this->messages))); } protected function translate(?string $id, array $parameters = [], ?string $domain = null, ?string $locale = null): string { if ($domain === null) { $domain = 'messages'; } $catalogue = $this->getCatalogue($locale); $format = $this instanceof TranslatorStrongTypeInterface ? $this->getFromCatalogue($catalogue, (string) $id, $domain) : $this->getCatalogue($locale)->get((string) $id, $domain); // @codeCoverageIgnore if ($format instanceof Closure) { // @codeCoverageIgnoreStart try { $count = (new ReflectionFunction($format))->getNumberOfRequiredParameters(); } catch (ReflectionException) { $count = 0; } // @codeCoverageIgnoreEnd return $format( ...array_values($parameters), ...array_fill(0, max(0, $count - \count($parameters)), null) ); } return parent::trans($id, $parameters, $domain, $locale); } /** * Init messages language from matching file in Lang directory. * * @param string $locale * * @return bool */ protected function loadMessagesFromFile(string $locale): bool { return isset($this->messages[$locale]) || $this->resetMessages($locale); } /** * Set messages of a locale and take file first if present. * * @param string $locale * @param array $messages * * @return $this */ public function setMessages(string $locale, array $messages): static { $this->loadMessagesFromFile($locale); $this->addResource('array', $messages, $locale); $this->messages[$locale] = array_merge( $this->messages[$locale] ?? [], $messages ); return $this; } /** * Set messages of the current locale and take file first if present. * * @param array $messages * * @return $this */ public function setTranslations(array $messages): static { return $this->setMessages($this->getLocale(), $messages); } /** * Get messages of a locale, if none given, return all the * languages. */ public function getMessages(?string $locale = null): array { return $locale === null ? $this->messages : $this->messages[$locale]; } /** * Set the current translator locale and indicate if the source locale file exists * * @param string $locale locale ex. en */ public function setLocale($locale): void { $locale = preg_replace_callback('/[-_]([a-z]{2,}|\d{2,})/', function ($matches) { // _2-letters or YUE is a region, _3+-letters is a variant $upper = strtoupper($matches[1]); if ($upper === 'YUE' || $upper === 'ISO' || \strlen($upper) <= static::REGION_CODE_LENGTH) { return "_$upper"; } return '_'.ucfirst($matches[1]); }, strtolower($locale)); $previousLocale = $this->getLocale(); if ($previousLocale === $locale && isset($this->messages[$locale])) { return; } unset(static::$singletons[$previousLocale]); if ($locale === 'auto') { $completeLocale = setlocale(LC_TIME, '0'); $locale = preg_replace('/^([^_.-]+).*$/', '$1', $completeLocale); $locales = $this->getAvailableLocales($locale); $completeLocaleChunks = preg_split('/[_.-]+/', $completeLocale); $getScore = static fn ($language) => self::compareChunkLists( $completeLocaleChunks, preg_split('/[_.-]+/', $language), ); usort($locales, static fn ($first, $second) => $getScore($second) <=> $getScore($first)); $locale = $locales[0]; } if (isset($this->aliases[$locale])) { $locale = $this->aliases[$locale]; } // If subtag (ex: en_CA) first load the macro (ex: en) to have a fallback if (str_contains($locale, '_') && $this->loadMessagesFromFile($macroLocale = preg_replace('/^([^_]+).*$/', '$1', $locale)) ) { parent::setLocale($macroLocale); } if (!$this->loadMessagesFromFile($locale) && !$this->initializing) { return; } parent::setLocale($locale); } /** * Show locale on var_dump(). * * @return array */ public function __debugInfo() { return [ 'locale' => $this->getLocale(), ]; } public function __serialize(): array { return [ 'locale' => $this->getLocale(), ]; } public function __unserialize(array $data): void { $this->initialize($data['locale'] ?? 'en'); } private function initialize($locale, ?MessageFormatterInterface $formatter = null, $cacheDir = null, $debug = false): void { parent::setLocale($locale); $this->initializing = true; $this->directories = [__DIR__.'/Lang']; $this->addLoader('array', new ArrayLoader()); parent::__construct($locale, new MessageFormatterMapper($formatter), $cacheDir, $debug); $this->initializing = false; } private static function compareChunkLists($referenceChunks, $chunks) { $score = 0; foreach ($referenceChunks as $index => $chunk) { if (!isset($chunks[$index])) { $score++; continue; } if (strtolower($chunks[$index]) === strtolower($chunk)) { $score += 10; } } return $score; } /** @codeCoverageIgnore */ private function modifyResources(callable $callback): void { try { $resourcesProperty = new ReflectionProperty(SymfonyTranslator::class, 'resources'); $resources = $resourcesProperty->getValue($this); $resourcesProperty->setValue($this, $callback($resources)); } catch (Throwable) { // Clear resources if available, if not, then nothing to clean } } }
PHP
{ "end_line": 191, "name": "resetMessages", "signature": "public function resetMessages(?string $locale = null): bool", "start_line": 154 }
{ "class_name": "AbstractTranslator", "class_signature": "class AbstractTranslator", "namespace": "Carbon" }
prepareParameter
Carbon/src/Carbon/Callback.php
public function prepareParameter(mixed $value, string|int $index = 0): mixed { $type = $this->getParameterType($index); if (!($type instanceof ReflectionNamedType)) { return $value; } $name = $type->getName(); if ($name === CarbonInterface::class) { $name = $value instanceof DateTime ? Carbon::class : CarbonImmutable::class; } if (!class_exists($name) || is_a($value, $name)) { return $value; } $class = $this->getPromotedClass($value); if ($class && is_a($name, $class, true)) { return $name::instance($value); } return $value; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Closure; use DateInterval; use DatePeriod; use DateTime; use DateTimeInterface; use DateTimeZone; use ReflectionFunction; use ReflectionNamedType; use ReflectionType; final class Callback { private ?ReflectionFunction $function; private function __construct(private readonly Closure $closure) { } public static function fromClosure(Closure $closure): self { return new self($closure); } public static function parameter(mixed $closure, mixed $value, string|int $index = 0): mixed { if ($closure instanceof Closure) { return self::fromClosure($closure)->prepareParameter($value, $index); } return $value; } public function getReflectionFunction(): ReflectionFunction { return $this->function ??= new ReflectionFunction($this->closure); } public function prepareParameter(mixed $value, string|int $index = 0): mixed { $type = $this->getParameterType($index); if (!($type instanceof ReflectionNamedType)) { return $value; } $name = $type->getName(); if ($name === CarbonInterface::class) { $name = $value instanceof DateTime ? Carbon::class : CarbonImmutable::class; } if (!class_exists($name) || is_a($value, $name)) { return $value; } $class = $this->getPromotedClass($value); if ($class && is_a($name, $class, true)) { return $name::instance($value); } return $value; } public function call(mixed ...$arguments): mixed { foreach ($arguments as $index => &$value) { if ($this->getPromotedClass($value)) { $value = $this->prepareParameter($value, $index); } } return ($this->closure)(...$arguments); } private function getParameterType(string|int $index): ?ReflectionType { $parameters = $this->getReflectionFunction()->getParameters(); if (\is_int($index)) { return ($parameters[$index] ?? null)?->getType(); } foreach ($parameters as $parameter) { if ($parameter->getName() === $index) { return $parameter->getType(); } } return null; } /** @return class-string|null */ private function getPromotedClass(mixed $value): ?string { if ($value instanceof DateTimeInterface) { return CarbonInterface::class; } if ($value instanceof DateInterval) { return CarbonInterval::class; } if ($value instanceof DatePeriod) { return CarbonPeriod::class; } if ($value instanceof DateTimeZone) { return CarbonTimeZone::class; } return null; } }
PHP
{ "end_line": 78, "name": "prepareParameter", "signature": "public function prepareParameter(mixed $value, string|int $index = 0): mixed", "start_line": 53 }
{ "class_name": "Callback", "class_signature": "class Callback", "namespace": "Carbon" }
shiftTimezone
Carbon/src/Carbon/CarbonInterval.php
public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH], 'day' => ['week' => Carbon::DAYS_PER_WEEK], 'hour' => ['day' => Carbon::HOURS_PER_DAY], 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], ]; return $defaults[$source][$target] ?? null; } /** * Returns current config for days per week. * * @return int|float */ public static function getDaysPerWeek() { return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; } /** * Returns current config for hours per day. * * @return int|float */ public static function getHoursPerDay() { return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; } /** * Returns current config for minutes per hour. * * @return int|float */ public static function getMinutesPerHour() { return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; } /** * Returns current config for seconds per minute. * * @return int|float */ public static function getSecondsPerMinute() { return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMillisecondsPerSecond() { return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMicrosecondsPerMillisecond() { return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; } /** * Create a new CarbonInterval instance from specific values. * This is an alias for the constructor that allows better fluent * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than * (new CarbonInterval(1))->fn(). * * @param int $years * @param int $months * @param int $weeks * @param int $days * @param int $hours * @param int $minutes * @param int $seconds * @param int $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. * * @return static */ public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); } /** * Parse a string into a new CarbonInterval object according to the specified format. * * @example * ``` * echo Carboninterval::createFromFormat('H:i', '1:30'); * ``` * * @param string $format Format of the $interval input string * @param string|null $interval Input string to convert into an interval * * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. * * @return static */ public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; } /** * Return the original source used to create the current interval. * * @return array|int|string|DateInterval|mixed|null */ public function original() { return $this->originalInput; } /** * Return the start date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function start(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->startDate; } /** * Return the end date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function end(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->endDate; } /** * Get rid of the original input, start date and end date that may be kept in memory. * * @return $this */ public function optimize(): static { $this->originalInput = null; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; $this->absolute = false; return $this; } /** * Get a copy of the instance. * * @return static */ public function copy(): static { $date = new static(0); $date->copyProperties($this); $date->step = $this->step; return $date; } /** * Get a copy of the instance. * * @return static */ public function clone(): static { return $this->copy(); } /** * Provide static helpers to create instances. Allows CarbonInterval::years(3). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @return static|mixed|null */ public static function __callStatic(string $method, array $parameters) { try { $interval = new static(0); $localStrictModeEnabled = $interval->localStrictModeEnabled; $interval->localStrictModeEnabled = true; $result = static::hasMacro($method) ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { return $interval->callMacro($method, $parameters); }) : $interval->$method(...$parameters); $interval->localStrictModeEnabled = $localStrictModeEnabled; return $result; } catch (BadFluentSetterException $exception) { if (Carbon::isStrictModeEnabled()) { throw new BadFluentConstructorException($method, 0, $exception); } return null; } } /** * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. * * @param array $dump data as exported by var_export() * * @return static */ #[ReturnTypeWillChange] public static function __set_state($dump) { /** @noinspection PhpVoidFunctionResultUsedInspection */ /** @var DateInterval $dateInterval */ $dateInterval = parent::__set_state($dump); return static::instance($dateInterval); } /** * Return the current context from inside a macro callee or a new one if static. * * @return static */ protected static function this(): static { return end(static::$macroContextStack) ?: new static(0); } /** * Creates a CarbonInterval from string. * * Format: * * Suffix | Unit | Example | DateInterval expression * -------|---------|---------|------------------------ * y | years | 1y | P1Y * mo | months | 3mo | P3M * w | weeks | 2w | P2W * d | days | 28d | P28D * h | hours | 4h | PT4H * m | minutes | 12m | PT12M * s | seconds | 59s | PT59S * * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. * * Special cases: * - An empty string will return a zero interval * - Fractions are allowed for weeks, days, hours and minutes and will be converted * and rounded to the next smaller value (caution: 0.5w = 4d) * * @param string $intervalDefinition * * @throws InvalidIntervalException * * @return static */ public static function fromString(string $intervalDefinition): static { if (empty($intervalDefinition)) { return self::withOriginal(new static(0), $intervalDefinition); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $milliseconds = 0; $microseconds = 0; $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ([$part, $value, $unit] = array_shift($parts)) { $intValue = (int) $value; $fraction = (float) $value - $intValue; // Fix calculation precision switch (round($fraction, 6)) { case 1: $fraction = 0; $intValue++; break; case 0: $fraction = 0; break; } switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { case 'millennia': case 'millennium': $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; break; case 'century': case 'centuries': $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; break; case 'decade': case 'decades': $years += $intValue * CarbonInterface::YEARS_PER_DECADE; break; case 'year': case 'years': case 'y': case 'yr': case 'yrs': $years += $intValue; break; case 'quarter': case 'quarters': $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; break; case 'month': case 'months': case 'mo': case 'mos': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; } break; case 'second': case 'seconds': case 's': $seconds += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; } break; case 'millisecond': case 'milliseconds': case 'milli': case 'ms': $milliseconds += $intValue; if ($fraction) { $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); } break; case 'microsecond': case 'microseconds': case 'micro': case 'µs': $microseconds += $intValue; break; default: throw new InvalidIntervalException( "Invalid part $part in definition $intervalDefinition", ); } } return self::withOriginal( new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds), $intervalDefinition, ); } /** * Creates a CarbonInterval from string using a different locale. * * @param string $interval interval string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be used instead. * * @return static */ public static function parseFromLocale(string $interval, ?string $locale = null): static { return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE)); } /** * Create an interval from the difference between 2 dates. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $start * @param \Carbon\Carbon|\DateTimeInterface|mixed $end * * @return static */ public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; } /** * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function abs(bool $absolute = false): static { if ($absolute && $this->invert) { $this->invert(); } return $this; } /** * @alias abs * * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function absolute(bool $absolute = true): static { return $this->abs($absolute); } /** * Cast the current instance into the given class. * * @template T of DateInterval * * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { return self::castIntervalToClass($this, $className); } /** * Create a CarbonInterval instance from a DateInterval one. Can not instance * DateInterval objects created from DateTime::diff() as you can't externally * set the $days field. * * @param DateInterval $interval * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static */ public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static { if ($skipCopy && $interval instanceof static) { return $interval; } return self::castIntervalToClass($interval, static::class, $skip); } /** * Make a CarbonInterval instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static|null */ public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); } protected static function makeFromString(string $interval): ?self { $interval = preg_replace('/\s+/', ' ', trim($interval)); if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { return static::fromString($interval); } $intervalInstance = static::createFromDateString($interval); return $intervalInstance->isEmpty() ? null : $intervalInstance; } protected function resolveInterval($interval): ?self { if (!($interval instanceof self)) { return self::make($interval); } return $interval; } /** * Sets up a DateInterval from the relative parts of the string. * * @param string $datetime * * @return static * * @link https://php.net/manual/en/dateinterval.createfromdatestring.php */ public static function createFromDateString(string $datetime): static { $string = strtr($datetime, [ ',' => ' ', ' and ' => ' ', ]); $previousException = null; try { $interval = parent::createFromDateString($string); } catch (Throwable $exception) { $interval = null; $previousException = $exception; } $interval ?: throw new InvalidFormatException( 'Could not create interval from: '.var_export($datetime, true), previous: $previousException, ); if (!($interval instanceof static)) { $interval = static::instance($interval); } return self::withOriginal($interval, $datetime); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the CarbonInterval object. */ public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; } /** * Get a part of the CarbonInterval object. */ public function __get(string $name): int|float|string|null { return $this->get($name); } /** * Set a part of the CarbonInterval object. * * @param Unit|string|array $name * @param int $value * * @throws UnknownSetterException * * @return $this */ public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; } /** * Set a part of the CarbonInterval object. * * @param string $name * @param int $value * * @throws UnknownSetterException */ public function __set(string $name, $value) { $this->set($name, $value); } /** * Allow setting of weeks and days to be cumulative. * * @param int $weeks Number of weeks to set * @param int $days Number of days to set * * @return static */ public function weeksAndDays(int $weeks, int $days): static { $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; return $this; } /** * Returns true if the interval is empty for each unit. * * @return bool */ public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonInterval::macro('twice', function () { * return $this->times(2); * }); * echo CarbonInterval::hours(2)->twice(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonInterval::mixin(new class { * public function daysToHours() { * return function () { * $this->hours += $this->days; * $this->days = 0; * * return $this; * }; * } * public function hoursToDays() { * return function () { * $this->days += $this->hours; * $this->hours = 0; * * return $this; * }; * } * }); * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; * echo CarbonInterval::days(5)->daysToHours() . "\n"; * ``` * * @param object|string $mixin * * @throws ReflectionException * * @return void */ public static function mixin($mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Call given macro. * * @param string $name * @param array $parameters * * @return mixed */ protected function callMacro(string $name, array $parameters) { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadFluentSetterException|Throwable * * @return static|int|float|string */ public function __call(string $method, array $parameters) { if (static::hasMacro($method)) { return static::bindMacroContext($this, function () use (&$method, &$parameters) { return $this->callMacro($method, $parameters); }); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); return $this->{$match['method']}($value, $match['unit']); } $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); try { $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); } } return $this; } protected function getForHumansInitialVariables($syntax, $short): array { if (\is_array($syntax)) { return $syntax; } if (\is_int($short)) { return [ 'parts' => $short, 'short' => false, ]; } if (\is_bool($syntax)) { return [ 'short' => $syntax, 'syntax' => CarbonInterface::DIFF_ABSOLUTE, ]; } return []; } /** * @param mixed $syntax * @param mixed $short * @param mixed $parts * @param mixed $options * * @return array */ protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array { $optionalSpace = ' '; $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; /** @var bool|string $join */ $join = $default === '' ? '' : ' '; /** @var bool|array|string $altNumbers */ $altNumbers = false; $aUnit = false; $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); $skip = array_map( static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit, (array) $skip, ); $skip = array_map( 'strtolower', array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''), ); $syntax ??= CarbonInterface::DIFF_ABSOLUTE; if ($parts === self::NO_LIMIT) { $parts = INF; } $options ??= static::getHumanDiffOptions(); if ($join === false) { $join = ' '; } elseif ($join === true) { $join = [ $default, $this->getTranslationMessage('list.1') ?? $default, ]; } if ($altNumbers && $altNumbers !== true) { $language = new Language($this->locale); $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { [$default, $last] = $join; if ($default !== ' ') { $optionalSpace = ''; } $join = function ($list) use ($default, $last) { if (\count($list) < 2) { return implode('', $list); } $end = array_pop($list); return implode($default, $list).$last.$end; }; } if (\is_string($join)) { if ($join !== ' ') { $optionalSpace = ''; } $glue = $join; $join = static fn ($list) => implode($glue, $list); } $interpolations = [ ':optional-space' => $optionalSpace, ]; $translator ??= isset($locale) ? Translator::get($locale) : null; return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator]; } protected static function getRoundingMethodFromOptions(int $options): ?string { if ($options & CarbonInterface::ROUND) { return 'round'; } if ($options & CarbonInterface::CEIL) { return 'ceil'; } if ($options & CarbonInterface::FLOOR) { return 'floor'; } return null; } /** * Returns interval values as an array where key are the unit names and values the counts. * * @return int[] */ public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; } /** * Returns interval non-zero values as an array where key are the unit names and values the counts. * * @return int[] */ public function getNonZeroValues(): array { return array_filter($this->toArray(), 'intval'); } /** * Returns interval values as an array where key are the unit names and values the counts * from the biggest non-zero one the the smallest non-zero one. * * @return int[] */ public function getValuesSequence(): array { $nonZeroValues = $this->getNonZeroValues(); if ($nonZeroValues === []) { return []; } $keys = array_keys($nonZeroValues); $firstKey = $keys[0]; $lastKey = $keys[\count($keys) - 1]; $values = []; $record = false; foreach ($this->toArray() as $unit => $count) { if ($unit === $firstKey) { $record = true; } if ($record) { $values[$unit] = $count; } if ($unit === $lastKey) { $record = false; } } return $values; } /** * Get the current interval in a human readable format in the current locale. * * @example * ``` * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; * ``` * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: -1: no limits) * @param int $options human diff options * * @throws Exception * * @return string */ public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string { /* @var TranslatorInterface|null $translator */ [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this ->getForHumansParameters($syntax, $short, $parts, $options); $interval = []; $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; $count = 1; $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); $declensionMode = null; $translator ??= $this->getLocalTranslator(); $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); if ($this->needsDeclension($declensionMode, $index, $parts)) { // Some languages have special pluralization for past and future tense. $key = $unit.'_'.$transId; $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); if ($result !== $key) { return $result; } } } $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); if ($result !== $unit) { return $result; } return null; }; $intervalValues = $this; $method = static::getRoundingMethodFromOptions($options); if ($method) { $previousCount = INF; while ( \count($intervalValues->getNonZeroValues()) > $parts && ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 ) { $index = min($count, $previousCount - 1) - 2; if ($index < 0) { break; } $intervalValues = $this->copy()->roundUnit( $keys[$index], 1, $method, ); $previousCount = $count; } } $diffIntervalArray = [ ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], ]; if (!empty($skip)) { foreach ($diffIntervalArray as $index => &$unitData) { $nextIndex = $index + 1; if ($unitData['value'] && isset($diffIntervalArray[$nextIndex]) && \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) ) { $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); $unitData['value'] = 0; } } } $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; } } if (!$absolute) { return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); }; $fallbackUnit = ['second', 's']; foreach ($diffIntervalArray as $diffIntervalData) { if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } // break the loop after we get the required number of parts in array if (\count($interval) >= $parts) { break; } // break the loop after we have reached the minimum unit if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } $actualParts = \count($interval); foreach ($interval as $index => &$item) { $item = $transChoice($item[0], $item[1], $index, $actualParts); } if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; $unit = $fallbackUnit[$short ? 1 : 0]; $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); } // join the interval parts by a space $time = $join($interval); unset($diffIntervalArray, $interval); if ($absolute) { return $time; } $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); if ($parts === 1) { if ($relativeToNow && $unit === 'day') { $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null; if ($specialTranslations && $options & $specialTranslations['option']) { $key = $specialTranslations[$isFuture ? 'future' : 'past']; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } } $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; } $time = [':time' => $time]; return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); } public function format(string $format): string { $output = parent::format($format); if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) { return $output; } $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate); return str_replace('(unknown)', $this->rawInterval->format('%a'), $output); } /** * Format the instance as a string using the forHumans() function. * * @throws Exception * * @return string */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if (!$format) { return $this->forHumans(); } if ($format instanceof Closure) { return $format($this); } return $this->format($format); } /** * Return native DateInterval PHP object matching the current instance. * * @example * ``` * var_dump(CarbonInterval::hours(2)->toDateInterval()); * ``` * * @return DateInterval */ public function toDateInterval(): DateInterval { return self::castIntervalToClass($this, DateInterval::class); } /** * Convert the interval to a CarbonPeriod. * * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. * * @return CarbonPeriod */ public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); } /** * Decompose the current interval into * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); } /** * Invert the interval. * * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this */ public function invert($inverted = null): static { $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; return $this; } protected function solveNegativeInterval(): static { if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { $this->years *= self::NEGATIVE; $this->months *= self::NEGATIVE; $this->dayz *= self::NEGATIVE; $this->hours *= self::NEGATIVE; $this->minutes *= self::NEGATIVE; $this->seconds *= self::NEGATIVE; $this->microseconds *= self::NEGATIVE; $this->invert(); } return $this; } /** * Add the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function sub($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } return $this->add($unit, -(float) $value); } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function subtract($unit, $value = 1): static { return $this->sub($unit, $value); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Multiply current instance given number of times. times() is naive, it multiplies each unit * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded * separately for each unit. * * Use times() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see multiply() * * @param float|int $factor * * @return $this */ public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; } /** * Divide current instance by a given divider. shares() is naive, it divides each unit separately * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours * and 7 minutes. * * Use shares() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see divide() * * @param float|int $divider * * @return $this */ public function shares($divider): static { return $this->times(1 / $divider); } protected function copyProperties(self $interval, $ignoreSign = false): static { $this->years = $interval->years; $this->months = $interval->months; $this->dayz = $interval->dayz; $this->hours = $interval->hours; $this->minutes = $interval->minutes; $this->seconds = $interval->seconds; $this->microseconds = $interval->microseconds; if (!$ignoreSign) { $this->invert = $interval->invert; } return $this; } /** * Multiply and cascade current instance by a given factor. * * @param float|int $factor * * @return $this */ public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); } /** * Divide and cascade current instance by a given divider. * * @param float|int $divider * * @return $this */ public function divide($divider): static { return $this->multiply(1 / $divider); } /** * Get the interval_spec string of a date interval. * * @param DateInterval $interval * * @return string */ public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), static::PERIOD_MONTHS => abs($interval->m), static::PERIOD_DAYS => abs($interval->d), ]); $skip = array_map([Unit::class, 'toNameIfUnit'], $skip); if ( $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) ) { $date = [ static::PERIOD_DAYS => abs($interval->days), ]; } $seconds = abs($interval->s); if ($microseconds && $interval->f > 0) { $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); } $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; foreach ($date as $key => $value) { $specString .= $value.$key; } if (\count($time) > 0) { $specString .= static::PERIOD_TIME_PREFIX; foreach ($time as $key => $value) { $specString .= $value.$key; } } return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; } /** * Get the interval_spec string. * * @return string */ public function spec(bool $microseconds = false): string { return static::getDateIntervalSpec($this, $microseconds); } /** * Comparing 2 date intervals. * * @param DateInterval $first * @param DateInterval $second * * @return int 0, 1 or -1 */ public static function compareDateIntervals(DateInterval $first, DateInterval $second): int { $current = Carbon::now(); $passed = $current->avoidMutation()->add($second); $current->add($first); return $current <=> $passed; } /** * Comparing with passed interval. * * @param DateInterval $interval * * @return int 0, 1 or -1 */ public function compare(DateInterval $interval): int { return static::compareDateIntervals($this, $interval); } /** * Convert overflowed values into bigger units. * * @return $this */ public function cascade(): static { return $this->doCascade(false); } public function hasNegativeValues(): bool { foreach ($this->toArray() as $value) { if ($value < 0) { return true; } } return false; } public function hasPositiveValues(): bool { foreach ($this->toArray() as $value) { if ($value > 0) { return true; } } return false; } /** * Get amount of given unit equivalent to the interval. * * @param string $unit * * @throws UnknownUnitException|UnitNotConfiguredException * * @return float */ public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see equalTo() * * @return bool */ public function eq($interval): bool { return $this->equalTo($interval); } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see notEqualTo() * * @return bool */ public function ne($interval): bool { return $this->notEqualTo($interval); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function notEqualTo($interval): bool { return !$this->eq($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThan() * * @return bool */ public function gt($interval): bool { return $this->greaterThan($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThanOrEqualTo() * * @return bool */ public function gte($interval): bool { return $this->greaterThanOrEqualTo($interval); } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThanOrEqualTo($interval): bool { return $this->greaterThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThan() * * @return bool */ public function lt($interval): bool { return $this->lessThan($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThanOrEqualTo() * * @return bool */ public function lte($interval): bool { return $this->lessThanOrEqualTo($interval); } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThanOrEqualTo($interval): bool { return $this->lessThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function between($interval1, $interval2, bool $equal = true): bool { return $equal ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) : $this->greaterThan($interval1) && $this->lessThan($interval2); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenIncluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenExcluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, false); } /** * Determines if the instance is between two others * * @example * ``` * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function isBetween($interval1, $interval2, bool $equal = true): bool { return $this->between($interval1, $interval2, $equal); } /** * Round the current instance at the given unit with given precision if specified and the given function. * * @throws Exception */ public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); } /** * Truncate the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function floorUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function ceilUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified. * * @param float|int|string|DateInterval|null $precision * @param string $function * * @throws Exception * * @return $this */ public function round($precision = 1, string $function = 'round'): static { return $this->roundWith($precision, $function); } /** * Round the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function floor(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function ceil(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'ceil'); } public function __unserialize(array $data): void { $properties = array_combine( array_map( static fn (mixed $key) => \is_string($key) ? str_replace('tzName', 'timezoneSetting', $key) : $key, array_keys($data), ), $data, ); if (method_exists(parent::class, '__unserialize')) { // PHP >= 8.2 parent::__unserialize($properties); return; } // PHP <= 8.1 // @codeCoverageIgnoreStart $properties = array_combine( array_map( static fn (string $property) => preg_replace('/^\0.+\0/', '', $property), array_keys($data), ), $data, ); $localStrictMode = $this->localStrictModeEnabled; $this->localStrictModeEnabled = false; $days = $properties['days'] ?? false; $this->days = $days === false ? false : (int) $days; $this->y = (int) ($properties['y'] ?? 0); $this->m = (int) ($properties['m'] ?? 0); $this->d = (int) ($properties['d'] ?? 0); $this->h = (int) ($properties['h'] ?? 0); $this->i = (int) ($properties['i'] ?? 0); $this->s = (int) ($properties['s'] ?? 0); $this->f = (float) ($properties['f'] ?? 0.0); // @phpstan-ignore-next-line $this->weekday = (int) ($properties['weekday'] ?? 0); // @phpstan-ignore-next-line $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0); // @phpstan-ignore-next-line $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0); $this->invert = (int) ($properties['invert'] ?? 0); // @phpstan-ignore-next-line $this->special_type = (int) ($properties['special_type'] ?? 0); // @phpstan-ignore-next-line $this->special_amount = (int) ($properties['special_amount'] ?? 0); // @phpstan-ignore-next-line $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0); // @phpstan-ignore-next-line $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0); parent::__construct(self::getDateIntervalSpec($this)); foreach ($properties as $property => $value) { if ($property === 'localStrictModeEnabled') { continue; } $this->$property = $value; } $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode; // @codeCoverageIgnoreEnd } /** * @template T * * @param T $interval * @param mixed $original * * @return T */ private static function withOriginal(mixed $interval, mixed $original): mixed { if ($interval instanceof self) { $interval->originalInput = $original; } return $interval; } private static function standardizeUnit(string $unit): string { $unit = rtrim($unit, 'sz').'s'; return $unit === 'days' ? 'dayz' : $unit; } private static function getFlipCascadeFactors(): array { if (!self::$flipCascadeFactors) { self::$flipCascadeFactors = []; foreach (self::getCascadeFactors() as $to => [$factor, $from]) { self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; } } return self::$flipCascadeFactors; } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object { $mainClass = DateInterval::class; if (!is_a($className, $mainClass, true)) { throw new InvalidCastException("$className is not a sub-class of $mainClass."); } $microseconds = $interval->f; $instance = self::buildInstance($interval, $className, $skip); if ($instance instanceof self) { $instance->originalInput = $interval; } if ($microseconds) { $instance->f = $microseconds; } if ($interval instanceof self && is_a($className, self::class, true)) { self::copyStep($interval, $instance); } self::copyNegativeUnits($interval, $instance); return self::withOriginal($instance, $interval); } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function buildInstance( DateInterval $interval, string $className, array $skip = [], ): object { $serialization = self::buildSerializationString($interval, $className, $skip); return match ($serialization) { null => new $className(static::getDateIntervalSpec($interval, false, $skip)), default => unserialize($serialization), }; } /** * As demonstrated by rlanvin (https://github.com/rlanvin) in * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438 * * Modifying the output of serialize() to change the class name and unserializing * the tweaked string allows creating new interval instances where the ->days * property can be set. It's not possible neither with `new` nto with `__set_state`. * * It has a non-negligible performance cost, so we'll use this method only if * $interval->days !== false. */ private static function buildSerializationString( DateInterval $interval, string $className, array $skip = [], ): ?string { if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) { return null; } // De-enhance CarbonInterval objects to be serializable back to DateInterval if ($interval instanceof self && !is_a($className, self::class, true)) { $interval = clone $interval; unset($interval->timezoneSetting); unset($interval->originalInput); unset($interval->startDate); unset($interval->endDate); unset($interval->rawInterval); unset($interval->absolute); unset($interval->initialValues); unset($interval->clock); unset($interval->step); unset($interval->localMonthsOverflow); unset($interval->localYearsOverflow); unset($interval->localStrictModeEnabled); unset($interval->localHumanDiffOptions); unset($interval->localToStringFormat); unset($interval->localSerializer); unset($interval->localMacros); unset($interval->localGenericMacros); unset($interval->localFormatFunction); unset($interval->localTranslator); } $serialization = serialize($interval); $inputClass = $interval::class; $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":'; if (!str_starts_with($serialization, $expectedStart)) { return null; // @codeCoverageIgnore } return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart)); } private static function copyStep(self $from, self $to): void { $to->setStep($from->getStep()); } private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void { $to->invert = $from->invert; foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { if ($from->$unit < 0) { self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE); } } } private function invertCascade(array $values): static { return $this->set(array_map(function ($value) { return -$value; }, $values))->doCascade(true)->invert(); } private function doCascade(bool $deep): static { $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { if ($$key === 'dayz') { $$key = 'daysExcludeWeeks'; } } $value = $newData[$source]; $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; $decimalPart = fmod($newData[$source], 1); if ($decimalPart !== 0.0) { $unit = $source; foreach ($previous as [$subUnit, $subFactor]) { $newData[$unit] -= $decimalPart; $newData[$subUnit] += $decimalPart * $subFactor; $decimalPart = fmod($newData[$subUnit], 1); if ($decimalPart === 0.0) { break; } $unit = $subUnit; } } array_unshift($previous, [$source, $factor]); } $positive = null; if (!$deep) { foreach ($newData as $value) { if ($value) { if ($positive === null) { $positive = ($value > 0); continue; } if (($value > 0) !== $positive) { return $this->invertCascade($originalData) ->solveNegativeInterval(); } } } } return $this->set($newData) ->solveNegativeInterval(); } private function needsDeclension(string $mode, int $index, int $parts): bool { return match ($mode) { 'last' => $index === $parts - 1, default => true, }; } private function checkIntegerValue(string $name, mixed $value): void { if (\is_int($value)) { return; } $this->assertSafeForInteger($name, $value); if (\is_float($value) && (((float) (int) $value) === $value)) { return; } if (!self::$floatSettersEnabled) { $type = \gettype($value); @trigger_error( "Since 2.70.0, it's deprecated to pass $type value for $name.\n". "It's truncated when stored as an integer interval unit.\n". "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", \E_USER_DEPRECATED, ); } } /** * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. */ private function assertSafeForInteger(string $name, mixed $value): void { if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); } } private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void { if (self::$floatSettersEnabled) { $floatValue = (float) $value; $base = (float) $integerValue; if ($floatValue === $base) { return; } $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; $upper = true; foreach ($units as $property => $name) { if ($name === $unit) { $upper = false; continue; } if (!$upper && $this->$property !== 0) { throw new RuntimeException( "You cannot set $unit to a float value as $name would be overridden, ". 'set it first to 0 explicitly if you really want to erase its value' ); } } $this->add($unit, $floatValue - $base); } } private function getInnerValues(): array { return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days]; } private function checkStartAndEnd(): void { if ( $this->initialValues !== null && ($this->startDate !== null || $this->endDate !== null) && $this->initialValues !== $this->getInnerValues() ) { $this->absolute = false; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; } } /** @return $this */ private function setSetting(string $setting, mixed $value): self { switch ($setting) { case 'timezoneSetting': return $value === null ? $this : $this->setTimezone($value); case 'step': $this->setStep($value); return $this; case 'localMonthsOverflow': return $value === null ? $this : $this->settings(['monthOverflow' => $value]); case 'localYearsOverflow': return $value === null ? $this : $this->settings(['yearOverflow' => $value]); case 'localStrictModeEnabled': case 'localHumanDiffOptions': case 'localToStringFormat': case 'localSerializer': case 'localMacros': case 'localGenericMacros': case 'localFormatFunction': case 'localTranslator': $this->$setting = $value; return $this; default: // Drop unknown settings return $this; } } private static function incrementUnit(DateInterval $instance, string $unit, int $value): void { if ($value === 0) { return; } // @codeCoverageIgnoreStart if (PHP_VERSION_ID !== 8_03_20) { $instance->$unit += $value; return; } // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value); // @codeCoverageIgnoreEnd } /** @codeCoverageIgnore */ private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void { switch ($unit) { case 'y': $instance->y = $value; break; case 'm': $instance->m = $value; break; case 'd': $instance->d = $value; break; case 'h': $instance->h = $value; break; case 'i': $instance->i = $value; break; case 's': $instance->s = $value; break; default: $instance->$unit = $value; } } }
PHP
{ "end_line": 353, "name": "shiftTimezone", "signature": "public function shiftTimezone(DateTimeZone|string|int $timezone): static", "start_line": 333 }
{ "class_name": "CarbonInterval", "class_signature": "class CarbonInterval implements CarbonConverterInterface, UnitValue", "namespace": "Carbon" }
createFromFormat
Carbon/src/Carbon/CarbonInterval.php
public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH], 'day' => ['week' => Carbon::DAYS_PER_WEEK], 'hour' => ['day' => Carbon::HOURS_PER_DAY], 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], ]; return $defaults[$source][$target] ?? null; } /** * Returns current config for days per week. * * @return int|float */ public static function getDaysPerWeek() { return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; } /** * Returns current config for hours per day. * * @return int|float */ public static function getHoursPerDay() { return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; } /** * Returns current config for minutes per hour. * * @return int|float */ public static function getMinutesPerHour() { return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; } /** * Returns current config for seconds per minute. * * @return int|float */ public static function getSecondsPerMinute() { return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMillisecondsPerSecond() { return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMicrosecondsPerMillisecond() { return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; } /** * Create a new CarbonInterval instance from specific values. * This is an alias for the constructor that allows better fluent * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than * (new CarbonInterval(1))->fn(). * * @param int $years * @param int $months * @param int $weeks * @param int $days * @param int $hours * @param int $minutes * @param int $seconds * @param int $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. * * @return static */ public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); } /** * Parse a string into a new CarbonInterval object according to the specified format. * * @example * ``` * echo Carboninterval::createFromFormat('H:i', '1:30'); * ``` * * @param string $format Format of the $interval input string * @param string|null $interval Input string to convert into an interval * * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. * * @return static */ public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; } /** * Return the original source used to create the current interval. * * @return array|int|string|DateInterval|mixed|null */ public function original() { return $this->originalInput; } /** * Return the start date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function start(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->startDate; } /** * Return the end date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function end(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->endDate; } /** * Get rid of the original input, start date and end date that may be kept in memory. * * @return $this */ public function optimize(): static { $this->originalInput = null; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; $this->absolute = false; return $this; } /** * Get a copy of the instance. * * @return static */ public function copy(): static { $date = new static(0); $date->copyProperties($this); $date->step = $this->step; return $date; } /** * Get a copy of the instance. * * @return static */ public function clone(): static { return $this->copy(); } /** * Provide static helpers to create instances. Allows CarbonInterval::years(3). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @return static|mixed|null */ public static function __callStatic(string $method, array $parameters) { try { $interval = new static(0); $localStrictModeEnabled = $interval->localStrictModeEnabled; $interval->localStrictModeEnabled = true; $result = static::hasMacro($method) ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { return $interval->callMacro($method, $parameters); }) : $interval->$method(...$parameters); $interval->localStrictModeEnabled = $localStrictModeEnabled; return $result; } catch (BadFluentSetterException $exception) { if (Carbon::isStrictModeEnabled()) { throw new BadFluentConstructorException($method, 0, $exception); } return null; } } /** * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. * * @param array $dump data as exported by var_export() * * @return static */ #[ReturnTypeWillChange] public static function __set_state($dump) { /** @noinspection PhpVoidFunctionResultUsedInspection */ /** @var DateInterval $dateInterval */ $dateInterval = parent::__set_state($dump); return static::instance($dateInterval); } /** * Return the current context from inside a macro callee or a new one if static. * * @return static */ protected static function this(): static { return end(static::$macroContextStack) ?: new static(0); } /** * Creates a CarbonInterval from string. * * Format: * * Suffix | Unit | Example | DateInterval expression * -------|---------|---------|------------------------ * y | years | 1y | P1Y * mo | months | 3mo | P3M * w | weeks | 2w | P2W * d | days | 28d | P28D * h | hours | 4h | PT4H * m | minutes | 12m | PT12M * s | seconds | 59s | PT59S * * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. * * Special cases: * - An empty string will return a zero interval * - Fractions are allowed for weeks, days, hours and minutes and will be converted * and rounded to the next smaller value (caution: 0.5w = 4d) * * @param string $intervalDefinition * * @throws InvalidIntervalException * * @return static */ public static function fromString(string $intervalDefinition): static { if (empty($intervalDefinition)) { return self::withOriginal(new static(0), $intervalDefinition); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $milliseconds = 0; $microseconds = 0; $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ([$part, $value, $unit] = array_shift($parts)) { $intValue = (int) $value; $fraction = (float) $value - $intValue; // Fix calculation precision switch (round($fraction, 6)) { case 1: $fraction = 0; $intValue++; break; case 0: $fraction = 0; break; } switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { case 'millennia': case 'millennium': $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; break; case 'century': case 'centuries': $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; break; case 'decade': case 'decades': $years += $intValue * CarbonInterface::YEARS_PER_DECADE; break; case 'year': case 'years': case 'y': case 'yr': case 'yrs': $years += $intValue; break; case 'quarter': case 'quarters': $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; break; case 'month': case 'months': case 'mo': case 'mos': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; } break; case 'second': case 'seconds': case 's': $seconds += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; } break; case 'millisecond': case 'milliseconds': case 'milli': case 'ms': $milliseconds += $intValue; if ($fraction) { $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); } break; case 'microsecond': case 'microseconds': case 'micro': case 'µs': $microseconds += $intValue; break; default: throw new InvalidIntervalException( "Invalid part $part in definition $intervalDefinition", ); } } return self::withOriginal( new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds), $intervalDefinition, ); } /** * Creates a CarbonInterval from string using a different locale. * * @param string $interval interval string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be used instead. * * @return static */ public static function parseFromLocale(string $interval, ?string $locale = null): static { return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE)); } /** * Create an interval from the difference between 2 dates. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $start * @param \Carbon\Carbon|\DateTimeInterface|mixed $end * * @return static */ public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; } /** * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function abs(bool $absolute = false): static { if ($absolute && $this->invert) { $this->invert(); } return $this; } /** * @alias abs * * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function absolute(bool $absolute = true): static { return $this->abs($absolute); } /** * Cast the current instance into the given class. * * @template T of DateInterval * * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { return self::castIntervalToClass($this, $className); } /** * Create a CarbonInterval instance from a DateInterval one. Can not instance * DateInterval objects created from DateTime::diff() as you can't externally * set the $days field. * * @param DateInterval $interval * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static */ public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static { if ($skipCopy && $interval instanceof static) { return $interval; } return self::castIntervalToClass($interval, static::class, $skip); } /** * Make a CarbonInterval instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static|null */ public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); } protected static function makeFromString(string $interval): ?self { $interval = preg_replace('/\s+/', ' ', trim($interval)); if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { return static::fromString($interval); } $intervalInstance = static::createFromDateString($interval); return $intervalInstance->isEmpty() ? null : $intervalInstance; } protected function resolveInterval($interval): ?self { if (!($interval instanceof self)) { return self::make($interval); } return $interval; } /** * Sets up a DateInterval from the relative parts of the string. * * @param string $datetime * * @return static * * @link https://php.net/manual/en/dateinterval.createfromdatestring.php */ public static function createFromDateString(string $datetime): static { $string = strtr($datetime, [ ',' => ' ', ' and ' => ' ', ]); $previousException = null; try { $interval = parent::createFromDateString($string); } catch (Throwable $exception) { $interval = null; $previousException = $exception; } $interval ?: throw new InvalidFormatException( 'Could not create interval from: '.var_export($datetime, true), previous: $previousException, ); if (!($interval instanceof static)) { $interval = static::instance($interval); } return self::withOriginal($interval, $datetime); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the CarbonInterval object. */ public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; } /** * Get a part of the CarbonInterval object. */ public function __get(string $name): int|float|string|null { return $this->get($name); } /** * Set a part of the CarbonInterval object. * * @param Unit|string|array $name * @param int $value * * @throws UnknownSetterException * * @return $this */ public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; } /** * Set a part of the CarbonInterval object. * * @param string $name * @param int $value * * @throws UnknownSetterException */ public function __set(string $name, $value) { $this->set($name, $value); } /** * Allow setting of weeks and days to be cumulative. * * @param int $weeks Number of weeks to set * @param int $days Number of days to set * * @return static */ public function weeksAndDays(int $weeks, int $days): static { $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; return $this; } /** * Returns true if the interval is empty for each unit. * * @return bool */ public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonInterval::macro('twice', function () { * return $this->times(2); * }); * echo CarbonInterval::hours(2)->twice(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonInterval::mixin(new class { * public function daysToHours() { * return function () { * $this->hours += $this->days; * $this->days = 0; * * return $this; * }; * } * public function hoursToDays() { * return function () { * $this->days += $this->hours; * $this->hours = 0; * * return $this; * }; * } * }); * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; * echo CarbonInterval::days(5)->daysToHours() . "\n"; * ``` * * @param object|string $mixin * * @throws ReflectionException * * @return void */ public static function mixin($mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Call given macro. * * @param string $name * @param array $parameters * * @return mixed */ protected function callMacro(string $name, array $parameters) { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadFluentSetterException|Throwable * * @return static|int|float|string */ public function __call(string $method, array $parameters) { if (static::hasMacro($method)) { return static::bindMacroContext($this, function () use (&$method, &$parameters) { return $this->callMacro($method, $parameters); }); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); return $this->{$match['method']}($value, $match['unit']); } $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); try { $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); } } return $this; } protected function getForHumansInitialVariables($syntax, $short): array { if (\is_array($syntax)) { return $syntax; } if (\is_int($short)) { return [ 'parts' => $short, 'short' => false, ]; } if (\is_bool($syntax)) { return [ 'short' => $syntax, 'syntax' => CarbonInterface::DIFF_ABSOLUTE, ]; } return []; } /** * @param mixed $syntax * @param mixed $short * @param mixed $parts * @param mixed $options * * @return array */ protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array { $optionalSpace = ' '; $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; /** @var bool|string $join */ $join = $default === '' ? '' : ' '; /** @var bool|array|string $altNumbers */ $altNumbers = false; $aUnit = false; $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); $skip = array_map( static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit, (array) $skip, ); $skip = array_map( 'strtolower', array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''), ); $syntax ??= CarbonInterface::DIFF_ABSOLUTE; if ($parts === self::NO_LIMIT) { $parts = INF; } $options ??= static::getHumanDiffOptions(); if ($join === false) { $join = ' '; } elseif ($join === true) { $join = [ $default, $this->getTranslationMessage('list.1') ?? $default, ]; } if ($altNumbers && $altNumbers !== true) { $language = new Language($this->locale); $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { [$default, $last] = $join; if ($default !== ' ') { $optionalSpace = ''; } $join = function ($list) use ($default, $last) { if (\count($list) < 2) { return implode('', $list); } $end = array_pop($list); return implode($default, $list).$last.$end; }; } if (\is_string($join)) { if ($join !== ' ') { $optionalSpace = ''; } $glue = $join; $join = static fn ($list) => implode($glue, $list); } $interpolations = [ ':optional-space' => $optionalSpace, ]; $translator ??= isset($locale) ? Translator::get($locale) : null; return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator]; } protected static function getRoundingMethodFromOptions(int $options): ?string { if ($options & CarbonInterface::ROUND) { return 'round'; } if ($options & CarbonInterface::CEIL) { return 'ceil'; } if ($options & CarbonInterface::FLOOR) { return 'floor'; } return null; } /** * Returns interval values as an array where key are the unit names and values the counts. * * @return int[] */ public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; } /** * Returns interval non-zero values as an array where key are the unit names and values the counts. * * @return int[] */ public function getNonZeroValues(): array { return array_filter($this->toArray(), 'intval'); } /** * Returns interval values as an array where key are the unit names and values the counts * from the biggest non-zero one the the smallest non-zero one. * * @return int[] */ public function getValuesSequence(): array { $nonZeroValues = $this->getNonZeroValues(); if ($nonZeroValues === []) { return []; } $keys = array_keys($nonZeroValues); $firstKey = $keys[0]; $lastKey = $keys[\count($keys) - 1]; $values = []; $record = false; foreach ($this->toArray() as $unit => $count) { if ($unit === $firstKey) { $record = true; } if ($record) { $values[$unit] = $count; } if ($unit === $lastKey) { $record = false; } } return $values; } /** * Get the current interval in a human readable format in the current locale. * * @example * ``` * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; * ``` * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: -1: no limits) * @param int $options human diff options * * @throws Exception * * @return string */ public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string { /* @var TranslatorInterface|null $translator */ [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this ->getForHumansParameters($syntax, $short, $parts, $options); $interval = []; $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; $count = 1; $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); $declensionMode = null; $translator ??= $this->getLocalTranslator(); $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); if ($this->needsDeclension($declensionMode, $index, $parts)) { // Some languages have special pluralization for past and future tense. $key = $unit.'_'.$transId; $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); if ($result !== $key) { return $result; } } } $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); if ($result !== $unit) { return $result; } return null; }; $intervalValues = $this; $method = static::getRoundingMethodFromOptions($options); if ($method) { $previousCount = INF; while ( \count($intervalValues->getNonZeroValues()) > $parts && ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 ) { $index = min($count, $previousCount - 1) - 2; if ($index < 0) { break; } $intervalValues = $this->copy()->roundUnit( $keys[$index], 1, $method, ); $previousCount = $count; } } $diffIntervalArray = [ ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], ]; if (!empty($skip)) { foreach ($diffIntervalArray as $index => &$unitData) { $nextIndex = $index + 1; if ($unitData['value'] && isset($diffIntervalArray[$nextIndex]) && \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) ) { $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); $unitData['value'] = 0; } } } $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; } } if (!$absolute) { return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); }; $fallbackUnit = ['second', 's']; foreach ($diffIntervalArray as $diffIntervalData) { if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } // break the loop after we get the required number of parts in array if (\count($interval) >= $parts) { break; } // break the loop after we have reached the minimum unit if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } $actualParts = \count($interval); foreach ($interval as $index => &$item) { $item = $transChoice($item[0], $item[1], $index, $actualParts); } if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; $unit = $fallbackUnit[$short ? 1 : 0]; $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); } // join the interval parts by a space $time = $join($interval); unset($diffIntervalArray, $interval); if ($absolute) { return $time; } $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); if ($parts === 1) { if ($relativeToNow && $unit === 'day') { $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null; if ($specialTranslations && $options & $specialTranslations['option']) { $key = $specialTranslations[$isFuture ? 'future' : 'past']; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } } $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; } $time = [':time' => $time]; return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); } public function format(string $format): string { $output = parent::format($format); if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) { return $output; } $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate); return str_replace('(unknown)', $this->rawInterval->format('%a'), $output); } /** * Format the instance as a string using the forHumans() function. * * @throws Exception * * @return string */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if (!$format) { return $this->forHumans(); } if ($format instanceof Closure) { return $format($this); } return $this->format($format); } /** * Return native DateInterval PHP object matching the current instance. * * @example * ``` * var_dump(CarbonInterval::hours(2)->toDateInterval()); * ``` * * @return DateInterval */ public function toDateInterval(): DateInterval { return self::castIntervalToClass($this, DateInterval::class); } /** * Convert the interval to a CarbonPeriod. * * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. * * @return CarbonPeriod */ public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); } /** * Decompose the current interval into * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); } /** * Invert the interval. * * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this */ public function invert($inverted = null): static { $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; return $this; } protected function solveNegativeInterval(): static { if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { $this->years *= self::NEGATIVE; $this->months *= self::NEGATIVE; $this->dayz *= self::NEGATIVE; $this->hours *= self::NEGATIVE; $this->minutes *= self::NEGATIVE; $this->seconds *= self::NEGATIVE; $this->microseconds *= self::NEGATIVE; $this->invert(); } return $this; } /** * Add the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function sub($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } return $this->add($unit, -(float) $value); } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function subtract($unit, $value = 1): static { return $this->sub($unit, $value); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Multiply current instance given number of times. times() is naive, it multiplies each unit * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded * separately for each unit. * * Use times() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see multiply() * * @param float|int $factor * * @return $this */ public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; } /** * Divide current instance by a given divider. shares() is naive, it divides each unit separately * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours * and 7 minutes. * * Use shares() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see divide() * * @param float|int $divider * * @return $this */ public function shares($divider): static { return $this->times(1 / $divider); } protected function copyProperties(self $interval, $ignoreSign = false): static { $this->years = $interval->years; $this->months = $interval->months; $this->dayz = $interval->dayz; $this->hours = $interval->hours; $this->minutes = $interval->minutes; $this->seconds = $interval->seconds; $this->microseconds = $interval->microseconds; if (!$ignoreSign) { $this->invert = $interval->invert; } return $this; } /** * Multiply and cascade current instance by a given factor. * * @param float|int $factor * * @return $this */ public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); } /** * Divide and cascade current instance by a given divider. * * @param float|int $divider * * @return $this */ public function divide($divider): static { return $this->multiply(1 / $divider); } /** * Get the interval_spec string of a date interval. * * @param DateInterval $interval * * @return string */ public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), static::PERIOD_MONTHS => abs($interval->m), static::PERIOD_DAYS => abs($interval->d), ]); $skip = array_map([Unit::class, 'toNameIfUnit'], $skip); if ( $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) ) { $date = [ static::PERIOD_DAYS => abs($interval->days), ]; } $seconds = abs($interval->s); if ($microseconds && $interval->f > 0) { $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); } $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; foreach ($date as $key => $value) { $specString .= $value.$key; } if (\count($time) > 0) { $specString .= static::PERIOD_TIME_PREFIX; foreach ($time as $key => $value) { $specString .= $value.$key; } } return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; } /** * Get the interval_spec string. * * @return string */ public function spec(bool $microseconds = false): string { return static::getDateIntervalSpec($this, $microseconds); } /** * Comparing 2 date intervals. * * @param DateInterval $first * @param DateInterval $second * * @return int 0, 1 or -1 */ public static function compareDateIntervals(DateInterval $first, DateInterval $second): int { $current = Carbon::now(); $passed = $current->avoidMutation()->add($second); $current->add($first); return $current <=> $passed; } /** * Comparing with passed interval. * * @param DateInterval $interval * * @return int 0, 1 or -1 */ public function compare(DateInterval $interval): int { return static::compareDateIntervals($this, $interval); } /** * Convert overflowed values into bigger units. * * @return $this */ public function cascade(): static { return $this->doCascade(false); } public function hasNegativeValues(): bool { foreach ($this->toArray() as $value) { if ($value < 0) { return true; } } return false; } public function hasPositiveValues(): bool { foreach ($this->toArray() as $value) { if ($value > 0) { return true; } } return false; } /** * Get amount of given unit equivalent to the interval. * * @param string $unit * * @throws UnknownUnitException|UnitNotConfiguredException * * @return float */ public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see equalTo() * * @return bool */ public function eq($interval): bool { return $this->equalTo($interval); } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see notEqualTo() * * @return bool */ public function ne($interval): bool { return $this->notEqualTo($interval); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function notEqualTo($interval): bool { return !$this->eq($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThan() * * @return bool */ public function gt($interval): bool { return $this->greaterThan($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThanOrEqualTo() * * @return bool */ public function gte($interval): bool { return $this->greaterThanOrEqualTo($interval); } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThanOrEqualTo($interval): bool { return $this->greaterThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThan() * * @return bool */ public function lt($interval): bool { return $this->lessThan($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThanOrEqualTo() * * @return bool */ public function lte($interval): bool { return $this->lessThanOrEqualTo($interval); } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThanOrEqualTo($interval): bool { return $this->lessThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function between($interval1, $interval2, bool $equal = true): bool { return $equal ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) : $this->greaterThan($interval1) && $this->lessThan($interval2); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenIncluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenExcluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, false); } /** * Determines if the instance is between two others * * @example * ``` * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function isBetween($interval1, $interval2, bool $equal = true): bool { return $this->between($interval1, $interval2, $equal); } /** * Round the current instance at the given unit with given precision if specified and the given function. * * @throws Exception */ public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); } /** * Truncate the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function floorUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function ceilUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified. * * @param float|int|string|DateInterval|null $precision * @param string $function * * @throws Exception * * @return $this */ public function round($precision = 1, string $function = 'round'): static { return $this->roundWith($precision, $function); } /** * Round the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function floor(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function ceil(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'ceil'); } public function __unserialize(array $data): void { $properties = array_combine( array_map( static fn (mixed $key) => \is_string($key) ? str_replace('tzName', 'timezoneSetting', $key) : $key, array_keys($data), ), $data, ); if (method_exists(parent::class, '__unserialize')) { // PHP >= 8.2 parent::__unserialize($properties); return; } // PHP <= 8.1 // @codeCoverageIgnoreStart $properties = array_combine( array_map( static fn (string $property) => preg_replace('/^\0.+\0/', '', $property), array_keys($data), ), $data, ); $localStrictMode = $this->localStrictModeEnabled; $this->localStrictModeEnabled = false; $days = $properties['days'] ?? false; $this->days = $days === false ? false : (int) $days; $this->y = (int) ($properties['y'] ?? 0); $this->m = (int) ($properties['m'] ?? 0); $this->d = (int) ($properties['d'] ?? 0); $this->h = (int) ($properties['h'] ?? 0); $this->i = (int) ($properties['i'] ?? 0); $this->s = (int) ($properties['s'] ?? 0); $this->f = (float) ($properties['f'] ?? 0.0); // @phpstan-ignore-next-line $this->weekday = (int) ($properties['weekday'] ?? 0); // @phpstan-ignore-next-line $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0); // @phpstan-ignore-next-line $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0); $this->invert = (int) ($properties['invert'] ?? 0); // @phpstan-ignore-next-line $this->special_type = (int) ($properties['special_type'] ?? 0); // @phpstan-ignore-next-line $this->special_amount = (int) ($properties['special_amount'] ?? 0); // @phpstan-ignore-next-line $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0); // @phpstan-ignore-next-line $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0); parent::__construct(self::getDateIntervalSpec($this)); foreach ($properties as $property => $value) { if ($property === 'localStrictModeEnabled') { continue; } $this->$property = $value; } $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode; // @codeCoverageIgnoreEnd } /** * @template T * * @param T $interval * @param mixed $original * * @return T */ private static function withOriginal(mixed $interval, mixed $original): mixed { if ($interval instanceof self) { $interval->originalInput = $original; } return $interval; } private static function standardizeUnit(string $unit): string { $unit = rtrim($unit, 'sz').'s'; return $unit === 'days' ? 'dayz' : $unit; } private static function getFlipCascadeFactors(): array { if (!self::$flipCascadeFactors) { self::$flipCascadeFactors = []; foreach (self::getCascadeFactors() as $to => [$factor, $from]) { self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; } } return self::$flipCascadeFactors; } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object { $mainClass = DateInterval::class; if (!is_a($className, $mainClass, true)) { throw new InvalidCastException("$className is not a sub-class of $mainClass."); } $microseconds = $interval->f; $instance = self::buildInstance($interval, $className, $skip); if ($instance instanceof self) { $instance->originalInput = $interval; } if ($microseconds) { $instance->f = $microseconds; } if ($interval instanceof self && is_a($className, self::class, true)) { self::copyStep($interval, $instance); } self::copyNegativeUnits($interval, $instance); return self::withOriginal($instance, $interval); } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function buildInstance( DateInterval $interval, string $className, array $skip = [], ): object { $serialization = self::buildSerializationString($interval, $className, $skip); return match ($serialization) { null => new $className(static::getDateIntervalSpec($interval, false, $skip)), default => unserialize($serialization), }; } /** * As demonstrated by rlanvin (https://github.com/rlanvin) in * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438 * * Modifying the output of serialize() to change the class name and unserializing * the tweaked string allows creating new interval instances where the ->days * property can be set. It's not possible neither with `new` nto with `__set_state`. * * It has a non-negligible performance cost, so we'll use this method only if * $interval->days !== false. */ private static function buildSerializationString( DateInterval $interval, string $className, array $skip = [], ): ?string { if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) { return null; } // De-enhance CarbonInterval objects to be serializable back to DateInterval if ($interval instanceof self && !is_a($className, self::class, true)) { $interval = clone $interval; unset($interval->timezoneSetting); unset($interval->originalInput); unset($interval->startDate); unset($interval->endDate); unset($interval->rawInterval); unset($interval->absolute); unset($interval->initialValues); unset($interval->clock); unset($interval->step); unset($interval->localMonthsOverflow); unset($interval->localYearsOverflow); unset($interval->localStrictModeEnabled); unset($interval->localHumanDiffOptions); unset($interval->localToStringFormat); unset($interval->localSerializer); unset($interval->localMacros); unset($interval->localGenericMacros); unset($interval->localFormatFunction); unset($interval->localTranslator); } $serialization = serialize($interval); $inputClass = $interval::class; $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":'; if (!str_starts_with($serialization, $expectedStart)) { return null; // @codeCoverageIgnore } return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart)); } private static function copyStep(self $from, self $to): void { $to->setStep($from->getStep()); } private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void { $to->invert = $from->invert; foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { if ($from->$unit < 0) { self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE); } } } private function invertCascade(array $values): static { return $this->set(array_map(function ($value) { return -$value; }, $values))->doCascade(true)->invert(); } private function doCascade(bool $deep): static { $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { if ($$key === 'dayz') { $$key = 'daysExcludeWeeks'; } } $value = $newData[$source]; $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; $decimalPart = fmod($newData[$source], 1); if ($decimalPart !== 0.0) { $unit = $source; foreach ($previous as [$subUnit, $subFactor]) { $newData[$unit] -= $decimalPart; $newData[$subUnit] += $decimalPart * $subFactor; $decimalPart = fmod($newData[$subUnit], 1); if ($decimalPart === 0.0) { break; } $unit = $subUnit; } } array_unshift($previous, [$source, $factor]); } $positive = null; if (!$deep) { foreach ($newData as $value) { if ($value) { if ($positive === null) { $positive = ($value > 0); continue; } if (($value > 0) !== $positive) { return $this->invertCascade($originalData) ->solveNegativeInterval(); } } } } return $this->set($newData) ->solveNegativeInterval(); } private function needsDeclension(string $mode, int $index, int $parts): bool { return match ($mode) { 'last' => $index === $parts - 1, default => true, }; } private function checkIntegerValue(string $name, mixed $value): void { if (\is_int($value)) { return; } $this->assertSafeForInteger($name, $value); if (\is_float($value) && (((float) (int) $value) === $value)) { return; } if (!self::$floatSettersEnabled) { $type = \gettype($value); @trigger_error( "Since 2.70.0, it's deprecated to pass $type value for $name.\n". "It's truncated when stored as an integer interval unit.\n". "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", \E_USER_DEPRECATED, ); } } /** * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. */ private function assertSafeForInteger(string $name, mixed $value): void { if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); } } private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void { if (self::$floatSettersEnabled) { $floatValue = (float) $value; $base = (float) $integerValue; if ($floatValue === $base) { return; } $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; $upper = true; foreach ($units as $property => $name) { if ($name === $unit) { $upper = false; continue; } if (!$upper && $this->$property !== 0) { throw new RuntimeException( "You cannot set $unit to a float value as $name would be overridden, ". 'set it first to 0 explicitly if you really want to erase its value' ); } } $this->add($unit, $floatValue - $base); } } private function getInnerValues(): array { return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days]; } private function checkStartAndEnd(): void { if ( $this->initialValues !== null && ($this->startDate !== null || $this->endDate !== null) && $this->initialValues !== $this->getInnerValues() ) { $this->absolute = false; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; } } /** @return $this */ private function setSetting(string $setting, mixed $value): self { switch ($setting) { case 'timezoneSetting': return $value === null ? $this : $this->setTimezone($value); case 'step': $this->setStep($value); return $this; case 'localMonthsOverflow': return $value === null ? $this : $this->settings(['monthOverflow' => $value]); case 'localYearsOverflow': return $value === null ? $this : $this->settings(['yearOverflow' => $value]); case 'localStrictModeEnabled': case 'localHumanDiffOptions': case 'localToStringFormat': case 'localSerializer': case 'localMacros': case 'localGenericMacros': case 'localFormatFunction': case 'localTranslator': $this->$setting = $value; return $this; default: // Drop unknown settings return $this; } } private static function incrementUnit(DateInterval $instance, string $unit, int $value): void { if ($value === 0) { return; } // @codeCoverageIgnoreStart if (PHP_VERSION_ID !== 8_03_20) { $instance->$unit += $value; return; } // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value); // @codeCoverageIgnoreEnd } /** @codeCoverageIgnore */ private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void { switch ($unit) { case 'y': $instance->y = $value; break; case 'm': $instance->m = $value; break; case 'd': $instance->d = $value; break; case 'h': $instance->h = $value; break; case 'i': $instance->i = $value; break; case 's': $instance->s = $value; break; default: $instance->$unit = $value; } } }
PHP
{ "end_line": 764, "name": "createFromFormat", "signature": "public static function createFromFormat(string $format, ?string $interval): static", "start_line": 714 }
{ "class_name": "CarbonInterval", "class_signature": "class CarbonInterval implements CarbonConverterInterface, UnitValue", "namespace": "Carbon" }
diff
Carbon/src/Carbon/CarbonInterval.php
public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH], 'day' => ['week' => Carbon::DAYS_PER_WEEK], 'hour' => ['day' => Carbon::HOURS_PER_DAY], 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], ]; return $defaults[$source][$target] ?? null; } /** * Returns current config for days per week. * * @return int|float */ public static function getDaysPerWeek() { return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; } /** * Returns current config for hours per day. * * @return int|float */ public static function getHoursPerDay() { return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; } /** * Returns current config for minutes per hour. * * @return int|float */ public static function getMinutesPerHour() { return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; } /** * Returns current config for seconds per minute. * * @return int|float */ public static function getSecondsPerMinute() { return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMillisecondsPerSecond() { return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMicrosecondsPerMillisecond() { return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; } /** * Create a new CarbonInterval instance from specific values. * This is an alias for the constructor that allows better fluent * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than * (new CarbonInterval(1))->fn(). * * @param int $years * @param int $months * @param int $weeks * @param int $days * @param int $hours * @param int $minutes * @param int $seconds * @param int $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. * * @return static */ public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); } /** * Parse a string into a new CarbonInterval object according to the specified format. * * @example * ``` * echo Carboninterval::createFromFormat('H:i', '1:30'); * ``` * * @param string $format Format of the $interval input string * @param string|null $interval Input string to convert into an interval * * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. * * @return static */ public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; } /** * Return the original source used to create the current interval. * * @return array|int|string|DateInterval|mixed|null */ public function original() { return $this->originalInput; } /** * Return the start date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function start(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->startDate; } /** * Return the end date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function end(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->endDate; } /** * Get rid of the original input, start date and end date that may be kept in memory. * * @return $this */ public function optimize(): static { $this->originalInput = null; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; $this->absolute = false; return $this; } /** * Get a copy of the instance. * * @return static */ public function copy(): static { $date = new static(0); $date->copyProperties($this); $date->step = $this->step; return $date; } /** * Get a copy of the instance. * * @return static */ public function clone(): static { return $this->copy(); } /** * Provide static helpers to create instances. Allows CarbonInterval::years(3). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @return static|mixed|null */ public static function __callStatic(string $method, array $parameters) { try { $interval = new static(0); $localStrictModeEnabled = $interval->localStrictModeEnabled; $interval->localStrictModeEnabled = true; $result = static::hasMacro($method) ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { return $interval->callMacro($method, $parameters); }) : $interval->$method(...$parameters); $interval->localStrictModeEnabled = $localStrictModeEnabled; return $result; } catch (BadFluentSetterException $exception) { if (Carbon::isStrictModeEnabled()) { throw new BadFluentConstructorException($method, 0, $exception); } return null; } } /** * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. * * @param array $dump data as exported by var_export() * * @return static */ #[ReturnTypeWillChange] public static function __set_state($dump) { /** @noinspection PhpVoidFunctionResultUsedInspection */ /** @var DateInterval $dateInterval */ $dateInterval = parent::__set_state($dump); return static::instance($dateInterval); } /** * Return the current context from inside a macro callee or a new one if static. * * @return static */ protected static function this(): static { return end(static::$macroContextStack) ?: new static(0); } /** * Creates a CarbonInterval from string. * * Format: * * Suffix | Unit | Example | DateInterval expression * -------|---------|---------|------------------------ * y | years | 1y | P1Y * mo | months | 3mo | P3M * w | weeks | 2w | P2W * d | days | 28d | P28D * h | hours | 4h | PT4H * m | minutes | 12m | PT12M * s | seconds | 59s | PT59S * * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. * * Special cases: * - An empty string will return a zero interval * - Fractions are allowed for weeks, days, hours and minutes and will be converted * and rounded to the next smaller value (caution: 0.5w = 4d) * * @param string $intervalDefinition * * @throws InvalidIntervalException * * @return static */ public static function fromString(string $intervalDefinition): static { if (empty($intervalDefinition)) { return self::withOriginal(new static(0), $intervalDefinition); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $milliseconds = 0; $microseconds = 0; $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ([$part, $value, $unit] = array_shift($parts)) { $intValue = (int) $value; $fraction = (float) $value - $intValue; // Fix calculation precision switch (round($fraction, 6)) { case 1: $fraction = 0; $intValue++; break; case 0: $fraction = 0; break; } switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { case 'millennia': case 'millennium': $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; break; case 'century': case 'centuries': $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; break; case 'decade': case 'decades': $years += $intValue * CarbonInterface::YEARS_PER_DECADE; break; case 'year': case 'years': case 'y': case 'yr': case 'yrs': $years += $intValue; break; case 'quarter': case 'quarters': $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; break; case 'month': case 'months': case 'mo': case 'mos': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; } break; case 'second': case 'seconds': case 's': $seconds += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; } break; case 'millisecond': case 'milliseconds': case 'milli': case 'ms': $milliseconds += $intValue; if ($fraction) { $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); } break; case 'microsecond': case 'microseconds': case 'micro': case 'µs': $microseconds += $intValue; break; default: throw new InvalidIntervalException( "Invalid part $part in definition $intervalDefinition", ); } } return self::withOriginal( new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds), $intervalDefinition, ); } /** * Creates a CarbonInterval from string using a different locale. * * @param string $interval interval string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be used instead. * * @return static */ public static function parseFromLocale(string $interval, ?string $locale = null): static { return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE)); } /** * Create an interval from the difference between 2 dates. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $start * @param \Carbon\Carbon|\DateTimeInterface|mixed $end * * @return static */ public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; } /** * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function abs(bool $absolute = false): static { if ($absolute && $this->invert) { $this->invert(); } return $this; } /** * @alias abs * * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function absolute(bool $absolute = true): static { return $this->abs($absolute); } /** * Cast the current instance into the given class. * * @template T of DateInterval * * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { return self::castIntervalToClass($this, $className); } /** * Create a CarbonInterval instance from a DateInterval one. Can not instance * DateInterval objects created from DateTime::diff() as you can't externally * set the $days field. * * @param DateInterval $interval * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static */ public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static { if ($skipCopy && $interval instanceof static) { return $interval; } return self::castIntervalToClass($interval, static::class, $skip); } /** * Make a CarbonInterval instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static|null */ public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); } protected static function makeFromString(string $interval): ?self { $interval = preg_replace('/\s+/', ' ', trim($interval)); if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { return static::fromString($interval); } $intervalInstance = static::createFromDateString($interval); return $intervalInstance->isEmpty() ? null : $intervalInstance; } protected function resolveInterval($interval): ?self { if (!($interval instanceof self)) { return self::make($interval); } return $interval; } /** * Sets up a DateInterval from the relative parts of the string. * * @param string $datetime * * @return static * * @link https://php.net/manual/en/dateinterval.createfromdatestring.php */ public static function createFromDateString(string $datetime): static { $string = strtr($datetime, [ ',' => ' ', ' and ' => ' ', ]); $previousException = null; try { $interval = parent::createFromDateString($string); } catch (Throwable $exception) { $interval = null; $previousException = $exception; } $interval ?: throw new InvalidFormatException( 'Could not create interval from: '.var_export($datetime, true), previous: $previousException, ); if (!($interval instanceof static)) { $interval = static::instance($interval); } return self::withOriginal($interval, $datetime); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the CarbonInterval object. */ public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; } /** * Get a part of the CarbonInterval object. */ public function __get(string $name): int|float|string|null { return $this->get($name); } /** * Set a part of the CarbonInterval object. * * @param Unit|string|array $name * @param int $value * * @throws UnknownSetterException * * @return $this */ public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; } /** * Set a part of the CarbonInterval object. * * @param string $name * @param int $value * * @throws UnknownSetterException */ public function __set(string $name, $value) { $this->set($name, $value); } /** * Allow setting of weeks and days to be cumulative. * * @param int $weeks Number of weeks to set * @param int $days Number of days to set * * @return static */ public function weeksAndDays(int $weeks, int $days): static { $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; return $this; } /** * Returns true if the interval is empty for each unit. * * @return bool */ public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonInterval::macro('twice', function () { * return $this->times(2); * }); * echo CarbonInterval::hours(2)->twice(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonInterval::mixin(new class { * public function daysToHours() { * return function () { * $this->hours += $this->days; * $this->days = 0; * * return $this; * }; * } * public function hoursToDays() { * return function () { * $this->days += $this->hours; * $this->hours = 0; * * return $this; * }; * } * }); * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; * echo CarbonInterval::days(5)->daysToHours() . "\n"; * ``` * * @param object|string $mixin * * @throws ReflectionException * * @return void */ public static function mixin($mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Call given macro. * * @param string $name * @param array $parameters * * @return mixed */ protected function callMacro(string $name, array $parameters) { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadFluentSetterException|Throwable * * @return static|int|float|string */ public function __call(string $method, array $parameters) { if (static::hasMacro($method)) { return static::bindMacroContext($this, function () use (&$method, &$parameters) { return $this->callMacro($method, $parameters); }); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); return $this->{$match['method']}($value, $match['unit']); } $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); try { $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); } } return $this; } protected function getForHumansInitialVariables($syntax, $short): array { if (\is_array($syntax)) { return $syntax; } if (\is_int($short)) { return [ 'parts' => $short, 'short' => false, ]; } if (\is_bool($syntax)) { return [ 'short' => $syntax, 'syntax' => CarbonInterface::DIFF_ABSOLUTE, ]; } return []; } /** * @param mixed $syntax * @param mixed $short * @param mixed $parts * @param mixed $options * * @return array */ protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array { $optionalSpace = ' '; $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; /** @var bool|string $join */ $join = $default === '' ? '' : ' '; /** @var bool|array|string $altNumbers */ $altNumbers = false; $aUnit = false; $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); $skip = array_map( static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit, (array) $skip, ); $skip = array_map( 'strtolower', array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''), ); $syntax ??= CarbonInterface::DIFF_ABSOLUTE; if ($parts === self::NO_LIMIT) { $parts = INF; } $options ??= static::getHumanDiffOptions(); if ($join === false) { $join = ' '; } elseif ($join === true) { $join = [ $default, $this->getTranslationMessage('list.1') ?? $default, ]; } if ($altNumbers && $altNumbers !== true) { $language = new Language($this->locale); $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { [$default, $last] = $join; if ($default !== ' ') { $optionalSpace = ''; } $join = function ($list) use ($default, $last) { if (\count($list) < 2) { return implode('', $list); } $end = array_pop($list); return implode($default, $list).$last.$end; }; } if (\is_string($join)) { if ($join !== ' ') { $optionalSpace = ''; } $glue = $join; $join = static fn ($list) => implode($glue, $list); } $interpolations = [ ':optional-space' => $optionalSpace, ]; $translator ??= isset($locale) ? Translator::get($locale) : null; return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator]; } protected static function getRoundingMethodFromOptions(int $options): ?string { if ($options & CarbonInterface::ROUND) { return 'round'; } if ($options & CarbonInterface::CEIL) { return 'ceil'; } if ($options & CarbonInterface::FLOOR) { return 'floor'; } return null; } /** * Returns interval values as an array where key are the unit names and values the counts. * * @return int[] */ public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; } /** * Returns interval non-zero values as an array where key are the unit names and values the counts. * * @return int[] */ public function getNonZeroValues(): array { return array_filter($this->toArray(), 'intval'); } /** * Returns interval values as an array where key are the unit names and values the counts * from the biggest non-zero one the the smallest non-zero one. * * @return int[] */ public function getValuesSequence(): array { $nonZeroValues = $this->getNonZeroValues(); if ($nonZeroValues === []) { return []; } $keys = array_keys($nonZeroValues); $firstKey = $keys[0]; $lastKey = $keys[\count($keys) - 1]; $values = []; $record = false; foreach ($this->toArray() as $unit => $count) { if ($unit === $firstKey) { $record = true; } if ($record) { $values[$unit] = $count; } if ($unit === $lastKey) { $record = false; } } return $values; } /** * Get the current interval in a human readable format in the current locale. * * @example * ``` * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; * ``` * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: -1: no limits) * @param int $options human diff options * * @throws Exception * * @return string */ public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string { /* @var TranslatorInterface|null $translator */ [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this ->getForHumansParameters($syntax, $short, $parts, $options); $interval = []; $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; $count = 1; $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); $declensionMode = null; $translator ??= $this->getLocalTranslator(); $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); if ($this->needsDeclension($declensionMode, $index, $parts)) { // Some languages have special pluralization for past and future tense. $key = $unit.'_'.$transId; $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); if ($result !== $key) { return $result; } } } $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); if ($result !== $unit) { return $result; } return null; }; $intervalValues = $this; $method = static::getRoundingMethodFromOptions($options); if ($method) { $previousCount = INF; while ( \count($intervalValues->getNonZeroValues()) > $parts && ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 ) { $index = min($count, $previousCount - 1) - 2; if ($index < 0) { break; } $intervalValues = $this->copy()->roundUnit( $keys[$index], 1, $method, ); $previousCount = $count; } } $diffIntervalArray = [ ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], ]; if (!empty($skip)) { foreach ($diffIntervalArray as $index => &$unitData) { $nextIndex = $index + 1; if ($unitData['value'] && isset($diffIntervalArray[$nextIndex]) && \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) ) { $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); $unitData['value'] = 0; } } } $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; } } if (!$absolute) { return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); }; $fallbackUnit = ['second', 's']; foreach ($diffIntervalArray as $diffIntervalData) { if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } // break the loop after we get the required number of parts in array if (\count($interval) >= $parts) { break; } // break the loop after we have reached the minimum unit if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } $actualParts = \count($interval); foreach ($interval as $index => &$item) { $item = $transChoice($item[0], $item[1], $index, $actualParts); } if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; $unit = $fallbackUnit[$short ? 1 : 0]; $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); } // join the interval parts by a space $time = $join($interval); unset($diffIntervalArray, $interval); if ($absolute) { return $time; } $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); if ($parts === 1) { if ($relativeToNow && $unit === 'day') { $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null; if ($specialTranslations && $options & $specialTranslations['option']) { $key = $specialTranslations[$isFuture ? 'future' : 'past']; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } } $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; } $time = [':time' => $time]; return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); } public function format(string $format): string { $output = parent::format($format); if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) { return $output; } $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate); return str_replace('(unknown)', $this->rawInterval->format('%a'), $output); } /** * Format the instance as a string using the forHumans() function. * * @throws Exception * * @return string */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if (!$format) { return $this->forHumans(); } if ($format instanceof Closure) { return $format($this); } return $this->format($format); } /** * Return native DateInterval PHP object matching the current instance. * * @example * ``` * var_dump(CarbonInterval::hours(2)->toDateInterval()); * ``` * * @return DateInterval */ public function toDateInterval(): DateInterval { return self::castIntervalToClass($this, DateInterval::class); } /** * Convert the interval to a CarbonPeriod. * * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. * * @return CarbonPeriod */ public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); } /** * Decompose the current interval into * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); } /** * Invert the interval. * * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this */ public function invert($inverted = null): static { $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; return $this; } protected function solveNegativeInterval(): static { if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { $this->years *= self::NEGATIVE; $this->months *= self::NEGATIVE; $this->dayz *= self::NEGATIVE; $this->hours *= self::NEGATIVE; $this->minutes *= self::NEGATIVE; $this->seconds *= self::NEGATIVE; $this->microseconds *= self::NEGATIVE; $this->invert(); } return $this; } /** * Add the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function sub($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } return $this->add($unit, -(float) $value); } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function subtract($unit, $value = 1): static { return $this->sub($unit, $value); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Multiply current instance given number of times. times() is naive, it multiplies each unit * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded * separately for each unit. * * Use times() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see multiply() * * @param float|int $factor * * @return $this */ public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; } /** * Divide current instance by a given divider. shares() is naive, it divides each unit separately * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours * and 7 minutes. * * Use shares() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see divide() * * @param float|int $divider * * @return $this */ public function shares($divider): static { return $this->times(1 / $divider); } protected function copyProperties(self $interval, $ignoreSign = false): static { $this->years = $interval->years; $this->months = $interval->months; $this->dayz = $interval->dayz; $this->hours = $interval->hours; $this->minutes = $interval->minutes; $this->seconds = $interval->seconds; $this->microseconds = $interval->microseconds; if (!$ignoreSign) { $this->invert = $interval->invert; } return $this; } /** * Multiply and cascade current instance by a given factor. * * @param float|int $factor * * @return $this */ public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); } /** * Divide and cascade current instance by a given divider. * * @param float|int $divider * * @return $this */ public function divide($divider): static { return $this->multiply(1 / $divider); } /** * Get the interval_spec string of a date interval. * * @param DateInterval $interval * * @return string */ public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), static::PERIOD_MONTHS => abs($interval->m), static::PERIOD_DAYS => abs($interval->d), ]); $skip = array_map([Unit::class, 'toNameIfUnit'], $skip); if ( $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) ) { $date = [ static::PERIOD_DAYS => abs($interval->days), ]; } $seconds = abs($interval->s); if ($microseconds && $interval->f > 0) { $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); } $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; foreach ($date as $key => $value) { $specString .= $value.$key; } if (\count($time) > 0) { $specString .= static::PERIOD_TIME_PREFIX; foreach ($time as $key => $value) { $specString .= $value.$key; } } return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; } /** * Get the interval_spec string. * * @return string */ public function spec(bool $microseconds = false): string { return static::getDateIntervalSpec($this, $microseconds); } /** * Comparing 2 date intervals. * * @param DateInterval $first * @param DateInterval $second * * @return int 0, 1 or -1 */ public static function compareDateIntervals(DateInterval $first, DateInterval $second): int { $current = Carbon::now(); $passed = $current->avoidMutation()->add($second); $current->add($first); return $current <=> $passed; } /** * Comparing with passed interval. * * @param DateInterval $interval * * @return int 0, 1 or -1 */ public function compare(DateInterval $interval): int { return static::compareDateIntervals($this, $interval); } /** * Convert overflowed values into bigger units. * * @return $this */ public function cascade(): static { return $this->doCascade(false); } public function hasNegativeValues(): bool { foreach ($this->toArray() as $value) { if ($value < 0) { return true; } } return false; } public function hasPositiveValues(): bool { foreach ($this->toArray() as $value) { if ($value > 0) { return true; } } return false; } /** * Get amount of given unit equivalent to the interval. * * @param string $unit * * @throws UnknownUnitException|UnitNotConfiguredException * * @return float */ public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see equalTo() * * @return bool */ public function eq($interval): bool { return $this->equalTo($interval); } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see notEqualTo() * * @return bool */ public function ne($interval): bool { return $this->notEqualTo($interval); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function notEqualTo($interval): bool { return !$this->eq($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThan() * * @return bool */ public function gt($interval): bool { return $this->greaterThan($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThanOrEqualTo() * * @return bool */ public function gte($interval): bool { return $this->greaterThanOrEqualTo($interval); } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThanOrEqualTo($interval): bool { return $this->greaterThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThan() * * @return bool */ public function lt($interval): bool { return $this->lessThan($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThanOrEqualTo() * * @return bool */ public function lte($interval): bool { return $this->lessThanOrEqualTo($interval); } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThanOrEqualTo($interval): bool { return $this->lessThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function between($interval1, $interval2, bool $equal = true): bool { return $equal ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) : $this->greaterThan($interval1) && $this->lessThan($interval2); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenIncluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenExcluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, false); } /** * Determines if the instance is between two others * * @example * ``` * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function isBetween($interval1, $interval2, bool $equal = true): bool { return $this->between($interval1, $interval2, $equal); } /** * Round the current instance at the given unit with given precision if specified and the given function. * * @throws Exception */ public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); } /** * Truncate the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function floorUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function ceilUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified. * * @param float|int|string|DateInterval|null $precision * @param string $function * * @throws Exception * * @return $this */ public function round($precision = 1, string $function = 'round'): static { return $this->roundWith($precision, $function); } /** * Round the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function floor(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function ceil(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'ceil'); } public function __unserialize(array $data): void { $properties = array_combine( array_map( static fn (mixed $key) => \is_string($key) ? str_replace('tzName', 'timezoneSetting', $key) : $key, array_keys($data), ), $data, ); if (method_exists(parent::class, '__unserialize')) { // PHP >= 8.2 parent::__unserialize($properties); return; } // PHP <= 8.1 // @codeCoverageIgnoreStart $properties = array_combine( array_map( static fn (string $property) => preg_replace('/^\0.+\0/', '', $property), array_keys($data), ), $data, ); $localStrictMode = $this->localStrictModeEnabled; $this->localStrictModeEnabled = false; $days = $properties['days'] ?? false; $this->days = $days === false ? false : (int) $days; $this->y = (int) ($properties['y'] ?? 0); $this->m = (int) ($properties['m'] ?? 0); $this->d = (int) ($properties['d'] ?? 0); $this->h = (int) ($properties['h'] ?? 0); $this->i = (int) ($properties['i'] ?? 0); $this->s = (int) ($properties['s'] ?? 0); $this->f = (float) ($properties['f'] ?? 0.0); // @phpstan-ignore-next-line $this->weekday = (int) ($properties['weekday'] ?? 0); // @phpstan-ignore-next-line $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0); // @phpstan-ignore-next-line $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0); $this->invert = (int) ($properties['invert'] ?? 0); // @phpstan-ignore-next-line $this->special_type = (int) ($properties['special_type'] ?? 0); // @phpstan-ignore-next-line $this->special_amount = (int) ($properties['special_amount'] ?? 0); // @phpstan-ignore-next-line $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0); // @phpstan-ignore-next-line $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0); parent::__construct(self::getDateIntervalSpec($this)); foreach ($properties as $property => $value) { if ($property === 'localStrictModeEnabled') { continue; } $this->$property = $value; } $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode; // @codeCoverageIgnoreEnd } /** * @template T * * @param T $interval * @param mixed $original * * @return T */ private static function withOriginal(mixed $interval, mixed $original): mixed { if ($interval instanceof self) { $interval->originalInput = $original; } return $interval; } private static function standardizeUnit(string $unit): string { $unit = rtrim($unit, 'sz').'s'; return $unit === 'days' ? 'dayz' : $unit; } private static function getFlipCascadeFactors(): array { if (!self::$flipCascadeFactors) { self::$flipCascadeFactors = []; foreach (self::getCascadeFactors() as $to => [$factor, $from]) { self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; } } return self::$flipCascadeFactors; } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object { $mainClass = DateInterval::class; if (!is_a($className, $mainClass, true)) { throw new InvalidCastException("$className is not a sub-class of $mainClass."); } $microseconds = $interval->f; $instance = self::buildInstance($interval, $className, $skip); if ($instance instanceof self) { $instance->originalInput = $interval; } if ($microseconds) { $instance->f = $microseconds; } if ($interval instanceof self && is_a($className, self::class, true)) { self::copyStep($interval, $instance); } self::copyNegativeUnits($interval, $instance); return self::withOriginal($instance, $interval); } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function buildInstance( DateInterval $interval, string $className, array $skip = [], ): object { $serialization = self::buildSerializationString($interval, $className, $skip); return match ($serialization) { null => new $className(static::getDateIntervalSpec($interval, false, $skip)), default => unserialize($serialization), }; } /** * As demonstrated by rlanvin (https://github.com/rlanvin) in * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438 * * Modifying the output of serialize() to change the class name and unserializing * the tweaked string allows creating new interval instances where the ->days * property can be set. It's not possible neither with `new` nto with `__set_state`. * * It has a non-negligible performance cost, so we'll use this method only if * $interval->days !== false. */ private static function buildSerializationString( DateInterval $interval, string $className, array $skip = [], ): ?string { if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) { return null; } // De-enhance CarbonInterval objects to be serializable back to DateInterval if ($interval instanceof self && !is_a($className, self::class, true)) { $interval = clone $interval; unset($interval->timezoneSetting); unset($interval->originalInput); unset($interval->startDate); unset($interval->endDate); unset($interval->rawInterval); unset($interval->absolute); unset($interval->initialValues); unset($interval->clock); unset($interval->step); unset($interval->localMonthsOverflow); unset($interval->localYearsOverflow); unset($interval->localStrictModeEnabled); unset($interval->localHumanDiffOptions); unset($interval->localToStringFormat); unset($interval->localSerializer); unset($interval->localMacros); unset($interval->localGenericMacros); unset($interval->localFormatFunction); unset($interval->localTranslator); } $serialization = serialize($interval); $inputClass = $interval::class; $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":'; if (!str_starts_with($serialization, $expectedStart)) { return null; // @codeCoverageIgnore } return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart)); } private static function copyStep(self $from, self $to): void { $to->setStep($from->getStep()); } private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void { $to->invert = $from->invert; foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { if ($from->$unit < 0) { self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE); } } } private function invertCascade(array $values): static { return $this->set(array_map(function ($value) { return -$value; }, $values))->doCascade(true)->invert(); } private function doCascade(bool $deep): static { $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { if ($$key === 'dayz') { $$key = 'daysExcludeWeeks'; } } $value = $newData[$source]; $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; $decimalPart = fmod($newData[$source], 1); if ($decimalPart !== 0.0) { $unit = $source; foreach ($previous as [$subUnit, $subFactor]) { $newData[$unit] -= $decimalPart; $newData[$subUnit] += $decimalPart * $subFactor; $decimalPart = fmod($newData[$subUnit], 1); if ($decimalPart === 0.0) { break; } $unit = $subUnit; } } array_unshift($previous, [$source, $factor]); } $positive = null; if (!$deep) { foreach ($newData as $value) { if ($value) { if ($positive === null) { $positive = ($value > 0); continue; } if (($value > 0) !== $positive) { return $this->invertCascade($originalData) ->solveNegativeInterval(); } } } } return $this->set($newData) ->solveNegativeInterval(); } private function needsDeclension(string $mode, int $index, int $parts): bool { return match ($mode) { 'last' => $index === $parts - 1, default => true, }; } private function checkIntegerValue(string $name, mixed $value): void { if (\is_int($value)) { return; } $this->assertSafeForInteger($name, $value); if (\is_float($value) && (((float) (int) $value) === $value)) { return; } if (!self::$floatSettersEnabled) { $type = \gettype($value); @trigger_error( "Since 2.70.0, it's deprecated to pass $type value for $name.\n". "It's truncated when stored as an integer interval unit.\n". "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", \E_USER_DEPRECATED, ); } } /** * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. */ private function assertSafeForInteger(string $name, mixed $value): void { if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); } } private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void { if (self::$floatSettersEnabled) { $floatValue = (float) $value; $base = (float) $integerValue; if ($floatValue === $base) { return; } $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; $upper = true; foreach ($units as $property => $name) { if ($name === $unit) { $upper = false; continue; } if (!$upper && $this->$property !== 0) { throw new RuntimeException( "You cannot set $unit to a float value as $name would be overridden, ". 'set it first to 0 explicitly if you really want to erase its value' ); } } $this->add($unit, $floatValue - $base); } } private function getInnerValues(): array { return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days]; } private function checkStartAndEnd(): void { if ( $this->initialValues !== null && ($this->startDate !== null || $this->endDate !== null) && $this->initialValues !== $this->getInnerValues() ) { $this->absolute = false; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; } } /** @return $this */ private function setSetting(string $setting, mixed $value): self { switch ($setting) { case 'timezoneSetting': return $value === null ? $this : $this->setTimezone($value); case 'step': $this->setStep($value); return $this; case 'localMonthsOverflow': return $value === null ? $this : $this->settings(['monthOverflow' => $value]); case 'localYearsOverflow': return $value === null ? $this : $this->settings(['yearOverflow' => $value]); case 'localStrictModeEnabled': case 'localHumanDiffOptions': case 'localToStringFormat': case 'localSerializer': case 'localMacros': case 'localGenericMacros': case 'localFormatFunction': case 'localTranslator': $this->$setting = $value; return $this; default: // Drop unknown settings return $this; } } private static function incrementUnit(DateInterval $instance, string $unit, int $value): void { if ($value === 0) { return; } // @codeCoverageIgnoreStart if (PHP_VERSION_ID !== 8_03_20) { $instance->$unit += $value; return; } // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value); // @codeCoverageIgnoreEnd } /** @codeCoverageIgnore */ private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void { switch ($unit) { case 'y': $instance->y = $value; break; case 'm': $instance->m = $value; break; case 'd': $instance->d = $value; break; case 'h': $instance->h = $value; break; case 'i': $instance->i = $value; break; case 's': $instance->s = $value; break; default: $instance->$unit = $value; } } }
PHP
{ "end_line": 1132, "name": "diff", "signature": "public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static", "start_line": 1118 }
{ "class_name": "CarbonInterval", "class_signature": "class CarbonInterval implements CarbonConverterInterface, UnitValue", "namespace": "Carbon" }
make
Carbon/src/Carbon/CarbonInterval.php
public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH], 'day' => ['week' => Carbon::DAYS_PER_WEEK], 'hour' => ['day' => Carbon::HOURS_PER_DAY], 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], ]; return $defaults[$source][$target] ?? null; } /** * Returns current config for days per week. * * @return int|float */ public static function getDaysPerWeek() { return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; } /** * Returns current config for hours per day. * * @return int|float */ public static function getHoursPerDay() { return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; } /** * Returns current config for minutes per hour. * * @return int|float */ public static function getMinutesPerHour() { return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; } /** * Returns current config for seconds per minute. * * @return int|float */ public static function getSecondsPerMinute() { return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMillisecondsPerSecond() { return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMicrosecondsPerMillisecond() { return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; } /** * Create a new CarbonInterval instance from specific values. * This is an alias for the constructor that allows better fluent * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than * (new CarbonInterval(1))->fn(). * * @param int $years * @param int $months * @param int $weeks * @param int $days * @param int $hours * @param int $minutes * @param int $seconds * @param int $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. * * @return static */ public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); } /** * Parse a string into a new CarbonInterval object according to the specified format. * * @example * ``` * echo Carboninterval::createFromFormat('H:i', '1:30'); * ``` * * @param string $format Format of the $interval input string * @param string|null $interval Input string to convert into an interval * * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. * * @return static */ public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; } /** * Return the original source used to create the current interval. * * @return array|int|string|DateInterval|mixed|null */ public function original() { return $this->originalInput; } /** * Return the start date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function start(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->startDate; } /** * Return the end date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function end(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->endDate; } /** * Get rid of the original input, start date and end date that may be kept in memory. * * @return $this */ public function optimize(): static { $this->originalInput = null; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; $this->absolute = false; return $this; } /** * Get a copy of the instance. * * @return static */ public function copy(): static { $date = new static(0); $date->copyProperties($this); $date->step = $this->step; return $date; } /** * Get a copy of the instance. * * @return static */ public function clone(): static { return $this->copy(); } /** * Provide static helpers to create instances. Allows CarbonInterval::years(3). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @return static|mixed|null */ public static function __callStatic(string $method, array $parameters) { try { $interval = new static(0); $localStrictModeEnabled = $interval->localStrictModeEnabled; $interval->localStrictModeEnabled = true; $result = static::hasMacro($method) ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { return $interval->callMacro($method, $parameters); }) : $interval->$method(...$parameters); $interval->localStrictModeEnabled = $localStrictModeEnabled; return $result; } catch (BadFluentSetterException $exception) { if (Carbon::isStrictModeEnabled()) { throw new BadFluentConstructorException($method, 0, $exception); } return null; } } /** * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. * * @param array $dump data as exported by var_export() * * @return static */ #[ReturnTypeWillChange] public static function __set_state($dump) { /** @noinspection PhpVoidFunctionResultUsedInspection */ /** @var DateInterval $dateInterval */ $dateInterval = parent::__set_state($dump); return static::instance($dateInterval); } /** * Return the current context from inside a macro callee or a new one if static. * * @return static */ protected static function this(): static { return end(static::$macroContextStack) ?: new static(0); } /** * Creates a CarbonInterval from string. * * Format: * * Suffix | Unit | Example | DateInterval expression * -------|---------|---------|------------------------ * y | years | 1y | P1Y * mo | months | 3mo | P3M * w | weeks | 2w | P2W * d | days | 28d | P28D * h | hours | 4h | PT4H * m | minutes | 12m | PT12M * s | seconds | 59s | PT59S * * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. * * Special cases: * - An empty string will return a zero interval * - Fractions are allowed for weeks, days, hours and minutes and will be converted * and rounded to the next smaller value (caution: 0.5w = 4d) * * @param string $intervalDefinition * * @throws InvalidIntervalException * * @return static */ public static function fromString(string $intervalDefinition): static { if (empty($intervalDefinition)) { return self::withOriginal(new static(0), $intervalDefinition); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $milliseconds = 0; $microseconds = 0; $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ([$part, $value, $unit] = array_shift($parts)) { $intValue = (int) $value; $fraction = (float) $value - $intValue; // Fix calculation precision switch (round($fraction, 6)) { case 1: $fraction = 0; $intValue++; break; case 0: $fraction = 0; break; } switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { case 'millennia': case 'millennium': $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; break; case 'century': case 'centuries': $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; break; case 'decade': case 'decades': $years += $intValue * CarbonInterface::YEARS_PER_DECADE; break; case 'year': case 'years': case 'y': case 'yr': case 'yrs': $years += $intValue; break; case 'quarter': case 'quarters': $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; break; case 'month': case 'months': case 'mo': case 'mos': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; } break; case 'second': case 'seconds': case 's': $seconds += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; } break; case 'millisecond': case 'milliseconds': case 'milli': case 'ms': $milliseconds += $intValue; if ($fraction) { $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); } break; case 'microsecond': case 'microseconds': case 'micro': case 'µs': $microseconds += $intValue; break; default: throw new InvalidIntervalException( "Invalid part $part in definition $intervalDefinition", ); } } return self::withOriginal( new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds), $intervalDefinition, ); } /** * Creates a CarbonInterval from string using a different locale. * * @param string $interval interval string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be used instead. * * @return static */ public static function parseFromLocale(string $interval, ?string $locale = null): static { return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE)); } /** * Create an interval from the difference between 2 dates. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $start * @param \Carbon\Carbon|\DateTimeInterface|mixed $end * * @return static */ public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; } /** * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function abs(bool $absolute = false): static { if ($absolute && $this->invert) { $this->invert(); } return $this; } /** * @alias abs * * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function absolute(bool $absolute = true): static { return $this->abs($absolute); } /** * Cast the current instance into the given class. * * @template T of DateInterval * * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { return self::castIntervalToClass($this, $className); } /** * Create a CarbonInterval instance from a DateInterval one. Can not instance * DateInterval objects created from DateTime::diff() as you can't externally * set the $days field. * * @param DateInterval $interval * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static */ public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static { if ($skipCopy && $interval instanceof static) { return $interval; } return self::castIntervalToClass($interval, static::class, $skip); } /** * Make a CarbonInterval instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static|null */ public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); } protected static function makeFromString(string $interval): ?self { $interval = preg_replace('/\s+/', ' ', trim($interval)); if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { return static::fromString($interval); } $intervalInstance = static::createFromDateString($interval); return $intervalInstance->isEmpty() ? null : $intervalInstance; } protected function resolveInterval($interval): ?self { if (!($interval instanceof self)) { return self::make($interval); } return $interval; } /** * Sets up a DateInterval from the relative parts of the string. * * @param string $datetime * * @return static * * @link https://php.net/manual/en/dateinterval.createfromdatestring.php */ public static function createFromDateString(string $datetime): static { $string = strtr($datetime, [ ',' => ' ', ' and ' => ' ', ]); $previousException = null; try { $interval = parent::createFromDateString($string); } catch (Throwable $exception) { $interval = null; $previousException = $exception; } $interval ?: throw new InvalidFormatException( 'Could not create interval from: '.var_export($datetime, true), previous: $previousException, ); if (!($interval instanceof static)) { $interval = static::instance($interval); } return self::withOriginal($interval, $datetime); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the CarbonInterval object. */ public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; } /** * Get a part of the CarbonInterval object. */ public function __get(string $name): int|float|string|null { return $this->get($name); } /** * Set a part of the CarbonInterval object. * * @param Unit|string|array $name * @param int $value * * @throws UnknownSetterException * * @return $this */ public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; } /** * Set a part of the CarbonInterval object. * * @param string $name * @param int $value * * @throws UnknownSetterException */ public function __set(string $name, $value) { $this->set($name, $value); } /** * Allow setting of weeks and days to be cumulative. * * @param int $weeks Number of weeks to set * @param int $days Number of days to set * * @return static */ public function weeksAndDays(int $weeks, int $days): static { $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; return $this; } /** * Returns true if the interval is empty for each unit. * * @return bool */ public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonInterval::macro('twice', function () { * return $this->times(2); * }); * echo CarbonInterval::hours(2)->twice(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonInterval::mixin(new class { * public function daysToHours() { * return function () { * $this->hours += $this->days; * $this->days = 0; * * return $this; * }; * } * public function hoursToDays() { * return function () { * $this->days += $this->hours; * $this->hours = 0; * * return $this; * }; * } * }); * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; * echo CarbonInterval::days(5)->daysToHours() . "\n"; * ``` * * @param object|string $mixin * * @throws ReflectionException * * @return void */ public static function mixin($mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Call given macro. * * @param string $name * @param array $parameters * * @return mixed */ protected function callMacro(string $name, array $parameters) { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadFluentSetterException|Throwable * * @return static|int|float|string */ public function __call(string $method, array $parameters) { if (static::hasMacro($method)) { return static::bindMacroContext($this, function () use (&$method, &$parameters) { return $this->callMacro($method, $parameters); }); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); return $this->{$match['method']}($value, $match['unit']); } $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); try { $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); } } return $this; } protected function getForHumansInitialVariables($syntax, $short): array { if (\is_array($syntax)) { return $syntax; } if (\is_int($short)) { return [ 'parts' => $short, 'short' => false, ]; } if (\is_bool($syntax)) { return [ 'short' => $syntax, 'syntax' => CarbonInterface::DIFF_ABSOLUTE, ]; } return []; } /** * @param mixed $syntax * @param mixed $short * @param mixed $parts * @param mixed $options * * @return array */ protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array { $optionalSpace = ' '; $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; /** @var bool|string $join */ $join = $default === '' ? '' : ' '; /** @var bool|array|string $altNumbers */ $altNumbers = false; $aUnit = false; $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); $skip = array_map( static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit, (array) $skip, ); $skip = array_map( 'strtolower', array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''), ); $syntax ??= CarbonInterface::DIFF_ABSOLUTE; if ($parts === self::NO_LIMIT) { $parts = INF; } $options ??= static::getHumanDiffOptions(); if ($join === false) { $join = ' '; } elseif ($join === true) { $join = [ $default, $this->getTranslationMessage('list.1') ?? $default, ]; } if ($altNumbers && $altNumbers !== true) { $language = new Language($this->locale); $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { [$default, $last] = $join; if ($default !== ' ') { $optionalSpace = ''; } $join = function ($list) use ($default, $last) { if (\count($list) < 2) { return implode('', $list); } $end = array_pop($list); return implode($default, $list).$last.$end; }; } if (\is_string($join)) { if ($join !== ' ') { $optionalSpace = ''; } $glue = $join; $join = static fn ($list) => implode($glue, $list); } $interpolations = [ ':optional-space' => $optionalSpace, ]; $translator ??= isset($locale) ? Translator::get($locale) : null; return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator]; } protected static function getRoundingMethodFromOptions(int $options): ?string { if ($options & CarbonInterface::ROUND) { return 'round'; } if ($options & CarbonInterface::CEIL) { return 'ceil'; } if ($options & CarbonInterface::FLOOR) { return 'floor'; } return null; } /** * Returns interval values as an array where key are the unit names and values the counts. * * @return int[] */ public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; } /** * Returns interval non-zero values as an array where key are the unit names and values the counts. * * @return int[] */ public function getNonZeroValues(): array { return array_filter($this->toArray(), 'intval'); } /** * Returns interval values as an array where key are the unit names and values the counts * from the biggest non-zero one the the smallest non-zero one. * * @return int[] */ public function getValuesSequence(): array { $nonZeroValues = $this->getNonZeroValues(); if ($nonZeroValues === []) { return []; } $keys = array_keys($nonZeroValues); $firstKey = $keys[0]; $lastKey = $keys[\count($keys) - 1]; $values = []; $record = false; foreach ($this->toArray() as $unit => $count) { if ($unit === $firstKey) { $record = true; } if ($record) { $values[$unit] = $count; } if ($unit === $lastKey) { $record = false; } } return $values; } /** * Get the current interval in a human readable format in the current locale. * * @example * ``` * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; * ``` * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: -1: no limits) * @param int $options human diff options * * @throws Exception * * @return string */ public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string { /* @var TranslatorInterface|null $translator */ [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this ->getForHumansParameters($syntax, $short, $parts, $options); $interval = []; $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; $count = 1; $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); $declensionMode = null; $translator ??= $this->getLocalTranslator(); $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); if ($this->needsDeclension($declensionMode, $index, $parts)) { // Some languages have special pluralization for past and future tense. $key = $unit.'_'.$transId; $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); if ($result !== $key) { return $result; } } } $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); if ($result !== $unit) { return $result; } return null; }; $intervalValues = $this; $method = static::getRoundingMethodFromOptions($options); if ($method) { $previousCount = INF; while ( \count($intervalValues->getNonZeroValues()) > $parts && ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 ) { $index = min($count, $previousCount - 1) - 2; if ($index < 0) { break; } $intervalValues = $this->copy()->roundUnit( $keys[$index], 1, $method, ); $previousCount = $count; } } $diffIntervalArray = [ ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], ]; if (!empty($skip)) { foreach ($diffIntervalArray as $index => &$unitData) { $nextIndex = $index + 1; if ($unitData['value'] && isset($diffIntervalArray[$nextIndex]) && \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) ) { $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); $unitData['value'] = 0; } } } $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; } } if (!$absolute) { return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); }; $fallbackUnit = ['second', 's']; foreach ($diffIntervalArray as $diffIntervalData) { if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } // break the loop after we get the required number of parts in array if (\count($interval) >= $parts) { break; } // break the loop after we have reached the minimum unit if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } $actualParts = \count($interval); foreach ($interval as $index => &$item) { $item = $transChoice($item[0], $item[1], $index, $actualParts); } if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; $unit = $fallbackUnit[$short ? 1 : 0]; $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); } // join the interval parts by a space $time = $join($interval); unset($diffIntervalArray, $interval); if ($absolute) { return $time; } $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); if ($parts === 1) { if ($relativeToNow && $unit === 'day') { $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null; if ($specialTranslations && $options & $specialTranslations['option']) { $key = $specialTranslations[$isFuture ? 'future' : 'past']; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } } $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; } $time = [':time' => $time]; return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); } public function format(string $format): string { $output = parent::format($format); if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) { return $output; } $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate); return str_replace('(unknown)', $this->rawInterval->format('%a'), $output); } /** * Format the instance as a string using the forHumans() function. * * @throws Exception * * @return string */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if (!$format) { return $this->forHumans(); } if ($format instanceof Closure) { return $format($this); } return $this->format($format); } /** * Return native DateInterval PHP object matching the current instance. * * @example * ``` * var_dump(CarbonInterval::hours(2)->toDateInterval()); * ``` * * @return DateInterval */ public function toDateInterval(): DateInterval { return self::castIntervalToClass($this, DateInterval::class); } /** * Convert the interval to a CarbonPeriod. * * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. * * @return CarbonPeriod */ public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); } /** * Decompose the current interval into * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); } /** * Invert the interval. * * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this */ public function invert($inverted = null): static { $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; return $this; } protected function solveNegativeInterval(): static { if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { $this->years *= self::NEGATIVE; $this->months *= self::NEGATIVE; $this->dayz *= self::NEGATIVE; $this->hours *= self::NEGATIVE; $this->minutes *= self::NEGATIVE; $this->seconds *= self::NEGATIVE; $this->microseconds *= self::NEGATIVE; $this->invert(); } return $this; } /** * Add the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function sub($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } return $this->add($unit, -(float) $value); } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function subtract($unit, $value = 1): static { return $this->sub($unit, $value); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Multiply current instance given number of times. times() is naive, it multiplies each unit * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded * separately for each unit. * * Use times() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see multiply() * * @param float|int $factor * * @return $this */ public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; } /** * Divide current instance by a given divider. shares() is naive, it divides each unit separately * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours * and 7 minutes. * * Use shares() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see divide() * * @param float|int $divider * * @return $this */ public function shares($divider): static { return $this->times(1 / $divider); } protected function copyProperties(self $interval, $ignoreSign = false): static { $this->years = $interval->years; $this->months = $interval->months; $this->dayz = $interval->dayz; $this->hours = $interval->hours; $this->minutes = $interval->minutes; $this->seconds = $interval->seconds; $this->microseconds = $interval->microseconds; if (!$ignoreSign) { $this->invert = $interval->invert; } return $this; } /** * Multiply and cascade current instance by a given factor. * * @param float|int $factor * * @return $this */ public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); } /** * Divide and cascade current instance by a given divider. * * @param float|int $divider * * @return $this */ public function divide($divider): static { return $this->multiply(1 / $divider); } /** * Get the interval_spec string of a date interval. * * @param DateInterval $interval * * @return string */ public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), static::PERIOD_MONTHS => abs($interval->m), static::PERIOD_DAYS => abs($interval->d), ]); $skip = array_map([Unit::class, 'toNameIfUnit'], $skip); if ( $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) ) { $date = [ static::PERIOD_DAYS => abs($interval->days), ]; } $seconds = abs($interval->s); if ($microseconds && $interval->f > 0) { $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); } $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; foreach ($date as $key => $value) { $specString .= $value.$key; } if (\count($time) > 0) { $specString .= static::PERIOD_TIME_PREFIX; foreach ($time as $key => $value) { $specString .= $value.$key; } } return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; } /** * Get the interval_spec string. * * @return string */ public function spec(bool $microseconds = false): string { return static::getDateIntervalSpec($this, $microseconds); } /** * Comparing 2 date intervals. * * @param DateInterval $first * @param DateInterval $second * * @return int 0, 1 or -1 */ public static function compareDateIntervals(DateInterval $first, DateInterval $second): int { $current = Carbon::now(); $passed = $current->avoidMutation()->add($second); $current->add($first); return $current <=> $passed; } /** * Comparing with passed interval. * * @param DateInterval $interval * * @return int 0, 1 or -1 */ public function compare(DateInterval $interval): int { return static::compareDateIntervals($this, $interval); } /** * Convert overflowed values into bigger units. * * @return $this */ public function cascade(): static { return $this->doCascade(false); } public function hasNegativeValues(): bool { foreach ($this->toArray() as $value) { if ($value < 0) { return true; } } return false; } public function hasPositiveValues(): bool { foreach ($this->toArray() as $value) { if ($value > 0) { return true; } } return false; } /** * Get amount of given unit equivalent to the interval. * * @param string $unit * * @throws UnknownUnitException|UnitNotConfiguredException * * @return float */ public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see equalTo() * * @return bool */ public function eq($interval): bool { return $this->equalTo($interval); } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see notEqualTo() * * @return bool */ public function ne($interval): bool { return $this->notEqualTo($interval); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function notEqualTo($interval): bool { return !$this->eq($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThan() * * @return bool */ public function gt($interval): bool { return $this->greaterThan($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThanOrEqualTo() * * @return bool */ public function gte($interval): bool { return $this->greaterThanOrEqualTo($interval); } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThanOrEqualTo($interval): bool { return $this->greaterThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThan() * * @return bool */ public function lt($interval): bool { return $this->lessThan($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThanOrEqualTo() * * @return bool */ public function lte($interval): bool { return $this->lessThanOrEqualTo($interval); } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThanOrEqualTo($interval): bool { return $this->lessThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function between($interval1, $interval2, bool $equal = true): bool { return $equal ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) : $this->greaterThan($interval1) && $this->lessThan($interval2); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenIncluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenExcluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, false); } /** * Determines if the instance is between two others * * @example * ``` * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function isBetween($interval1, $interval2, bool $equal = true): bool { return $this->between($interval1, $interval2, $equal); } /** * Round the current instance at the given unit with given precision if specified and the given function. * * @throws Exception */ public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); } /** * Truncate the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function floorUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function ceilUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified. * * @param float|int|string|DateInterval|null $precision * @param string $function * * @throws Exception * * @return $this */ public function round($precision = 1, string $function = 'round'): static { return $this->roundWith($precision, $function); } /** * Round the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function floor(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function ceil(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'ceil'); } public function __unserialize(array $data): void { $properties = array_combine( array_map( static fn (mixed $key) => \is_string($key) ? str_replace('tzName', 'timezoneSetting', $key) : $key, array_keys($data), ), $data, ); if (method_exists(parent::class, '__unserialize')) { // PHP >= 8.2 parent::__unserialize($properties); return; } // PHP <= 8.1 // @codeCoverageIgnoreStart $properties = array_combine( array_map( static fn (string $property) => preg_replace('/^\0.+\0/', '', $property), array_keys($data), ), $data, ); $localStrictMode = $this->localStrictModeEnabled; $this->localStrictModeEnabled = false; $days = $properties['days'] ?? false; $this->days = $days === false ? false : (int) $days; $this->y = (int) ($properties['y'] ?? 0); $this->m = (int) ($properties['m'] ?? 0); $this->d = (int) ($properties['d'] ?? 0); $this->h = (int) ($properties['h'] ?? 0); $this->i = (int) ($properties['i'] ?? 0); $this->s = (int) ($properties['s'] ?? 0); $this->f = (float) ($properties['f'] ?? 0.0); // @phpstan-ignore-next-line $this->weekday = (int) ($properties['weekday'] ?? 0); // @phpstan-ignore-next-line $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0); // @phpstan-ignore-next-line $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0); $this->invert = (int) ($properties['invert'] ?? 0); // @phpstan-ignore-next-line $this->special_type = (int) ($properties['special_type'] ?? 0); // @phpstan-ignore-next-line $this->special_amount = (int) ($properties['special_amount'] ?? 0); // @phpstan-ignore-next-line $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0); // @phpstan-ignore-next-line $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0); parent::__construct(self::getDateIntervalSpec($this)); foreach ($properties as $property => $value) { if ($property === 'localStrictModeEnabled') { continue; } $this->$property = $value; } $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode; // @codeCoverageIgnoreEnd } /** * @template T * * @param T $interval * @param mixed $original * * @return T */ private static function withOriginal(mixed $interval, mixed $original): mixed { if ($interval instanceof self) { $interval->originalInput = $original; } return $interval; } private static function standardizeUnit(string $unit): string { $unit = rtrim($unit, 'sz').'s'; return $unit === 'days' ? 'dayz' : $unit; } private static function getFlipCascadeFactors(): array { if (!self::$flipCascadeFactors) { self::$flipCascadeFactors = []; foreach (self::getCascadeFactors() as $to => [$factor, $from]) { self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; } } return self::$flipCascadeFactors; } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object { $mainClass = DateInterval::class; if (!is_a($className, $mainClass, true)) { throw new InvalidCastException("$className is not a sub-class of $mainClass."); } $microseconds = $interval->f; $instance = self::buildInstance($interval, $className, $skip); if ($instance instanceof self) { $instance->originalInput = $interval; } if ($microseconds) { $instance->f = $microseconds; } if ($interval instanceof self && is_a($className, self::class, true)) { self::copyStep($interval, $instance); } self::copyNegativeUnits($interval, $instance); return self::withOriginal($instance, $interval); } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function buildInstance( DateInterval $interval, string $className, array $skip = [], ): object { $serialization = self::buildSerializationString($interval, $className, $skip); return match ($serialization) { null => new $className(static::getDateIntervalSpec($interval, false, $skip)), default => unserialize($serialization), }; } /** * As demonstrated by rlanvin (https://github.com/rlanvin) in * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438 * * Modifying the output of serialize() to change the class name and unserializing * the tweaked string allows creating new interval instances where the ->days * property can be set. It's not possible neither with `new` nto with `__set_state`. * * It has a non-negligible performance cost, so we'll use this method only if * $interval->days !== false. */ private static function buildSerializationString( DateInterval $interval, string $className, array $skip = [], ): ?string { if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) { return null; } // De-enhance CarbonInterval objects to be serializable back to DateInterval if ($interval instanceof self && !is_a($className, self::class, true)) { $interval = clone $interval; unset($interval->timezoneSetting); unset($interval->originalInput); unset($interval->startDate); unset($interval->endDate); unset($interval->rawInterval); unset($interval->absolute); unset($interval->initialValues); unset($interval->clock); unset($interval->step); unset($interval->localMonthsOverflow); unset($interval->localYearsOverflow); unset($interval->localStrictModeEnabled); unset($interval->localHumanDiffOptions); unset($interval->localToStringFormat); unset($interval->localSerializer); unset($interval->localMacros); unset($interval->localGenericMacros); unset($interval->localFormatFunction); unset($interval->localTranslator); } $serialization = serialize($interval); $inputClass = $interval::class; $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":'; if (!str_starts_with($serialization, $expectedStart)) { return null; // @codeCoverageIgnore } return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart)); } private static function copyStep(self $from, self $to): void { $to->setStep($from->getStep()); } private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void { $to->invert = $from->invert; foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { if ($from->$unit < 0) { self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE); } } } private function invertCascade(array $values): static { return $this->set(array_map(function ($value) { return -$value; }, $values))->doCascade(true)->invert(); } private function doCascade(bool $deep): static { $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { if ($$key === 'dayz') { $$key = 'daysExcludeWeeks'; } } $value = $newData[$source]; $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; $decimalPart = fmod($newData[$source], 1); if ($decimalPart !== 0.0) { $unit = $source; foreach ($previous as [$subUnit, $subFactor]) { $newData[$unit] -= $decimalPart; $newData[$subUnit] += $decimalPart * $subFactor; $decimalPart = fmod($newData[$subUnit], 1); if ($decimalPart === 0.0) { break; } $unit = $subUnit; } } array_unshift($previous, [$source, $factor]); } $positive = null; if (!$deep) { foreach ($newData as $value) { if ($value) { if ($positive === null) { $positive = ($value > 0); continue; } if (($value > 0) !== $positive) { return $this->invertCascade($originalData) ->solveNegativeInterval(); } } } } return $this->set($newData) ->solveNegativeInterval(); } private function needsDeclension(string $mode, int $index, int $parts): bool { return match ($mode) { 'last' => $index === $parts - 1, default => true, }; } private function checkIntegerValue(string $name, mixed $value): void { if (\is_int($value)) { return; } $this->assertSafeForInteger($name, $value); if (\is_float($value) && (((float) (int) $value) === $value)) { return; } if (!self::$floatSettersEnabled) { $type = \gettype($value); @trigger_error( "Since 2.70.0, it's deprecated to pass $type value for $name.\n". "It's truncated when stored as an integer interval unit.\n". "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", \E_USER_DEPRECATED, ); } } /** * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. */ private function assertSafeForInteger(string $name, mixed $value): void { if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); } } private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void { if (self::$floatSettersEnabled) { $floatValue = (float) $value; $base = (float) $integerValue; if ($floatValue === $base) { return; } $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; $upper = true; foreach ($units as $property => $name) { if ($name === $unit) { $upper = false; continue; } if (!$upper && $this->$property !== 0) { throw new RuntimeException( "You cannot set $unit to a float value as $name would be overridden, ". 'set it first to 0 explicitly if you really want to erase its value' ); } } $this->add($unit, $floatValue - $base); } } private function getInnerValues(): array { return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days]; } private function checkStartAndEnd(): void { if ( $this->initialValues !== null && ($this->startDate !== null || $this->endDate !== null) && $this->initialValues !== $this->getInnerValues() ) { $this->absolute = false; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; } } /** @return $this */ private function setSetting(string $setting, mixed $value): self { switch ($setting) { case 'timezoneSetting': return $value === null ? $this : $this->setTimezone($value); case 'step': $this->setStep($value); return $this; case 'localMonthsOverflow': return $value === null ? $this : $this->settings(['monthOverflow' => $value]); case 'localYearsOverflow': return $value === null ? $this : $this->settings(['yearOverflow' => $value]); case 'localStrictModeEnabled': case 'localHumanDiffOptions': case 'localToStringFormat': case 'localSerializer': case 'localMacros': case 'localGenericMacros': case 'localFormatFunction': case 'localTranslator': $this->$setting = $value; return $this; default: // Drop unknown settings return $this; } } private static function incrementUnit(DateInterval $instance, string $unit, int $value): void { if ($value === 0) { return; } // @codeCoverageIgnoreStart if (PHP_VERSION_ID !== 8_03_20) { $instance->$unit += $value; return; } // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value); // @codeCoverageIgnoreEnd } /** @codeCoverageIgnore */ private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void { switch ($unit) { case 'y': $instance->y = $value; break; case 'm': $instance->m = $value; break; case 'd': $instance->d = $value; break; case 'h': $instance->h = $value; break; case 'i': $instance->i = $value; break; case 's': $instance->s = $value; break; default: $instance->$unit = $value; } } }
PHP
{ "end_line": 1240, "name": "make", "signature": "public static function make($interval, $unit = null, bool $skipCopy = false): ?self", "start_line": 1213 }
{ "class_name": "CarbonInterval", "class_signature": "class CarbonInterval implements CarbonConverterInterface, UnitValue", "namespace": "Carbon" }
get
Carbon/src/Carbon/CarbonInterval.php
public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH], 'day' => ['week' => Carbon::DAYS_PER_WEEK], 'hour' => ['day' => Carbon::HOURS_PER_DAY], 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], ]; return $defaults[$source][$target] ?? null; } /** * Returns current config for days per week. * * @return int|float */ public static function getDaysPerWeek() { return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; } /** * Returns current config for hours per day. * * @return int|float */ public static function getHoursPerDay() { return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; } /** * Returns current config for minutes per hour. * * @return int|float */ public static function getMinutesPerHour() { return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; } /** * Returns current config for seconds per minute. * * @return int|float */ public static function getSecondsPerMinute() { return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMillisecondsPerSecond() { return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMicrosecondsPerMillisecond() { return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; } /** * Create a new CarbonInterval instance from specific values. * This is an alias for the constructor that allows better fluent * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than * (new CarbonInterval(1))->fn(). * * @param int $years * @param int $months * @param int $weeks * @param int $days * @param int $hours * @param int $minutes * @param int $seconds * @param int $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. * * @return static */ public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); } /** * Parse a string into a new CarbonInterval object according to the specified format. * * @example * ``` * echo Carboninterval::createFromFormat('H:i', '1:30'); * ``` * * @param string $format Format of the $interval input string * @param string|null $interval Input string to convert into an interval * * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. * * @return static */ public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; } /** * Return the original source used to create the current interval. * * @return array|int|string|DateInterval|mixed|null */ public function original() { return $this->originalInput; } /** * Return the start date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function start(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->startDate; } /** * Return the end date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function end(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->endDate; } /** * Get rid of the original input, start date and end date that may be kept in memory. * * @return $this */ public function optimize(): static { $this->originalInput = null; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; $this->absolute = false; return $this; } /** * Get a copy of the instance. * * @return static */ public function copy(): static { $date = new static(0); $date->copyProperties($this); $date->step = $this->step; return $date; } /** * Get a copy of the instance. * * @return static */ public function clone(): static { return $this->copy(); } /** * Provide static helpers to create instances. Allows CarbonInterval::years(3). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @return static|mixed|null */ public static function __callStatic(string $method, array $parameters) { try { $interval = new static(0); $localStrictModeEnabled = $interval->localStrictModeEnabled; $interval->localStrictModeEnabled = true; $result = static::hasMacro($method) ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { return $interval->callMacro($method, $parameters); }) : $interval->$method(...$parameters); $interval->localStrictModeEnabled = $localStrictModeEnabled; return $result; } catch (BadFluentSetterException $exception) { if (Carbon::isStrictModeEnabled()) { throw new BadFluentConstructorException($method, 0, $exception); } return null; } } /** * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. * * @param array $dump data as exported by var_export() * * @return static */ #[ReturnTypeWillChange] public static function __set_state($dump) { /** @noinspection PhpVoidFunctionResultUsedInspection */ /** @var DateInterval $dateInterval */ $dateInterval = parent::__set_state($dump); return static::instance($dateInterval); } /** * Return the current context from inside a macro callee or a new one if static. * * @return static */ protected static function this(): static { return end(static::$macroContextStack) ?: new static(0); } /** * Creates a CarbonInterval from string. * * Format: * * Suffix | Unit | Example | DateInterval expression * -------|---------|---------|------------------------ * y | years | 1y | P1Y * mo | months | 3mo | P3M * w | weeks | 2w | P2W * d | days | 28d | P28D * h | hours | 4h | PT4H * m | minutes | 12m | PT12M * s | seconds | 59s | PT59S * * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. * * Special cases: * - An empty string will return a zero interval * - Fractions are allowed for weeks, days, hours and minutes and will be converted * and rounded to the next smaller value (caution: 0.5w = 4d) * * @param string $intervalDefinition * * @throws InvalidIntervalException * * @return static */ public static function fromString(string $intervalDefinition): static { if (empty($intervalDefinition)) { return self::withOriginal(new static(0), $intervalDefinition); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $milliseconds = 0; $microseconds = 0; $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ([$part, $value, $unit] = array_shift($parts)) { $intValue = (int) $value; $fraction = (float) $value - $intValue; // Fix calculation precision switch (round($fraction, 6)) { case 1: $fraction = 0; $intValue++; break; case 0: $fraction = 0; break; } switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { case 'millennia': case 'millennium': $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; break; case 'century': case 'centuries': $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; break; case 'decade': case 'decades': $years += $intValue * CarbonInterface::YEARS_PER_DECADE; break; case 'year': case 'years': case 'y': case 'yr': case 'yrs': $years += $intValue; break; case 'quarter': case 'quarters': $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; break; case 'month': case 'months': case 'mo': case 'mos': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; } break; case 'second': case 'seconds': case 's': $seconds += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; } break; case 'millisecond': case 'milliseconds': case 'milli': case 'ms': $milliseconds += $intValue; if ($fraction) { $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); } break; case 'microsecond': case 'microseconds': case 'micro': case 'µs': $microseconds += $intValue; break; default: throw new InvalidIntervalException( "Invalid part $part in definition $intervalDefinition", ); } } return self::withOriginal( new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds), $intervalDefinition, ); } /** * Creates a CarbonInterval from string using a different locale. * * @param string $interval interval string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be used instead. * * @return static */ public static function parseFromLocale(string $interval, ?string $locale = null): static { return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE)); } /** * Create an interval from the difference between 2 dates. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $start * @param \Carbon\Carbon|\DateTimeInterface|mixed $end * * @return static */ public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; } /** * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function abs(bool $absolute = false): static { if ($absolute && $this->invert) { $this->invert(); } return $this; } /** * @alias abs * * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function absolute(bool $absolute = true): static { return $this->abs($absolute); } /** * Cast the current instance into the given class. * * @template T of DateInterval * * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { return self::castIntervalToClass($this, $className); } /** * Create a CarbonInterval instance from a DateInterval one. Can not instance * DateInterval objects created from DateTime::diff() as you can't externally * set the $days field. * * @param DateInterval $interval * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static */ public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static { if ($skipCopy && $interval instanceof static) { return $interval; } return self::castIntervalToClass($interval, static::class, $skip); } /** * Make a CarbonInterval instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static|null */ public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); } protected static function makeFromString(string $interval): ?self { $interval = preg_replace('/\s+/', ' ', trim($interval)); if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { return static::fromString($interval); } $intervalInstance = static::createFromDateString($interval); return $intervalInstance->isEmpty() ? null : $intervalInstance; } protected function resolveInterval($interval): ?self { if (!($interval instanceof self)) { return self::make($interval); } return $interval; } /** * Sets up a DateInterval from the relative parts of the string. * * @param string $datetime * * @return static * * @link https://php.net/manual/en/dateinterval.createfromdatestring.php */ public static function createFromDateString(string $datetime): static { $string = strtr($datetime, [ ',' => ' ', ' and ' => ' ', ]); $previousException = null; try { $interval = parent::createFromDateString($string); } catch (Throwable $exception) { $interval = null; $previousException = $exception; } $interval ?: throw new InvalidFormatException( 'Could not create interval from: '.var_export($datetime, true), previous: $previousException, ); if (!($interval instanceof static)) { $interval = static::instance($interval); } return self::withOriginal($interval, $datetime); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the CarbonInterval object. */ public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; } /** * Get a part of the CarbonInterval object. */ public function __get(string $name): int|float|string|null { return $this->get($name); } /** * Set a part of the CarbonInterval object. * * @param Unit|string|array $name * @param int $value * * @throws UnknownSetterException * * @return $this */ public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; } /** * Set a part of the CarbonInterval object. * * @param string $name * @param int $value * * @throws UnknownSetterException */ public function __set(string $name, $value) { $this->set($name, $value); } /** * Allow setting of weeks and days to be cumulative. * * @param int $weeks Number of weeks to set * @param int $days Number of days to set * * @return static */ public function weeksAndDays(int $weeks, int $days): static { $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; return $this; } /** * Returns true if the interval is empty for each unit. * * @return bool */ public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonInterval::macro('twice', function () { * return $this->times(2); * }); * echo CarbonInterval::hours(2)->twice(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonInterval::mixin(new class { * public function daysToHours() { * return function () { * $this->hours += $this->days; * $this->days = 0; * * return $this; * }; * } * public function hoursToDays() { * return function () { * $this->days += $this->hours; * $this->hours = 0; * * return $this; * }; * } * }); * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; * echo CarbonInterval::days(5)->daysToHours() . "\n"; * ``` * * @param object|string $mixin * * @throws ReflectionException * * @return void */ public static function mixin($mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Call given macro. * * @param string $name * @param array $parameters * * @return mixed */ protected function callMacro(string $name, array $parameters) { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadFluentSetterException|Throwable * * @return static|int|float|string */ public function __call(string $method, array $parameters) { if (static::hasMacro($method)) { return static::bindMacroContext($this, function () use (&$method, &$parameters) { return $this->callMacro($method, $parameters); }); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); return $this->{$match['method']}($value, $match['unit']); } $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); try { $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); } } return $this; } protected function getForHumansInitialVariables($syntax, $short): array { if (\is_array($syntax)) { return $syntax; } if (\is_int($short)) { return [ 'parts' => $short, 'short' => false, ]; } if (\is_bool($syntax)) { return [ 'short' => $syntax, 'syntax' => CarbonInterface::DIFF_ABSOLUTE, ]; } return []; } /** * @param mixed $syntax * @param mixed $short * @param mixed $parts * @param mixed $options * * @return array */ protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array { $optionalSpace = ' '; $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; /** @var bool|string $join */ $join = $default === '' ? '' : ' '; /** @var bool|array|string $altNumbers */ $altNumbers = false; $aUnit = false; $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); $skip = array_map( static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit, (array) $skip, ); $skip = array_map( 'strtolower', array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''), ); $syntax ??= CarbonInterface::DIFF_ABSOLUTE; if ($parts === self::NO_LIMIT) { $parts = INF; } $options ??= static::getHumanDiffOptions(); if ($join === false) { $join = ' '; } elseif ($join === true) { $join = [ $default, $this->getTranslationMessage('list.1') ?? $default, ]; } if ($altNumbers && $altNumbers !== true) { $language = new Language($this->locale); $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { [$default, $last] = $join; if ($default !== ' ') { $optionalSpace = ''; } $join = function ($list) use ($default, $last) { if (\count($list) < 2) { return implode('', $list); } $end = array_pop($list); return implode($default, $list).$last.$end; }; } if (\is_string($join)) { if ($join !== ' ') { $optionalSpace = ''; } $glue = $join; $join = static fn ($list) => implode($glue, $list); } $interpolations = [ ':optional-space' => $optionalSpace, ]; $translator ??= isset($locale) ? Translator::get($locale) : null; return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator]; } protected static function getRoundingMethodFromOptions(int $options): ?string { if ($options & CarbonInterface::ROUND) { return 'round'; } if ($options & CarbonInterface::CEIL) { return 'ceil'; } if ($options & CarbonInterface::FLOOR) { return 'floor'; } return null; } /** * Returns interval values as an array where key are the unit names and values the counts. * * @return int[] */ public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; } /** * Returns interval non-zero values as an array where key are the unit names and values the counts. * * @return int[] */ public function getNonZeroValues(): array { return array_filter($this->toArray(), 'intval'); } /** * Returns interval values as an array where key are the unit names and values the counts * from the biggest non-zero one the the smallest non-zero one. * * @return int[] */ public function getValuesSequence(): array { $nonZeroValues = $this->getNonZeroValues(); if ($nonZeroValues === []) { return []; } $keys = array_keys($nonZeroValues); $firstKey = $keys[0]; $lastKey = $keys[\count($keys) - 1]; $values = []; $record = false; foreach ($this->toArray() as $unit => $count) { if ($unit === $firstKey) { $record = true; } if ($record) { $values[$unit] = $count; } if ($unit === $lastKey) { $record = false; } } return $values; } /** * Get the current interval in a human readable format in the current locale. * * @example * ``` * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; * ``` * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: -1: no limits) * @param int $options human diff options * * @throws Exception * * @return string */ public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string { /* @var TranslatorInterface|null $translator */ [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this ->getForHumansParameters($syntax, $short, $parts, $options); $interval = []; $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; $count = 1; $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); $declensionMode = null; $translator ??= $this->getLocalTranslator(); $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); if ($this->needsDeclension($declensionMode, $index, $parts)) { // Some languages have special pluralization for past and future tense. $key = $unit.'_'.$transId; $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); if ($result !== $key) { return $result; } } } $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); if ($result !== $unit) { return $result; } return null; }; $intervalValues = $this; $method = static::getRoundingMethodFromOptions($options); if ($method) { $previousCount = INF; while ( \count($intervalValues->getNonZeroValues()) > $parts && ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 ) { $index = min($count, $previousCount - 1) - 2; if ($index < 0) { break; } $intervalValues = $this->copy()->roundUnit( $keys[$index], 1, $method, ); $previousCount = $count; } } $diffIntervalArray = [ ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], ]; if (!empty($skip)) { foreach ($diffIntervalArray as $index => &$unitData) { $nextIndex = $index + 1; if ($unitData['value'] && isset($diffIntervalArray[$nextIndex]) && \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) ) { $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); $unitData['value'] = 0; } } } $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; } } if (!$absolute) { return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); }; $fallbackUnit = ['second', 's']; foreach ($diffIntervalArray as $diffIntervalData) { if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } // break the loop after we get the required number of parts in array if (\count($interval) >= $parts) { break; } // break the loop after we have reached the minimum unit if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } $actualParts = \count($interval); foreach ($interval as $index => &$item) { $item = $transChoice($item[0], $item[1], $index, $actualParts); } if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; $unit = $fallbackUnit[$short ? 1 : 0]; $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); } // join the interval parts by a space $time = $join($interval); unset($diffIntervalArray, $interval); if ($absolute) { return $time; } $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); if ($parts === 1) { if ($relativeToNow && $unit === 'day') { $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null; if ($specialTranslations && $options & $specialTranslations['option']) { $key = $specialTranslations[$isFuture ? 'future' : 'past']; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } } $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; } $time = [':time' => $time]; return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); } public function format(string $format): string { $output = parent::format($format); if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) { return $output; } $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate); return str_replace('(unknown)', $this->rawInterval->format('%a'), $output); } /** * Format the instance as a string using the forHumans() function. * * @throws Exception * * @return string */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if (!$format) { return $this->forHumans(); } if ($format instanceof Closure) { return $format($this); } return $this->format($format); } /** * Return native DateInterval PHP object matching the current instance. * * @example * ``` * var_dump(CarbonInterval::hours(2)->toDateInterval()); * ``` * * @return DateInterval */ public function toDateInterval(): DateInterval { return self::castIntervalToClass($this, DateInterval::class); } /** * Convert the interval to a CarbonPeriod. * * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. * * @return CarbonPeriod */ public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); } /** * Decompose the current interval into * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); } /** * Invert the interval. * * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this */ public function invert($inverted = null): static { $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; return $this; } protected function solveNegativeInterval(): static { if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { $this->years *= self::NEGATIVE; $this->months *= self::NEGATIVE; $this->dayz *= self::NEGATIVE; $this->hours *= self::NEGATIVE; $this->minutes *= self::NEGATIVE; $this->seconds *= self::NEGATIVE; $this->microseconds *= self::NEGATIVE; $this->invert(); } return $this; } /** * Add the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function sub($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } return $this->add($unit, -(float) $value); } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function subtract($unit, $value = 1): static { return $this->sub($unit, $value); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Multiply current instance given number of times. times() is naive, it multiplies each unit * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded * separately for each unit. * * Use times() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see multiply() * * @param float|int $factor * * @return $this */ public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; } /** * Divide current instance by a given divider. shares() is naive, it divides each unit separately * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours * and 7 minutes. * * Use shares() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see divide() * * @param float|int $divider * * @return $this */ public function shares($divider): static { return $this->times(1 / $divider); } protected function copyProperties(self $interval, $ignoreSign = false): static { $this->years = $interval->years; $this->months = $interval->months; $this->dayz = $interval->dayz; $this->hours = $interval->hours; $this->minutes = $interval->minutes; $this->seconds = $interval->seconds; $this->microseconds = $interval->microseconds; if (!$ignoreSign) { $this->invert = $interval->invert; } return $this; } /** * Multiply and cascade current instance by a given factor. * * @param float|int $factor * * @return $this */ public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); } /** * Divide and cascade current instance by a given divider. * * @param float|int $divider * * @return $this */ public function divide($divider): static { return $this->multiply(1 / $divider); } /** * Get the interval_spec string of a date interval. * * @param DateInterval $interval * * @return string */ public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), static::PERIOD_MONTHS => abs($interval->m), static::PERIOD_DAYS => abs($interval->d), ]); $skip = array_map([Unit::class, 'toNameIfUnit'], $skip); if ( $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) ) { $date = [ static::PERIOD_DAYS => abs($interval->days), ]; } $seconds = abs($interval->s); if ($microseconds && $interval->f > 0) { $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); } $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; foreach ($date as $key => $value) { $specString .= $value.$key; } if (\count($time) > 0) { $specString .= static::PERIOD_TIME_PREFIX; foreach ($time as $key => $value) { $specString .= $value.$key; } } return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; } /** * Get the interval_spec string. * * @return string */ public function spec(bool $microseconds = false): string { return static::getDateIntervalSpec($this, $microseconds); } /** * Comparing 2 date intervals. * * @param DateInterval $first * @param DateInterval $second * * @return int 0, 1 or -1 */ public static function compareDateIntervals(DateInterval $first, DateInterval $second): int { $current = Carbon::now(); $passed = $current->avoidMutation()->add($second); $current->add($first); return $current <=> $passed; } /** * Comparing with passed interval. * * @param DateInterval $interval * * @return int 0, 1 or -1 */ public function compare(DateInterval $interval): int { return static::compareDateIntervals($this, $interval); } /** * Convert overflowed values into bigger units. * * @return $this */ public function cascade(): static { return $this->doCascade(false); } public function hasNegativeValues(): bool { foreach ($this->toArray() as $value) { if ($value < 0) { return true; } } return false; } public function hasPositiveValues(): bool { foreach ($this->toArray() as $value) { if ($value > 0) { return true; } } return false; } /** * Get amount of given unit equivalent to the interval. * * @param string $unit * * @throws UnknownUnitException|UnitNotConfiguredException * * @return float */ public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see equalTo() * * @return bool */ public function eq($interval): bool { return $this->equalTo($interval); } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see notEqualTo() * * @return bool */ public function ne($interval): bool { return $this->notEqualTo($interval); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function notEqualTo($interval): bool { return !$this->eq($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThan() * * @return bool */ public function gt($interval): bool { return $this->greaterThan($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThanOrEqualTo() * * @return bool */ public function gte($interval): bool { return $this->greaterThanOrEqualTo($interval); } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThanOrEqualTo($interval): bool { return $this->greaterThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThan() * * @return bool */ public function lt($interval): bool { return $this->lessThan($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThanOrEqualTo() * * @return bool */ public function lte($interval): bool { return $this->lessThanOrEqualTo($interval); } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThanOrEqualTo($interval): bool { return $this->lessThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function between($interval1, $interval2, bool $equal = true): bool { return $equal ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) : $this->greaterThan($interval1) && $this->lessThan($interval2); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenIncluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenExcluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, false); } /** * Determines if the instance is between two others * * @example * ``` * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function isBetween($interval1, $interval2, bool $equal = true): bool { return $this->between($interval1, $interval2, $equal); } /** * Round the current instance at the given unit with given precision if specified and the given function. * * @throws Exception */ public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); } /** * Truncate the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function floorUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function ceilUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified. * * @param float|int|string|DateInterval|null $precision * @param string $function * * @throws Exception * * @return $this */ public function round($precision = 1, string $function = 'round'): static { return $this->roundWith($precision, $function); } /** * Round the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function floor(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function ceil(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'ceil'); } public function __unserialize(array $data): void { $properties = array_combine( array_map( static fn (mixed $key) => \is_string($key) ? str_replace('tzName', 'timezoneSetting', $key) : $key, array_keys($data), ), $data, ); if (method_exists(parent::class, '__unserialize')) { // PHP >= 8.2 parent::__unserialize($properties); return; } // PHP <= 8.1 // @codeCoverageIgnoreStart $properties = array_combine( array_map( static fn (string $property) => preg_replace('/^\0.+\0/', '', $property), array_keys($data), ), $data, ); $localStrictMode = $this->localStrictModeEnabled; $this->localStrictModeEnabled = false; $days = $properties['days'] ?? false; $this->days = $days === false ? false : (int) $days; $this->y = (int) ($properties['y'] ?? 0); $this->m = (int) ($properties['m'] ?? 0); $this->d = (int) ($properties['d'] ?? 0); $this->h = (int) ($properties['h'] ?? 0); $this->i = (int) ($properties['i'] ?? 0); $this->s = (int) ($properties['s'] ?? 0); $this->f = (float) ($properties['f'] ?? 0.0); // @phpstan-ignore-next-line $this->weekday = (int) ($properties['weekday'] ?? 0); // @phpstan-ignore-next-line $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0); // @phpstan-ignore-next-line $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0); $this->invert = (int) ($properties['invert'] ?? 0); // @phpstan-ignore-next-line $this->special_type = (int) ($properties['special_type'] ?? 0); // @phpstan-ignore-next-line $this->special_amount = (int) ($properties['special_amount'] ?? 0); // @phpstan-ignore-next-line $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0); // @phpstan-ignore-next-line $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0); parent::__construct(self::getDateIntervalSpec($this)); foreach ($properties as $property => $value) { if ($property === 'localStrictModeEnabled') { continue; } $this->$property = $value; } $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode; // @codeCoverageIgnoreEnd } /** * @template T * * @param T $interval * @param mixed $original * * @return T */ private static function withOriginal(mixed $interval, mixed $original): mixed { if ($interval instanceof self) { $interval->originalInput = $original; } return $interval; } private static function standardizeUnit(string $unit): string { $unit = rtrim($unit, 'sz').'s'; return $unit === 'days' ? 'dayz' : $unit; } private static function getFlipCascadeFactors(): array { if (!self::$flipCascadeFactors) { self::$flipCascadeFactors = []; foreach (self::getCascadeFactors() as $to => [$factor, $from]) { self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; } } return self::$flipCascadeFactors; } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object { $mainClass = DateInterval::class; if (!is_a($className, $mainClass, true)) { throw new InvalidCastException("$className is not a sub-class of $mainClass."); } $microseconds = $interval->f; $instance = self::buildInstance($interval, $className, $skip); if ($instance instanceof self) { $instance->originalInput = $interval; } if ($microseconds) { $instance->f = $microseconds; } if ($interval instanceof self && is_a($className, self::class, true)) { self::copyStep($interval, $instance); } self::copyNegativeUnits($interval, $instance); return self::withOriginal($instance, $interval); } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function buildInstance( DateInterval $interval, string $className, array $skip = [], ): object { $serialization = self::buildSerializationString($interval, $className, $skip); return match ($serialization) { null => new $className(static::getDateIntervalSpec($interval, false, $skip)), default => unserialize($serialization), }; } /** * As demonstrated by rlanvin (https://github.com/rlanvin) in * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438 * * Modifying the output of serialize() to change the class name and unserializing * the tweaked string allows creating new interval instances where the ->days * property can be set. It's not possible neither with `new` nto with `__set_state`. * * It has a non-negligible performance cost, so we'll use this method only if * $interval->days !== false. */ private static function buildSerializationString( DateInterval $interval, string $className, array $skip = [], ): ?string { if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) { return null; } // De-enhance CarbonInterval objects to be serializable back to DateInterval if ($interval instanceof self && !is_a($className, self::class, true)) { $interval = clone $interval; unset($interval->timezoneSetting); unset($interval->originalInput); unset($interval->startDate); unset($interval->endDate); unset($interval->rawInterval); unset($interval->absolute); unset($interval->initialValues); unset($interval->clock); unset($interval->step); unset($interval->localMonthsOverflow); unset($interval->localYearsOverflow); unset($interval->localStrictModeEnabled); unset($interval->localHumanDiffOptions); unset($interval->localToStringFormat); unset($interval->localSerializer); unset($interval->localMacros); unset($interval->localGenericMacros); unset($interval->localFormatFunction); unset($interval->localTranslator); } $serialization = serialize($interval); $inputClass = $interval::class; $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":'; if (!str_starts_with($serialization, $expectedStart)) { return null; // @codeCoverageIgnore } return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart)); } private static function copyStep(self $from, self $to): void { $to->setStep($from->getStep()); } private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void { $to->invert = $from->invert; foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { if ($from->$unit < 0) { self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE); } } } private function invertCascade(array $values): static { return $this->set(array_map(function ($value) { return -$value; }, $values))->doCascade(true)->invert(); } private function doCascade(bool $deep): static { $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { if ($$key === 'dayz') { $$key = 'daysExcludeWeeks'; } } $value = $newData[$source]; $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; $decimalPart = fmod($newData[$source], 1); if ($decimalPart !== 0.0) { $unit = $source; foreach ($previous as [$subUnit, $subFactor]) { $newData[$unit] -= $decimalPart; $newData[$subUnit] += $decimalPart * $subFactor; $decimalPart = fmod($newData[$subUnit], 1); if ($decimalPart === 0.0) { break; } $unit = $subUnit; } } array_unshift($previous, [$source, $factor]); } $positive = null; if (!$deep) { foreach ($newData as $value) { if ($value) { if ($positive === null) { $positive = ($value > 0); continue; } if (($value > 0) !== $positive) { return $this->invertCascade($originalData) ->solveNegativeInterval(); } } } } return $this->set($newData) ->solveNegativeInterval(); } private function needsDeclension(string $mode, int $index, int $parts): bool { return match ($mode) { 'last' => $index === $parts - 1, default => true, }; } private function checkIntegerValue(string $name, mixed $value): void { if (\is_int($value)) { return; } $this->assertSafeForInteger($name, $value); if (\is_float($value) && (((float) (int) $value) === $value)) { return; } if (!self::$floatSettersEnabled) { $type = \gettype($value); @trigger_error( "Since 2.70.0, it's deprecated to pass $type value for $name.\n". "It's truncated when stored as an integer interval unit.\n". "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", \E_USER_DEPRECATED, ); } } /** * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. */ private function assertSafeForInteger(string $name, mixed $value): void { if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); } } private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void { if (self::$floatSettersEnabled) { $floatValue = (float) $value; $base = (float) $integerValue; if ($floatValue === $base) { return; } $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; $upper = true; foreach ($units as $property => $name) { if ($name === $unit) { $upper = false; continue; } if (!$upper && $this->$property !== 0) { throw new RuntimeException( "You cannot set $unit to a float value as $name would be overridden, ". 'set it first to 0 explicitly if you really want to erase its value' ); } } $this->add($unit, $floatValue - $base); } } private function getInnerValues(): array { return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days]; } private function checkStartAndEnd(): void { if ( $this->initialValues !== null && ($this->startDate !== null || $this->endDate !== null) && $this->initialValues !== $this->getInnerValues() ) { $this->absolute = false; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; } } /** @return $this */ private function setSetting(string $setting, mixed $value): self { switch ($setting) { case 'timezoneSetting': return $value === null ? $this : $this->setTimezone($value); case 'step': $this->setStep($value); return $this; case 'localMonthsOverflow': return $value === null ? $this : $this->settings(['monthOverflow' => $value]); case 'localYearsOverflow': return $value === null ? $this : $this->settings(['yearOverflow' => $value]); case 'localStrictModeEnabled': case 'localHumanDiffOptions': case 'localToStringFormat': case 'localSerializer': case 'localMacros': case 'localGenericMacros': case 'localFormatFunction': case 'localTranslator': $this->$setting = $value; return $this; default: // Drop unknown settings return $this; } } private static function incrementUnit(DateInterval $instance, string $unit, int $value): void { if ($value === 0) { return; } // @codeCoverageIgnoreStart if (PHP_VERSION_ID !== 8_03_20) { $instance->$unit += $value; return; } // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value); // @codeCoverageIgnoreEnd } /** @codeCoverageIgnore */ private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void { switch ($unit) { case 'y': $instance->y = $value; break; case 'm': $instance->m = $value; break; case 'd': $instance->d = $value; break; case 'h': $instance->h = $value; break; case 'i': $instance->i = $value; break; case 's': $instance->s = $value; break; default: $instance->$unit = $value; } } }
PHP
{ "end_line": 1344, "name": "get", "signature": "public function get(Unit|string $name): int|float|string|null", "start_line": 1311 }
{ "class_name": "CarbonInterval", "class_signature": "class CarbonInterval implements CarbonConverterInterface, UnitValue", "namespace": "Carbon" }
set
Carbon/src/Carbon/CarbonInterval.php
public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH], 'day' => ['week' => Carbon::DAYS_PER_WEEK], 'hour' => ['day' => Carbon::HOURS_PER_DAY], 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], ]; return $defaults[$source][$target] ?? null; } /** * Returns current config for days per week. * * @return int|float */ public static function getDaysPerWeek() { return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; } /** * Returns current config for hours per day. * * @return int|float */ public static function getHoursPerDay() { return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; } /** * Returns current config for minutes per hour. * * @return int|float */ public static function getMinutesPerHour() { return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; } /** * Returns current config for seconds per minute. * * @return int|float */ public static function getSecondsPerMinute() { return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMillisecondsPerSecond() { return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMicrosecondsPerMillisecond() { return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; } /** * Create a new CarbonInterval instance from specific values. * This is an alias for the constructor that allows better fluent * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than * (new CarbonInterval(1))->fn(). * * @param int $years * @param int $months * @param int $weeks * @param int $days * @param int $hours * @param int $minutes * @param int $seconds * @param int $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. * * @return static */ public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); } /** * Parse a string into a new CarbonInterval object according to the specified format. * * @example * ``` * echo Carboninterval::createFromFormat('H:i', '1:30'); * ``` * * @param string $format Format of the $interval input string * @param string|null $interval Input string to convert into an interval * * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. * * @return static */ public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; } /** * Return the original source used to create the current interval. * * @return array|int|string|DateInterval|mixed|null */ public function original() { return $this->originalInput; } /** * Return the start date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function start(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->startDate; } /** * Return the end date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function end(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->endDate; } /** * Get rid of the original input, start date and end date that may be kept in memory. * * @return $this */ public function optimize(): static { $this->originalInput = null; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; $this->absolute = false; return $this; } /** * Get a copy of the instance. * * @return static */ public function copy(): static { $date = new static(0); $date->copyProperties($this); $date->step = $this->step; return $date; } /** * Get a copy of the instance. * * @return static */ public function clone(): static { return $this->copy(); } /** * Provide static helpers to create instances. Allows CarbonInterval::years(3). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @return static|mixed|null */ public static function __callStatic(string $method, array $parameters) { try { $interval = new static(0); $localStrictModeEnabled = $interval->localStrictModeEnabled; $interval->localStrictModeEnabled = true; $result = static::hasMacro($method) ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { return $interval->callMacro($method, $parameters); }) : $interval->$method(...$parameters); $interval->localStrictModeEnabled = $localStrictModeEnabled; return $result; } catch (BadFluentSetterException $exception) { if (Carbon::isStrictModeEnabled()) { throw new BadFluentConstructorException($method, 0, $exception); } return null; } } /** * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. * * @param array $dump data as exported by var_export() * * @return static */ #[ReturnTypeWillChange] public static function __set_state($dump) { /** @noinspection PhpVoidFunctionResultUsedInspection */ /** @var DateInterval $dateInterval */ $dateInterval = parent::__set_state($dump); return static::instance($dateInterval); } /** * Return the current context from inside a macro callee or a new one if static. * * @return static */ protected static function this(): static { return end(static::$macroContextStack) ?: new static(0); } /** * Creates a CarbonInterval from string. * * Format: * * Suffix | Unit | Example | DateInterval expression * -------|---------|---------|------------------------ * y | years | 1y | P1Y * mo | months | 3mo | P3M * w | weeks | 2w | P2W * d | days | 28d | P28D * h | hours | 4h | PT4H * m | minutes | 12m | PT12M * s | seconds | 59s | PT59S * * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. * * Special cases: * - An empty string will return a zero interval * - Fractions are allowed for weeks, days, hours and minutes and will be converted * and rounded to the next smaller value (caution: 0.5w = 4d) * * @param string $intervalDefinition * * @throws InvalidIntervalException * * @return static */ public static function fromString(string $intervalDefinition): static { if (empty($intervalDefinition)) { return self::withOriginal(new static(0), $intervalDefinition); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $milliseconds = 0; $microseconds = 0; $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ([$part, $value, $unit] = array_shift($parts)) { $intValue = (int) $value; $fraction = (float) $value - $intValue; // Fix calculation precision switch (round($fraction, 6)) { case 1: $fraction = 0; $intValue++; break; case 0: $fraction = 0; break; } switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { case 'millennia': case 'millennium': $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; break; case 'century': case 'centuries': $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; break; case 'decade': case 'decades': $years += $intValue * CarbonInterface::YEARS_PER_DECADE; break; case 'year': case 'years': case 'y': case 'yr': case 'yrs': $years += $intValue; break; case 'quarter': case 'quarters': $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; break; case 'month': case 'months': case 'mo': case 'mos': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; } break; case 'second': case 'seconds': case 's': $seconds += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; } break; case 'millisecond': case 'milliseconds': case 'milli': case 'ms': $milliseconds += $intValue; if ($fraction) { $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); } break; case 'microsecond': case 'microseconds': case 'micro': case 'µs': $microseconds += $intValue; break; default: throw new InvalidIntervalException( "Invalid part $part in definition $intervalDefinition", ); } } return self::withOriginal( new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds), $intervalDefinition, ); } /** * Creates a CarbonInterval from string using a different locale. * * @param string $interval interval string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be used instead. * * @return static */ public static function parseFromLocale(string $interval, ?string $locale = null): static { return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE)); } /** * Create an interval from the difference between 2 dates. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $start * @param \Carbon\Carbon|\DateTimeInterface|mixed $end * * @return static */ public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; } /** * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function abs(bool $absolute = false): static { if ($absolute && $this->invert) { $this->invert(); } return $this; } /** * @alias abs * * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function absolute(bool $absolute = true): static { return $this->abs($absolute); } /** * Cast the current instance into the given class. * * @template T of DateInterval * * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { return self::castIntervalToClass($this, $className); } /** * Create a CarbonInterval instance from a DateInterval one. Can not instance * DateInterval objects created from DateTime::diff() as you can't externally * set the $days field. * * @param DateInterval $interval * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static */ public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static { if ($skipCopy && $interval instanceof static) { return $interval; } return self::castIntervalToClass($interval, static::class, $skip); } /** * Make a CarbonInterval instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static|null */ public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); } protected static function makeFromString(string $interval): ?self { $interval = preg_replace('/\s+/', ' ', trim($interval)); if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { return static::fromString($interval); } $intervalInstance = static::createFromDateString($interval); return $intervalInstance->isEmpty() ? null : $intervalInstance; } protected function resolveInterval($interval): ?self { if (!($interval instanceof self)) { return self::make($interval); } return $interval; } /** * Sets up a DateInterval from the relative parts of the string. * * @param string $datetime * * @return static * * @link https://php.net/manual/en/dateinterval.createfromdatestring.php */ public static function createFromDateString(string $datetime): static { $string = strtr($datetime, [ ',' => ' ', ' and ' => ' ', ]); $previousException = null; try { $interval = parent::createFromDateString($string); } catch (Throwable $exception) { $interval = null; $previousException = $exception; } $interval ?: throw new InvalidFormatException( 'Could not create interval from: '.var_export($datetime, true), previous: $previousException, ); if (!($interval instanceof static)) { $interval = static::instance($interval); } return self::withOriginal($interval, $datetime); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the CarbonInterval object. */ public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; } /** * Get a part of the CarbonInterval object. */ public function __get(string $name): int|float|string|null { return $this->get($name); } /** * Set a part of the CarbonInterval object. * * @param Unit|string|array $name * @param int $value * * @throws UnknownSetterException * * @return $this */ public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; } /** * Set a part of the CarbonInterval object. * * @param string $name * @param int $value * * @throws UnknownSetterException */ public function __set(string $name, $value) { $this->set($name, $value); } /** * Allow setting of weeks and days to be cumulative. * * @param int $weeks Number of weeks to set * @param int $days Number of days to set * * @return static */ public function weeksAndDays(int $weeks, int $days): static { $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; return $this; } /** * Returns true if the interval is empty for each unit. * * @return bool */ public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonInterval::macro('twice', function () { * return $this->times(2); * }); * echo CarbonInterval::hours(2)->twice(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonInterval::mixin(new class { * public function daysToHours() { * return function () { * $this->hours += $this->days; * $this->days = 0; * * return $this; * }; * } * public function hoursToDays() { * return function () { * $this->days += $this->hours; * $this->hours = 0; * * return $this; * }; * } * }); * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; * echo CarbonInterval::days(5)->daysToHours() . "\n"; * ``` * * @param object|string $mixin * * @throws ReflectionException * * @return void */ public static function mixin($mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Call given macro. * * @param string $name * @param array $parameters * * @return mixed */ protected function callMacro(string $name, array $parameters) { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadFluentSetterException|Throwable * * @return static|int|float|string */ public function __call(string $method, array $parameters) { if (static::hasMacro($method)) { return static::bindMacroContext($this, function () use (&$method, &$parameters) { return $this->callMacro($method, $parameters); }); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); return $this->{$match['method']}($value, $match['unit']); } $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); try { $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); } } return $this; } protected function getForHumansInitialVariables($syntax, $short): array { if (\is_array($syntax)) { return $syntax; } if (\is_int($short)) { return [ 'parts' => $short, 'short' => false, ]; } if (\is_bool($syntax)) { return [ 'short' => $syntax, 'syntax' => CarbonInterface::DIFF_ABSOLUTE, ]; } return []; } /** * @param mixed $syntax * @param mixed $short * @param mixed $parts * @param mixed $options * * @return array */ protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array { $optionalSpace = ' '; $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; /** @var bool|string $join */ $join = $default === '' ? '' : ' '; /** @var bool|array|string $altNumbers */ $altNumbers = false; $aUnit = false; $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); $skip = array_map( static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit, (array) $skip, ); $skip = array_map( 'strtolower', array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''), ); $syntax ??= CarbonInterface::DIFF_ABSOLUTE; if ($parts === self::NO_LIMIT) { $parts = INF; } $options ??= static::getHumanDiffOptions(); if ($join === false) { $join = ' '; } elseif ($join === true) { $join = [ $default, $this->getTranslationMessage('list.1') ?? $default, ]; } if ($altNumbers && $altNumbers !== true) { $language = new Language($this->locale); $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { [$default, $last] = $join; if ($default !== ' ') { $optionalSpace = ''; } $join = function ($list) use ($default, $last) { if (\count($list) < 2) { return implode('', $list); } $end = array_pop($list); return implode($default, $list).$last.$end; }; } if (\is_string($join)) { if ($join !== ' ') { $optionalSpace = ''; } $glue = $join; $join = static fn ($list) => implode($glue, $list); } $interpolations = [ ':optional-space' => $optionalSpace, ]; $translator ??= isset($locale) ? Translator::get($locale) : null; return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator]; } protected static function getRoundingMethodFromOptions(int $options): ?string { if ($options & CarbonInterface::ROUND) { return 'round'; } if ($options & CarbonInterface::CEIL) { return 'ceil'; } if ($options & CarbonInterface::FLOOR) { return 'floor'; } return null; } /** * Returns interval values as an array where key are the unit names and values the counts. * * @return int[] */ public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; } /** * Returns interval non-zero values as an array where key are the unit names and values the counts. * * @return int[] */ public function getNonZeroValues(): array { return array_filter($this->toArray(), 'intval'); } /** * Returns interval values as an array where key are the unit names and values the counts * from the biggest non-zero one the the smallest non-zero one. * * @return int[] */ public function getValuesSequence(): array { $nonZeroValues = $this->getNonZeroValues(); if ($nonZeroValues === []) { return []; } $keys = array_keys($nonZeroValues); $firstKey = $keys[0]; $lastKey = $keys[\count($keys) - 1]; $values = []; $record = false; foreach ($this->toArray() as $unit => $count) { if ($unit === $firstKey) { $record = true; } if ($record) { $values[$unit] = $count; } if ($unit === $lastKey) { $record = false; } } return $values; } /** * Get the current interval in a human readable format in the current locale. * * @example * ``` * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; * ``` * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: -1: no limits) * @param int $options human diff options * * @throws Exception * * @return string */ public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string { /* @var TranslatorInterface|null $translator */ [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this ->getForHumansParameters($syntax, $short, $parts, $options); $interval = []; $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; $count = 1; $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); $declensionMode = null; $translator ??= $this->getLocalTranslator(); $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); if ($this->needsDeclension($declensionMode, $index, $parts)) { // Some languages have special pluralization for past and future tense. $key = $unit.'_'.$transId; $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); if ($result !== $key) { return $result; } } } $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); if ($result !== $unit) { return $result; } return null; }; $intervalValues = $this; $method = static::getRoundingMethodFromOptions($options); if ($method) { $previousCount = INF; while ( \count($intervalValues->getNonZeroValues()) > $parts && ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 ) { $index = min($count, $previousCount - 1) - 2; if ($index < 0) { break; } $intervalValues = $this->copy()->roundUnit( $keys[$index], 1, $method, ); $previousCount = $count; } } $diffIntervalArray = [ ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], ]; if (!empty($skip)) { foreach ($diffIntervalArray as $index => &$unitData) { $nextIndex = $index + 1; if ($unitData['value'] && isset($diffIntervalArray[$nextIndex]) && \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) ) { $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); $unitData['value'] = 0; } } } $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; } } if (!$absolute) { return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); }; $fallbackUnit = ['second', 's']; foreach ($diffIntervalArray as $diffIntervalData) { if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } // break the loop after we get the required number of parts in array if (\count($interval) >= $parts) { break; } // break the loop after we have reached the minimum unit if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } $actualParts = \count($interval); foreach ($interval as $index => &$item) { $item = $transChoice($item[0], $item[1], $index, $actualParts); } if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; $unit = $fallbackUnit[$short ? 1 : 0]; $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); } // join the interval parts by a space $time = $join($interval); unset($diffIntervalArray, $interval); if ($absolute) { return $time; } $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); if ($parts === 1) { if ($relativeToNow && $unit === 'day') { $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null; if ($specialTranslations && $options & $specialTranslations['option']) { $key = $specialTranslations[$isFuture ? 'future' : 'past']; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } } $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; } $time = [':time' => $time]; return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); } public function format(string $format): string { $output = parent::format($format); if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) { return $output; } $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate); return str_replace('(unknown)', $this->rawInterval->format('%a'), $output); } /** * Format the instance as a string using the forHumans() function. * * @throws Exception * * @return string */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if (!$format) { return $this->forHumans(); } if ($format instanceof Closure) { return $format($this); } return $this->format($format); } /** * Return native DateInterval PHP object matching the current instance. * * @example * ``` * var_dump(CarbonInterval::hours(2)->toDateInterval()); * ``` * * @return DateInterval */ public function toDateInterval(): DateInterval { return self::castIntervalToClass($this, DateInterval::class); } /** * Convert the interval to a CarbonPeriod. * * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. * * @return CarbonPeriod */ public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); } /** * Decompose the current interval into * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); } /** * Invert the interval. * * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this */ public function invert($inverted = null): static { $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; return $this; } protected function solveNegativeInterval(): static { if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { $this->years *= self::NEGATIVE; $this->months *= self::NEGATIVE; $this->dayz *= self::NEGATIVE; $this->hours *= self::NEGATIVE; $this->minutes *= self::NEGATIVE; $this->seconds *= self::NEGATIVE; $this->microseconds *= self::NEGATIVE; $this->invert(); } return $this; } /** * Add the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function sub($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } return $this->add($unit, -(float) $value); } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function subtract($unit, $value = 1): static { return $this->sub($unit, $value); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Multiply current instance given number of times. times() is naive, it multiplies each unit * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded * separately for each unit. * * Use times() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see multiply() * * @param float|int $factor * * @return $this */ public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; } /** * Divide current instance by a given divider. shares() is naive, it divides each unit separately * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours * and 7 minutes. * * Use shares() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see divide() * * @param float|int $divider * * @return $this */ public function shares($divider): static { return $this->times(1 / $divider); } protected function copyProperties(self $interval, $ignoreSign = false): static { $this->years = $interval->years; $this->months = $interval->months; $this->dayz = $interval->dayz; $this->hours = $interval->hours; $this->minutes = $interval->minutes; $this->seconds = $interval->seconds; $this->microseconds = $interval->microseconds; if (!$ignoreSign) { $this->invert = $interval->invert; } return $this; } /** * Multiply and cascade current instance by a given factor. * * @param float|int $factor * * @return $this */ public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); } /** * Divide and cascade current instance by a given divider. * * @param float|int $divider * * @return $this */ public function divide($divider): static { return $this->multiply(1 / $divider); } /** * Get the interval_spec string of a date interval. * * @param DateInterval $interval * * @return string */ public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), static::PERIOD_MONTHS => abs($interval->m), static::PERIOD_DAYS => abs($interval->d), ]); $skip = array_map([Unit::class, 'toNameIfUnit'], $skip); if ( $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) ) { $date = [ static::PERIOD_DAYS => abs($interval->days), ]; } $seconds = abs($interval->s); if ($microseconds && $interval->f > 0) { $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); } $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; foreach ($date as $key => $value) { $specString .= $value.$key; } if (\count($time) > 0) { $specString .= static::PERIOD_TIME_PREFIX; foreach ($time as $key => $value) { $specString .= $value.$key; } } return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; } /** * Get the interval_spec string. * * @return string */ public function spec(bool $microseconds = false): string { return static::getDateIntervalSpec($this, $microseconds); } /** * Comparing 2 date intervals. * * @param DateInterval $first * @param DateInterval $second * * @return int 0, 1 or -1 */ public static function compareDateIntervals(DateInterval $first, DateInterval $second): int { $current = Carbon::now(); $passed = $current->avoidMutation()->add($second); $current->add($first); return $current <=> $passed; } /** * Comparing with passed interval. * * @param DateInterval $interval * * @return int 0, 1 or -1 */ public function compare(DateInterval $interval): int { return static::compareDateIntervals($this, $interval); } /** * Convert overflowed values into bigger units. * * @return $this */ public function cascade(): static { return $this->doCascade(false); } public function hasNegativeValues(): bool { foreach ($this->toArray() as $value) { if ($value < 0) { return true; } } return false; } public function hasPositiveValues(): bool { foreach ($this->toArray() as $value) { if ($value > 0) { return true; } } return false; } /** * Get amount of given unit equivalent to the interval. * * @param string $unit * * @throws UnknownUnitException|UnitNotConfiguredException * * @return float */ public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see equalTo() * * @return bool */ public function eq($interval): bool { return $this->equalTo($interval); } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see notEqualTo() * * @return bool */ public function ne($interval): bool { return $this->notEqualTo($interval); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function notEqualTo($interval): bool { return !$this->eq($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThan() * * @return bool */ public function gt($interval): bool { return $this->greaterThan($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThanOrEqualTo() * * @return bool */ public function gte($interval): bool { return $this->greaterThanOrEqualTo($interval); } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThanOrEqualTo($interval): bool { return $this->greaterThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThan() * * @return bool */ public function lt($interval): bool { return $this->lessThan($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThanOrEqualTo() * * @return bool */ public function lte($interval): bool { return $this->lessThanOrEqualTo($interval); } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThanOrEqualTo($interval): bool { return $this->lessThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function between($interval1, $interval2, bool $equal = true): bool { return $equal ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) : $this->greaterThan($interval1) && $this->lessThan($interval2); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenIncluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenExcluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, false); } /** * Determines if the instance is between two others * * @example * ``` * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function isBetween($interval1, $interval2, bool $equal = true): bool { return $this->between($interval1, $interval2, $equal); } /** * Round the current instance at the given unit with given precision if specified and the given function. * * @throws Exception */ public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); } /** * Truncate the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function floorUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function ceilUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified. * * @param float|int|string|DateInterval|null $precision * @param string $function * * @throws Exception * * @return $this */ public function round($precision = 1, string $function = 'round'): static { return $this->roundWith($precision, $function); } /** * Round the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function floor(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function ceil(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'ceil'); } public function __unserialize(array $data): void { $properties = array_combine( array_map( static fn (mixed $key) => \is_string($key) ? str_replace('tzName', 'timezoneSetting', $key) : $key, array_keys($data), ), $data, ); if (method_exists(parent::class, '__unserialize')) { // PHP >= 8.2 parent::__unserialize($properties); return; } // PHP <= 8.1 // @codeCoverageIgnoreStart $properties = array_combine( array_map( static fn (string $property) => preg_replace('/^\0.+\0/', '', $property), array_keys($data), ), $data, ); $localStrictMode = $this->localStrictModeEnabled; $this->localStrictModeEnabled = false; $days = $properties['days'] ?? false; $this->days = $days === false ? false : (int) $days; $this->y = (int) ($properties['y'] ?? 0); $this->m = (int) ($properties['m'] ?? 0); $this->d = (int) ($properties['d'] ?? 0); $this->h = (int) ($properties['h'] ?? 0); $this->i = (int) ($properties['i'] ?? 0); $this->s = (int) ($properties['s'] ?? 0); $this->f = (float) ($properties['f'] ?? 0.0); // @phpstan-ignore-next-line $this->weekday = (int) ($properties['weekday'] ?? 0); // @phpstan-ignore-next-line $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0); // @phpstan-ignore-next-line $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0); $this->invert = (int) ($properties['invert'] ?? 0); // @phpstan-ignore-next-line $this->special_type = (int) ($properties['special_type'] ?? 0); // @phpstan-ignore-next-line $this->special_amount = (int) ($properties['special_amount'] ?? 0); // @phpstan-ignore-next-line $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0); // @phpstan-ignore-next-line $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0); parent::__construct(self::getDateIntervalSpec($this)); foreach ($properties as $property => $value) { if ($property === 'localStrictModeEnabled') { continue; } $this->$property = $value; } $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode; // @codeCoverageIgnoreEnd } /** * @template T * * @param T $interval * @param mixed $original * * @return T */ private static function withOriginal(mixed $interval, mixed $original): mixed { if ($interval instanceof self) { $interval->originalInput = $original; } return $interval; } private static function standardizeUnit(string $unit): string { $unit = rtrim($unit, 'sz').'s'; return $unit === 'days' ? 'dayz' : $unit; } private static function getFlipCascadeFactors(): array { if (!self::$flipCascadeFactors) { self::$flipCascadeFactors = []; foreach (self::getCascadeFactors() as $to => [$factor, $from]) { self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; } } return self::$flipCascadeFactors; } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object { $mainClass = DateInterval::class; if (!is_a($className, $mainClass, true)) { throw new InvalidCastException("$className is not a sub-class of $mainClass."); } $microseconds = $interval->f; $instance = self::buildInstance($interval, $className, $skip); if ($instance instanceof self) { $instance->originalInput = $interval; } if ($microseconds) { $instance->f = $microseconds; } if ($interval instanceof self && is_a($className, self::class, true)) { self::copyStep($interval, $instance); } self::copyNegativeUnits($interval, $instance); return self::withOriginal($instance, $interval); } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function buildInstance( DateInterval $interval, string $className, array $skip = [], ): object { $serialization = self::buildSerializationString($interval, $className, $skip); return match ($serialization) { null => new $className(static::getDateIntervalSpec($interval, false, $skip)), default => unserialize($serialization), }; } /** * As demonstrated by rlanvin (https://github.com/rlanvin) in * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438 * * Modifying the output of serialize() to change the class name and unserializing * the tweaked string allows creating new interval instances where the ->days * property can be set. It's not possible neither with `new` nto with `__set_state`. * * It has a non-negligible performance cost, so we'll use this method only if * $interval->days !== false. */ private static function buildSerializationString( DateInterval $interval, string $className, array $skip = [], ): ?string { if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) { return null; } // De-enhance CarbonInterval objects to be serializable back to DateInterval if ($interval instanceof self && !is_a($className, self::class, true)) { $interval = clone $interval; unset($interval->timezoneSetting); unset($interval->originalInput); unset($interval->startDate); unset($interval->endDate); unset($interval->rawInterval); unset($interval->absolute); unset($interval->initialValues); unset($interval->clock); unset($interval->step); unset($interval->localMonthsOverflow); unset($interval->localYearsOverflow); unset($interval->localStrictModeEnabled); unset($interval->localHumanDiffOptions); unset($interval->localToStringFormat); unset($interval->localSerializer); unset($interval->localMacros); unset($interval->localGenericMacros); unset($interval->localFormatFunction); unset($interval->localTranslator); } $serialization = serialize($interval); $inputClass = $interval::class; $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":'; if (!str_starts_with($serialization, $expectedStart)) { return null; // @codeCoverageIgnore } return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart)); } private static function copyStep(self $from, self $to): void { $to->setStep($from->getStep()); } private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void { $to->invert = $from->invert; foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { if ($from->$unit < 0) { self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE); } } } private function invertCascade(array $values): static { return $this->set(array_map(function ($value) { return -$value; }, $values))->doCascade(true)->invert(); } private function doCascade(bool $deep): static { $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { if ($$key === 'dayz') { $$key = 'daysExcludeWeeks'; } } $value = $newData[$source]; $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; $decimalPart = fmod($newData[$source], 1); if ($decimalPart !== 0.0) { $unit = $source; foreach ($previous as [$subUnit, $subFactor]) { $newData[$unit] -= $decimalPart; $newData[$subUnit] += $decimalPart * $subFactor; $decimalPart = fmod($newData[$subUnit], 1); if ($decimalPart === 0.0) { break; } $unit = $subUnit; } } array_unshift($previous, [$source, $factor]); } $positive = null; if (!$deep) { foreach ($newData as $value) { if ($value) { if ($positive === null) { $positive = ($value > 0); continue; } if (($value > 0) !== $positive) { return $this->invertCascade($originalData) ->solveNegativeInterval(); } } } } return $this->set($newData) ->solveNegativeInterval(); } private function needsDeclension(string $mode, int $index, int $parts): bool { return match ($mode) { 'last' => $index === $parts - 1, default => true, }; } private function checkIntegerValue(string $name, mixed $value): void { if (\is_int($value)) { return; } $this->assertSafeForInteger($name, $value); if (\is_float($value) && (((float) (int) $value) === $value)) { return; } if (!self::$floatSettersEnabled) { $type = \gettype($value); @trigger_error( "Since 2.70.0, it's deprecated to pass $type value for $name.\n". "It's truncated when stored as an integer interval unit.\n". "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", \E_USER_DEPRECATED, ); } } /** * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. */ private function assertSafeForInteger(string $name, mixed $value): void { if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); } } private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void { if (self::$floatSettersEnabled) { $floatValue = (float) $value; $base = (float) $integerValue; if ($floatValue === $base) { return; } $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; $upper = true; foreach ($units as $property => $name) { if ($name === $unit) { $upper = false; continue; } if (!$upper && $this->$property !== 0) { throw new RuntimeException( "You cannot set $unit to a float value as $name would be overridden, ". 'set it first to 0 explicitly if you really want to erase its value' ); } } $this->add($unit, $floatValue - $base); } } private function getInnerValues(): array { return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days]; } private function checkStartAndEnd(): void { if ( $this->initialValues !== null && ($this->startDate !== null || $this->endDate !== null) && $this->initialValues !== $this->getInnerValues() ) { $this->absolute = false; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; } } /** @return $this */ private function setSetting(string $setting, mixed $value): self { switch ($setting) { case 'timezoneSetting': return $value === null ? $this : $this->setTimezone($value); case 'step': $this->setStep($value); return $this; case 'localMonthsOverflow': return $value === null ? $this : $this->settings(['monthOverflow' => $value]); case 'localYearsOverflow': return $value === null ? $this : $this->settings(['yearOverflow' => $value]); case 'localStrictModeEnabled': case 'localHumanDiffOptions': case 'localToStringFormat': case 'localSerializer': case 'localMacros': case 'localGenericMacros': case 'localFormatFunction': case 'localTranslator': $this->$setting = $value; return $this; default: // Drop unknown settings return $this; } } private static function incrementUnit(DateInterval $instance, string $unit, int $value): void { if ($value === 0) { return; } // @codeCoverageIgnoreStart if (PHP_VERSION_ID !== 8_03_20) { $instance->$unit += $value; return; } // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value); // @codeCoverageIgnoreEnd } /** @codeCoverageIgnore */ private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void { switch ($unit) { case 'y': $instance->y = $value; break; case 'm': $instance->m = $value; break; case 'd': $instance->d = $value; break; case 'h': $instance->h = $value; break; case 'i': $instance->i = $value; break; case 's': $instance->s = $value; break; default: $instance->$unit = $value; } } }
PHP
{ "end_line": 1461, "name": "set", "signature": "public function set($name, $value = null): static", "start_line": 1364 }
{ "class_name": "CarbonInterval", "class_signature": "class CarbonInterval implements CarbonConverterInterface, UnitValue", "namespace": "Carbon" }
isEmpty
Carbon/src/Carbon/CarbonInterval.php
public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH], 'day' => ['week' => Carbon::DAYS_PER_WEEK], 'hour' => ['day' => Carbon::HOURS_PER_DAY], 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], ]; return $defaults[$source][$target] ?? null; } /** * Returns current config for days per week. * * @return int|float */ public static function getDaysPerWeek() { return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; } /** * Returns current config for hours per day. * * @return int|float */ public static function getHoursPerDay() { return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; } /** * Returns current config for minutes per hour. * * @return int|float */ public static function getMinutesPerHour() { return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; } /** * Returns current config for seconds per minute. * * @return int|float */ public static function getSecondsPerMinute() { return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMillisecondsPerSecond() { return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMicrosecondsPerMillisecond() { return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; } /** * Create a new CarbonInterval instance from specific values. * This is an alias for the constructor that allows better fluent * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than * (new CarbonInterval(1))->fn(). * * @param int $years * @param int $months * @param int $weeks * @param int $days * @param int $hours * @param int $minutes * @param int $seconds * @param int $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. * * @return static */ public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); } /** * Parse a string into a new CarbonInterval object according to the specified format. * * @example * ``` * echo Carboninterval::createFromFormat('H:i', '1:30'); * ``` * * @param string $format Format of the $interval input string * @param string|null $interval Input string to convert into an interval * * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. * * @return static */ public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; } /** * Return the original source used to create the current interval. * * @return array|int|string|DateInterval|mixed|null */ public function original() { return $this->originalInput; } /** * Return the start date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function start(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->startDate; } /** * Return the end date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function end(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->endDate; } /** * Get rid of the original input, start date and end date that may be kept in memory. * * @return $this */ public function optimize(): static { $this->originalInput = null; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; $this->absolute = false; return $this; } /** * Get a copy of the instance. * * @return static */ public function copy(): static { $date = new static(0); $date->copyProperties($this); $date->step = $this->step; return $date; } /** * Get a copy of the instance. * * @return static */ public function clone(): static { return $this->copy(); } /** * Provide static helpers to create instances. Allows CarbonInterval::years(3). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @return static|mixed|null */ public static function __callStatic(string $method, array $parameters) { try { $interval = new static(0); $localStrictModeEnabled = $interval->localStrictModeEnabled; $interval->localStrictModeEnabled = true; $result = static::hasMacro($method) ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { return $interval->callMacro($method, $parameters); }) : $interval->$method(...$parameters); $interval->localStrictModeEnabled = $localStrictModeEnabled; return $result; } catch (BadFluentSetterException $exception) { if (Carbon::isStrictModeEnabled()) { throw new BadFluentConstructorException($method, 0, $exception); } return null; } } /** * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. * * @param array $dump data as exported by var_export() * * @return static */ #[ReturnTypeWillChange] public static function __set_state($dump) { /** @noinspection PhpVoidFunctionResultUsedInspection */ /** @var DateInterval $dateInterval */ $dateInterval = parent::__set_state($dump); return static::instance($dateInterval); } /** * Return the current context from inside a macro callee or a new one if static. * * @return static */ protected static function this(): static { return end(static::$macroContextStack) ?: new static(0); } /** * Creates a CarbonInterval from string. * * Format: * * Suffix | Unit | Example | DateInterval expression * -------|---------|---------|------------------------ * y | years | 1y | P1Y * mo | months | 3mo | P3M * w | weeks | 2w | P2W * d | days | 28d | P28D * h | hours | 4h | PT4H * m | minutes | 12m | PT12M * s | seconds | 59s | PT59S * * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. * * Special cases: * - An empty string will return a zero interval * - Fractions are allowed for weeks, days, hours and minutes and will be converted * and rounded to the next smaller value (caution: 0.5w = 4d) * * @param string $intervalDefinition * * @throws InvalidIntervalException * * @return static */ public static function fromString(string $intervalDefinition): static { if (empty($intervalDefinition)) { return self::withOriginal(new static(0), $intervalDefinition); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $milliseconds = 0; $microseconds = 0; $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ([$part, $value, $unit] = array_shift($parts)) { $intValue = (int) $value; $fraction = (float) $value - $intValue; // Fix calculation precision switch (round($fraction, 6)) { case 1: $fraction = 0; $intValue++; break; case 0: $fraction = 0; break; } switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { case 'millennia': case 'millennium': $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; break; case 'century': case 'centuries': $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; break; case 'decade': case 'decades': $years += $intValue * CarbonInterface::YEARS_PER_DECADE; break; case 'year': case 'years': case 'y': case 'yr': case 'yrs': $years += $intValue; break; case 'quarter': case 'quarters': $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; break; case 'month': case 'months': case 'mo': case 'mos': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; } break; case 'second': case 'seconds': case 's': $seconds += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; } break; case 'millisecond': case 'milliseconds': case 'milli': case 'ms': $milliseconds += $intValue; if ($fraction) { $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); } break; case 'microsecond': case 'microseconds': case 'micro': case 'µs': $microseconds += $intValue; break; default: throw new InvalidIntervalException( "Invalid part $part in definition $intervalDefinition", ); } } return self::withOriginal( new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds), $intervalDefinition, ); } /** * Creates a CarbonInterval from string using a different locale. * * @param string $interval interval string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be used instead. * * @return static */ public static function parseFromLocale(string $interval, ?string $locale = null): static { return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE)); } /** * Create an interval from the difference between 2 dates. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $start * @param \Carbon\Carbon|\DateTimeInterface|mixed $end * * @return static */ public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; } /** * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function abs(bool $absolute = false): static { if ($absolute && $this->invert) { $this->invert(); } return $this; } /** * @alias abs * * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function absolute(bool $absolute = true): static { return $this->abs($absolute); } /** * Cast the current instance into the given class. * * @template T of DateInterval * * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { return self::castIntervalToClass($this, $className); } /** * Create a CarbonInterval instance from a DateInterval one. Can not instance * DateInterval objects created from DateTime::diff() as you can't externally * set the $days field. * * @param DateInterval $interval * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static */ public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static { if ($skipCopy && $interval instanceof static) { return $interval; } return self::castIntervalToClass($interval, static::class, $skip); } /** * Make a CarbonInterval instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static|null */ public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); } protected static function makeFromString(string $interval): ?self { $interval = preg_replace('/\s+/', ' ', trim($interval)); if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { return static::fromString($interval); } $intervalInstance = static::createFromDateString($interval); return $intervalInstance->isEmpty() ? null : $intervalInstance; } protected function resolveInterval($interval): ?self { if (!($interval instanceof self)) { return self::make($interval); } return $interval; } /** * Sets up a DateInterval from the relative parts of the string. * * @param string $datetime * * @return static * * @link https://php.net/manual/en/dateinterval.createfromdatestring.php */ public static function createFromDateString(string $datetime): static { $string = strtr($datetime, [ ',' => ' ', ' and ' => ' ', ]); $previousException = null; try { $interval = parent::createFromDateString($string); } catch (Throwable $exception) { $interval = null; $previousException = $exception; } $interval ?: throw new InvalidFormatException( 'Could not create interval from: '.var_export($datetime, true), previous: $previousException, ); if (!($interval instanceof static)) { $interval = static::instance($interval); } return self::withOriginal($interval, $datetime); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the CarbonInterval object. */ public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; } /** * Get a part of the CarbonInterval object. */ public function __get(string $name): int|float|string|null { return $this->get($name); } /** * Set a part of the CarbonInterval object. * * @param Unit|string|array $name * @param int $value * * @throws UnknownSetterException * * @return $this */ public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; } /** * Set a part of the CarbonInterval object. * * @param string $name * @param int $value * * @throws UnknownSetterException */ public function __set(string $name, $value) { $this->set($name, $value); } /** * Allow setting of weeks and days to be cumulative. * * @param int $weeks Number of weeks to set * @param int $days Number of days to set * * @return static */ public function weeksAndDays(int $weeks, int $days): static { $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; return $this; } /** * Returns true if the interval is empty for each unit. * * @return bool */ public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonInterval::macro('twice', function () { * return $this->times(2); * }); * echo CarbonInterval::hours(2)->twice(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonInterval::mixin(new class { * public function daysToHours() { * return function () { * $this->hours += $this->days; * $this->days = 0; * * return $this; * }; * } * public function hoursToDays() { * return function () { * $this->days += $this->hours; * $this->hours = 0; * * return $this; * }; * } * }); * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; * echo CarbonInterval::days(5)->daysToHours() . "\n"; * ``` * * @param object|string $mixin * * @throws ReflectionException * * @return void */ public static function mixin($mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Call given macro. * * @param string $name * @param array $parameters * * @return mixed */ protected function callMacro(string $name, array $parameters) { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadFluentSetterException|Throwable * * @return static|int|float|string */ public function __call(string $method, array $parameters) { if (static::hasMacro($method)) { return static::bindMacroContext($this, function () use (&$method, &$parameters) { return $this->callMacro($method, $parameters); }); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); return $this->{$match['method']}($value, $match['unit']); } $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); try { $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); } } return $this; } protected function getForHumansInitialVariables($syntax, $short): array { if (\is_array($syntax)) { return $syntax; } if (\is_int($short)) { return [ 'parts' => $short, 'short' => false, ]; } if (\is_bool($syntax)) { return [ 'short' => $syntax, 'syntax' => CarbonInterface::DIFF_ABSOLUTE, ]; } return []; } /** * @param mixed $syntax * @param mixed $short * @param mixed $parts * @param mixed $options * * @return array */ protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array { $optionalSpace = ' '; $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; /** @var bool|string $join */ $join = $default === '' ? '' : ' '; /** @var bool|array|string $altNumbers */ $altNumbers = false; $aUnit = false; $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); $skip = array_map( static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit, (array) $skip, ); $skip = array_map( 'strtolower', array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''), ); $syntax ??= CarbonInterface::DIFF_ABSOLUTE; if ($parts === self::NO_LIMIT) { $parts = INF; } $options ??= static::getHumanDiffOptions(); if ($join === false) { $join = ' '; } elseif ($join === true) { $join = [ $default, $this->getTranslationMessage('list.1') ?? $default, ]; } if ($altNumbers && $altNumbers !== true) { $language = new Language($this->locale); $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { [$default, $last] = $join; if ($default !== ' ') { $optionalSpace = ''; } $join = function ($list) use ($default, $last) { if (\count($list) < 2) { return implode('', $list); } $end = array_pop($list); return implode($default, $list).$last.$end; }; } if (\is_string($join)) { if ($join !== ' ') { $optionalSpace = ''; } $glue = $join; $join = static fn ($list) => implode($glue, $list); } $interpolations = [ ':optional-space' => $optionalSpace, ]; $translator ??= isset($locale) ? Translator::get($locale) : null; return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator]; } protected static function getRoundingMethodFromOptions(int $options): ?string { if ($options & CarbonInterface::ROUND) { return 'round'; } if ($options & CarbonInterface::CEIL) { return 'ceil'; } if ($options & CarbonInterface::FLOOR) { return 'floor'; } return null; } /** * Returns interval values as an array where key are the unit names and values the counts. * * @return int[] */ public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; } /** * Returns interval non-zero values as an array where key are the unit names and values the counts. * * @return int[] */ public function getNonZeroValues(): array { return array_filter($this->toArray(), 'intval'); } /** * Returns interval values as an array where key are the unit names and values the counts * from the biggest non-zero one the the smallest non-zero one. * * @return int[] */ public function getValuesSequence(): array { $nonZeroValues = $this->getNonZeroValues(); if ($nonZeroValues === []) { return []; } $keys = array_keys($nonZeroValues); $firstKey = $keys[0]; $lastKey = $keys[\count($keys) - 1]; $values = []; $record = false; foreach ($this->toArray() as $unit => $count) { if ($unit === $firstKey) { $record = true; } if ($record) { $values[$unit] = $count; } if ($unit === $lastKey) { $record = false; } } return $values; } /** * Get the current interval in a human readable format in the current locale. * * @example * ``` * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; * ``` * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: -1: no limits) * @param int $options human diff options * * @throws Exception * * @return string */ public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string { /* @var TranslatorInterface|null $translator */ [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this ->getForHumansParameters($syntax, $short, $parts, $options); $interval = []; $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; $count = 1; $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); $declensionMode = null; $translator ??= $this->getLocalTranslator(); $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); if ($this->needsDeclension($declensionMode, $index, $parts)) { // Some languages have special pluralization for past and future tense. $key = $unit.'_'.$transId; $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); if ($result !== $key) { return $result; } } } $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); if ($result !== $unit) { return $result; } return null; }; $intervalValues = $this; $method = static::getRoundingMethodFromOptions($options); if ($method) { $previousCount = INF; while ( \count($intervalValues->getNonZeroValues()) > $parts && ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 ) { $index = min($count, $previousCount - 1) - 2; if ($index < 0) { break; } $intervalValues = $this->copy()->roundUnit( $keys[$index], 1, $method, ); $previousCount = $count; } } $diffIntervalArray = [ ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], ]; if (!empty($skip)) { foreach ($diffIntervalArray as $index => &$unitData) { $nextIndex = $index + 1; if ($unitData['value'] && isset($diffIntervalArray[$nextIndex]) && \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) ) { $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); $unitData['value'] = 0; } } } $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; } } if (!$absolute) { return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); }; $fallbackUnit = ['second', 's']; foreach ($diffIntervalArray as $diffIntervalData) { if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } // break the loop after we get the required number of parts in array if (\count($interval) >= $parts) { break; } // break the loop after we have reached the minimum unit if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } $actualParts = \count($interval); foreach ($interval as $index => &$item) { $item = $transChoice($item[0], $item[1], $index, $actualParts); } if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; $unit = $fallbackUnit[$short ? 1 : 0]; $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); } // join the interval parts by a space $time = $join($interval); unset($diffIntervalArray, $interval); if ($absolute) { return $time; } $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); if ($parts === 1) { if ($relativeToNow && $unit === 'day') { $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null; if ($specialTranslations && $options & $specialTranslations['option']) { $key = $specialTranslations[$isFuture ? 'future' : 'past']; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } } $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; } $time = [':time' => $time]; return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); } public function format(string $format): string { $output = parent::format($format); if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) { return $output; } $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate); return str_replace('(unknown)', $this->rawInterval->format('%a'), $output); } /** * Format the instance as a string using the forHumans() function. * * @throws Exception * * @return string */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if (!$format) { return $this->forHumans(); } if ($format instanceof Closure) { return $format($this); } return $this->format($format); } /** * Return native DateInterval PHP object matching the current instance. * * @example * ``` * var_dump(CarbonInterval::hours(2)->toDateInterval()); * ``` * * @return DateInterval */ public function toDateInterval(): DateInterval { return self::castIntervalToClass($this, DateInterval::class); } /** * Convert the interval to a CarbonPeriod. * * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. * * @return CarbonPeriod */ public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); } /** * Decompose the current interval into * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); } /** * Invert the interval. * * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this */ public function invert($inverted = null): static { $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; return $this; } protected function solveNegativeInterval(): static { if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { $this->years *= self::NEGATIVE; $this->months *= self::NEGATIVE; $this->dayz *= self::NEGATIVE; $this->hours *= self::NEGATIVE; $this->minutes *= self::NEGATIVE; $this->seconds *= self::NEGATIVE; $this->microseconds *= self::NEGATIVE; $this->invert(); } return $this; } /** * Add the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function sub($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } return $this->add($unit, -(float) $value); } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function subtract($unit, $value = 1): static { return $this->sub($unit, $value); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Multiply current instance given number of times. times() is naive, it multiplies each unit * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded * separately for each unit. * * Use times() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see multiply() * * @param float|int $factor * * @return $this */ public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; } /** * Divide current instance by a given divider. shares() is naive, it divides each unit separately * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours * and 7 minutes. * * Use shares() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see divide() * * @param float|int $divider * * @return $this */ public function shares($divider): static { return $this->times(1 / $divider); } protected function copyProperties(self $interval, $ignoreSign = false): static { $this->years = $interval->years; $this->months = $interval->months; $this->dayz = $interval->dayz; $this->hours = $interval->hours; $this->minutes = $interval->minutes; $this->seconds = $interval->seconds; $this->microseconds = $interval->microseconds; if (!$ignoreSign) { $this->invert = $interval->invert; } return $this; } /** * Multiply and cascade current instance by a given factor. * * @param float|int $factor * * @return $this */ public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); } /** * Divide and cascade current instance by a given divider. * * @param float|int $divider * * @return $this */ public function divide($divider): static { return $this->multiply(1 / $divider); } /** * Get the interval_spec string of a date interval. * * @param DateInterval $interval * * @return string */ public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), static::PERIOD_MONTHS => abs($interval->m), static::PERIOD_DAYS => abs($interval->d), ]); $skip = array_map([Unit::class, 'toNameIfUnit'], $skip); if ( $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) ) { $date = [ static::PERIOD_DAYS => abs($interval->days), ]; } $seconds = abs($interval->s); if ($microseconds && $interval->f > 0) { $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); } $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; foreach ($date as $key => $value) { $specString .= $value.$key; } if (\count($time) > 0) { $specString .= static::PERIOD_TIME_PREFIX; foreach ($time as $key => $value) { $specString .= $value.$key; } } return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; } /** * Get the interval_spec string. * * @return string */ public function spec(bool $microseconds = false): string { return static::getDateIntervalSpec($this, $microseconds); } /** * Comparing 2 date intervals. * * @param DateInterval $first * @param DateInterval $second * * @return int 0, 1 or -1 */ public static function compareDateIntervals(DateInterval $first, DateInterval $second): int { $current = Carbon::now(); $passed = $current->avoidMutation()->add($second); $current->add($first); return $current <=> $passed; } /** * Comparing with passed interval. * * @param DateInterval $interval * * @return int 0, 1 or -1 */ public function compare(DateInterval $interval): int { return static::compareDateIntervals($this, $interval); } /** * Convert overflowed values into bigger units. * * @return $this */ public function cascade(): static { return $this->doCascade(false); } public function hasNegativeValues(): bool { foreach ($this->toArray() as $value) { if ($value < 0) { return true; } } return false; } public function hasPositiveValues(): bool { foreach ($this->toArray() as $value) { if ($value > 0) { return true; } } return false; } /** * Get amount of given unit equivalent to the interval. * * @param string $unit * * @throws UnknownUnitException|UnitNotConfiguredException * * @return float */ public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see equalTo() * * @return bool */ public function eq($interval): bool { return $this->equalTo($interval); } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see notEqualTo() * * @return bool */ public function ne($interval): bool { return $this->notEqualTo($interval); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function notEqualTo($interval): bool { return !$this->eq($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThan() * * @return bool */ public function gt($interval): bool { return $this->greaterThan($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThanOrEqualTo() * * @return bool */ public function gte($interval): bool { return $this->greaterThanOrEqualTo($interval); } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThanOrEqualTo($interval): bool { return $this->greaterThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThan() * * @return bool */ public function lt($interval): bool { return $this->lessThan($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThanOrEqualTo() * * @return bool */ public function lte($interval): bool { return $this->lessThanOrEqualTo($interval); } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThanOrEqualTo($interval): bool { return $this->lessThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function between($interval1, $interval2, bool $equal = true): bool { return $equal ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) : $this->greaterThan($interval1) && $this->lessThan($interval2); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenIncluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenExcluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, false); } /** * Determines if the instance is between two others * * @example * ``` * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function isBetween($interval1, $interval2, bool $equal = true): bool { return $this->between($interval1, $interval2, $equal); } /** * Round the current instance at the given unit with given precision if specified and the given function. * * @throws Exception */ public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); } /** * Truncate the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function floorUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function ceilUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified. * * @param float|int|string|DateInterval|null $precision * @param string $function * * @throws Exception * * @return $this */ public function round($precision = 1, string $function = 'round'): static { return $this->roundWith($precision, $function); } /** * Round the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function floor(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function ceil(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'ceil'); } public function __unserialize(array $data): void { $properties = array_combine( array_map( static fn (mixed $key) => \is_string($key) ? str_replace('tzName', 'timezoneSetting', $key) : $key, array_keys($data), ), $data, ); if (method_exists(parent::class, '__unserialize')) { // PHP >= 8.2 parent::__unserialize($properties); return; } // PHP <= 8.1 // @codeCoverageIgnoreStart $properties = array_combine( array_map( static fn (string $property) => preg_replace('/^\0.+\0/', '', $property), array_keys($data), ), $data, ); $localStrictMode = $this->localStrictModeEnabled; $this->localStrictModeEnabled = false; $days = $properties['days'] ?? false; $this->days = $days === false ? false : (int) $days; $this->y = (int) ($properties['y'] ?? 0); $this->m = (int) ($properties['m'] ?? 0); $this->d = (int) ($properties['d'] ?? 0); $this->h = (int) ($properties['h'] ?? 0); $this->i = (int) ($properties['i'] ?? 0); $this->s = (int) ($properties['s'] ?? 0); $this->f = (float) ($properties['f'] ?? 0.0); // @phpstan-ignore-next-line $this->weekday = (int) ($properties['weekday'] ?? 0); // @phpstan-ignore-next-line $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0); // @phpstan-ignore-next-line $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0); $this->invert = (int) ($properties['invert'] ?? 0); // @phpstan-ignore-next-line $this->special_type = (int) ($properties['special_type'] ?? 0); // @phpstan-ignore-next-line $this->special_amount = (int) ($properties['special_amount'] ?? 0); // @phpstan-ignore-next-line $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0); // @phpstan-ignore-next-line $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0); parent::__construct(self::getDateIntervalSpec($this)); foreach ($properties as $property => $value) { if ($property === 'localStrictModeEnabled') { continue; } $this->$property = $value; } $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode; // @codeCoverageIgnoreEnd } /** * @template T * * @param T $interval * @param mixed $original * * @return T */ private static function withOriginal(mixed $interval, mixed $original): mixed { if ($interval instanceof self) { $interval->originalInput = $original; } return $interval; } private static function standardizeUnit(string $unit): string { $unit = rtrim($unit, 'sz').'s'; return $unit === 'days' ? 'dayz' : $unit; } private static function getFlipCascadeFactors(): array { if (!self::$flipCascadeFactors) { self::$flipCascadeFactors = []; foreach (self::getCascadeFactors() as $to => [$factor, $from]) { self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; } } return self::$flipCascadeFactors; } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object { $mainClass = DateInterval::class; if (!is_a($className, $mainClass, true)) { throw new InvalidCastException("$className is not a sub-class of $mainClass."); } $microseconds = $interval->f; $instance = self::buildInstance($interval, $className, $skip); if ($instance instanceof self) { $instance->originalInput = $interval; } if ($microseconds) { $instance->f = $microseconds; } if ($interval instanceof self && is_a($className, self::class, true)) { self::copyStep($interval, $instance); } self::copyNegativeUnits($interval, $instance); return self::withOriginal($instance, $interval); } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function buildInstance( DateInterval $interval, string $className, array $skip = [], ): object { $serialization = self::buildSerializationString($interval, $className, $skip); return match ($serialization) { null => new $className(static::getDateIntervalSpec($interval, false, $skip)), default => unserialize($serialization), }; } /** * As demonstrated by rlanvin (https://github.com/rlanvin) in * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438 * * Modifying the output of serialize() to change the class name and unserializing * the tweaked string allows creating new interval instances where the ->days * property can be set. It's not possible neither with `new` nto with `__set_state`. * * It has a non-negligible performance cost, so we'll use this method only if * $interval->days !== false. */ private static function buildSerializationString( DateInterval $interval, string $className, array $skip = [], ): ?string { if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) { return null; } // De-enhance CarbonInterval objects to be serializable back to DateInterval if ($interval instanceof self && !is_a($className, self::class, true)) { $interval = clone $interval; unset($interval->timezoneSetting); unset($interval->originalInput); unset($interval->startDate); unset($interval->endDate); unset($interval->rawInterval); unset($interval->absolute); unset($interval->initialValues); unset($interval->clock); unset($interval->step); unset($interval->localMonthsOverflow); unset($interval->localYearsOverflow); unset($interval->localStrictModeEnabled); unset($interval->localHumanDiffOptions); unset($interval->localToStringFormat); unset($interval->localSerializer); unset($interval->localMacros); unset($interval->localGenericMacros); unset($interval->localFormatFunction); unset($interval->localTranslator); } $serialization = serialize($interval); $inputClass = $interval::class; $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":'; if (!str_starts_with($serialization, $expectedStart)) { return null; // @codeCoverageIgnore } return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart)); } private static function copyStep(self $from, self $to): void { $to->setStep($from->getStep()); } private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void { $to->invert = $from->invert; foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { if ($from->$unit < 0) { self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE); } } } private function invertCascade(array $values): static { return $this->set(array_map(function ($value) { return -$value; }, $values))->doCascade(true)->invert(); } private function doCascade(bool $deep): static { $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { if ($$key === 'dayz') { $$key = 'daysExcludeWeeks'; } } $value = $newData[$source]; $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; $decimalPart = fmod($newData[$source], 1); if ($decimalPart !== 0.0) { $unit = $source; foreach ($previous as [$subUnit, $subFactor]) { $newData[$unit] -= $decimalPart; $newData[$subUnit] += $decimalPart * $subFactor; $decimalPart = fmod($newData[$subUnit], 1); if ($decimalPart === 0.0) { break; } $unit = $subUnit; } } array_unshift($previous, [$source, $factor]); } $positive = null; if (!$deep) { foreach ($newData as $value) { if ($value) { if ($positive === null) { $positive = ($value > 0); continue; } if (($value > 0) !== $positive) { return $this->invertCascade($originalData) ->solveNegativeInterval(); } } } } return $this->set($newData) ->solveNegativeInterval(); } private function needsDeclension(string $mode, int $index, int $parts): bool { return match ($mode) { 'last' => $index === $parts - 1, default => true, }; } private function checkIntegerValue(string $name, mixed $value): void { if (\is_int($value)) { return; } $this->assertSafeForInteger($name, $value); if (\is_float($value) && (((float) (int) $value) === $value)) { return; } if (!self::$floatSettersEnabled) { $type = \gettype($value); @trigger_error( "Since 2.70.0, it's deprecated to pass $type value for $name.\n". "It's truncated when stored as an integer interval unit.\n". "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", \E_USER_DEPRECATED, ); } } /** * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. */ private function assertSafeForInteger(string $name, mixed $value): void { if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); } } private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void { if (self::$floatSettersEnabled) { $floatValue = (float) $value; $base = (float) $integerValue; if ($floatValue === $base) { return; } $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; $upper = true; foreach ($units as $property => $name) { if ($name === $unit) { $upper = false; continue; } if (!$upper && $this->$property !== 0) { throw new RuntimeException( "You cannot set $unit to a float value as $name would be overridden, ". 'set it first to 0 explicitly if you really want to erase its value' ); } } $this->add($unit, $floatValue - $base); } } private function getInnerValues(): array { return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days]; } private function checkStartAndEnd(): void { if ( $this->initialValues !== null && ($this->startDate !== null || $this->endDate !== null) && $this->initialValues !== $this->getInnerValues() ) { $this->absolute = false; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; } } /** @return $this */ private function setSetting(string $setting, mixed $value): self { switch ($setting) { case 'timezoneSetting': return $value === null ? $this : $this->setTimezone($value); case 'step': $this->setStep($value); return $this; case 'localMonthsOverflow': return $value === null ? $this : $this->settings(['monthOverflow' => $value]); case 'localYearsOverflow': return $value === null ? $this : $this->settings(['yearOverflow' => $value]); case 'localStrictModeEnabled': case 'localHumanDiffOptions': case 'localToStringFormat': case 'localSerializer': case 'localMacros': case 'localGenericMacros': case 'localFormatFunction': case 'localTranslator': $this->$setting = $value; return $this; default: // Drop unknown settings return $this; } } private static function incrementUnit(DateInterval $instance, string $unit, int $value): void { if ($value === 0) { return; } // @codeCoverageIgnoreStart if (PHP_VERSION_ID !== 8_03_20) { $instance->$unit += $value; return; } // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value); // @codeCoverageIgnoreEnd } /** @codeCoverageIgnore */ private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void { switch ($unit) { case 'y': $instance->y = $value; break; case 'm': $instance->m = $value; break; case 'd': $instance->d = $value; break; case 'h': $instance->h = $value; break; case 'i': $instance->i = $value; break; case 's': $instance->s = $value; break; default: $instance->$unit = $value; } } }
PHP
{ "end_line": 1506, "name": "isEmpty", "signature": "public function isEmpty(): bool", "start_line": 1496 }
{ "class_name": "CarbonInterval", "class_signature": "class CarbonInterval implements CarbonConverterInterface, UnitValue", "namespace": "Carbon" }
toArray
Carbon/src/Carbon/CarbonInterval.php
public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH], 'day' => ['week' => Carbon::DAYS_PER_WEEK], 'hour' => ['day' => Carbon::HOURS_PER_DAY], 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], ]; return $defaults[$source][$target] ?? null; } /** * Returns current config for days per week. * * @return int|float */ public static function getDaysPerWeek() { return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; } /** * Returns current config for hours per day. * * @return int|float */ public static function getHoursPerDay() { return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; } /** * Returns current config for minutes per hour. * * @return int|float */ public static function getMinutesPerHour() { return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; } /** * Returns current config for seconds per minute. * * @return int|float */ public static function getSecondsPerMinute() { return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMillisecondsPerSecond() { return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMicrosecondsPerMillisecond() { return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; } /** * Create a new CarbonInterval instance from specific values. * This is an alias for the constructor that allows better fluent * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than * (new CarbonInterval(1))->fn(). * * @param int $years * @param int $months * @param int $weeks * @param int $days * @param int $hours * @param int $minutes * @param int $seconds * @param int $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. * * @return static */ public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); } /** * Parse a string into a new CarbonInterval object according to the specified format. * * @example * ``` * echo Carboninterval::createFromFormat('H:i', '1:30'); * ``` * * @param string $format Format of the $interval input string * @param string|null $interval Input string to convert into an interval * * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. * * @return static */ public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; } /** * Return the original source used to create the current interval. * * @return array|int|string|DateInterval|mixed|null */ public function original() { return $this->originalInput; } /** * Return the start date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function start(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->startDate; } /** * Return the end date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function end(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->endDate; } /** * Get rid of the original input, start date and end date that may be kept in memory. * * @return $this */ public function optimize(): static { $this->originalInput = null; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; $this->absolute = false; return $this; } /** * Get a copy of the instance. * * @return static */ public function copy(): static { $date = new static(0); $date->copyProperties($this); $date->step = $this->step; return $date; } /** * Get a copy of the instance. * * @return static */ public function clone(): static { return $this->copy(); } /** * Provide static helpers to create instances. Allows CarbonInterval::years(3). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @return static|mixed|null */ public static function __callStatic(string $method, array $parameters) { try { $interval = new static(0); $localStrictModeEnabled = $interval->localStrictModeEnabled; $interval->localStrictModeEnabled = true; $result = static::hasMacro($method) ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { return $interval->callMacro($method, $parameters); }) : $interval->$method(...$parameters); $interval->localStrictModeEnabled = $localStrictModeEnabled; return $result; } catch (BadFluentSetterException $exception) { if (Carbon::isStrictModeEnabled()) { throw new BadFluentConstructorException($method, 0, $exception); } return null; } } /** * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. * * @param array $dump data as exported by var_export() * * @return static */ #[ReturnTypeWillChange] public static function __set_state($dump) { /** @noinspection PhpVoidFunctionResultUsedInspection */ /** @var DateInterval $dateInterval */ $dateInterval = parent::__set_state($dump); return static::instance($dateInterval); } /** * Return the current context from inside a macro callee or a new one if static. * * @return static */ protected static function this(): static { return end(static::$macroContextStack) ?: new static(0); } /** * Creates a CarbonInterval from string. * * Format: * * Suffix | Unit | Example | DateInterval expression * -------|---------|---------|------------------------ * y | years | 1y | P1Y * mo | months | 3mo | P3M * w | weeks | 2w | P2W * d | days | 28d | P28D * h | hours | 4h | PT4H * m | minutes | 12m | PT12M * s | seconds | 59s | PT59S * * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. * * Special cases: * - An empty string will return a zero interval * - Fractions are allowed for weeks, days, hours and minutes and will be converted * and rounded to the next smaller value (caution: 0.5w = 4d) * * @param string $intervalDefinition * * @throws InvalidIntervalException * * @return static */ public static function fromString(string $intervalDefinition): static { if (empty($intervalDefinition)) { return self::withOriginal(new static(0), $intervalDefinition); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $milliseconds = 0; $microseconds = 0; $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ([$part, $value, $unit] = array_shift($parts)) { $intValue = (int) $value; $fraction = (float) $value - $intValue; // Fix calculation precision switch (round($fraction, 6)) { case 1: $fraction = 0; $intValue++; break; case 0: $fraction = 0; break; } switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { case 'millennia': case 'millennium': $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; break; case 'century': case 'centuries': $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; break; case 'decade': case 'decades': $years += $intValue * CarbonInterface::YEARS_PER_DECADE; break; case 'year': case 'years': case 'y': case 'yr': case 'yrs': $years += $intValue; break; case 'quarter': case 'quarters': $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; break; case 'month': case 'months': case 'mo': case 'mos': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; } break; case 'second': case 'seconds': case 's': $seconds += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; } break; case 'millisecond': case 'milliseconds': case 'milli': case 'ms': $milliseconds += $intValue; if ($fraction) { $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); } break; case 'microsecond': case 'microseconds': case 'micro': case 'µs': $microseconds += $intValue; break; default: throw new InvalidIntervalException( "Invalid part $part in definition $intervalDefinition", ); } } return self::withOriginal( new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds), $intervalDefinition, ); } /** * Creates a CarbonInterval from string using a different locale. * * @param string $interval interval string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be used instead. * * @return static */ public static function parseFromLocale(string $interval, ?string $locale = null): static { return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE)); } /** * Create an interval from the difference between 2 dates. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $start * @param \Carbon\Carbon|\DateTimeInterface|mixed $end * * @return static */ public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; } /** * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function abs(bool $absolute = false): static { if ($absolute && $this->invert) { $this->invert(); } return $this; } /** * @alias abs * * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function absolute(bool $absolute = true): static { return $this->abs($absolute); } /** * Cast the current instance into the given class. * * @template T of DateInterval * * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { return self::castIntervalToClass($this, $className); } /** * Create a CarbonInterval instance from a DateInterval one. Can not instance * DateInterval objects created from DateTime::diff() as you can't externally * set the $days field. * * @param DateInterval $interval * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static */ public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static { if ($skipCopy && $interval instanceof static) { return $interval; } return self::castIntervalToClass($interval, static::class, $skip); } /** * Make a CarbonInterval instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static|null */ public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); } protected static function makeFromString(string $interval): ?self { $interval = preg_replace('/\s+/', ' ', trim($interval)); if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { return static::fromString($interval); } $intervalInstance = static::createFromDateString($interval); return $intervalInstance->isEmpty() ? null : $intervalInstance; } protected function resolveInterval($interval): ?self { if (!($interval instanceof self)) { return self::make($interval); } return $interval; } /** * Sets up a DateInterval from the relative parts of the string. * * @param string $datetime * * @return static * * @link https://php.net/manual/en/dateinterval.createfromdatestring.php */ public static function createFromDateString(string $datetime): static { $string = strtr($datetime, [ ',' => ' ', ' and ' => ' ', ]); $previousException = null; try { $interval = parent::createFromDateString($string); } catch (Throwable $exception) { $interval = null; $previousException = $exception; } $interval ?: throw new InvalidFormatException( 'Could not create interval from: '.var_export($datetime, true), previous: $previousException, ); if (!($interval instanceof static)) { $interval = static::instance($interval); } return self::withOriginal($interval, $datetime); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the CarbonInterval object. */ public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; } /** * Get a part of the CarbonInterval object. */ public function __get(string $name): int|float|string|null { return $this->get($name); } /** * Set a part of the CarbonInterval object. * * @param Unit|string|array $name * @param int $value * * @throws UnknownSetterException * * @return $this */ public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; } /** * Set a part of the CarbonInterval object. * * @param string $name * @param int $value * * @throws UnknownSetterException */ public function __set(string $name, $value) { $this->set($name, $value); } /** * Allow setting of weeks and days to be cumulative. * * @param int $weeks Number of weeks to set * @param int $days Number of days to set * * @return static */ public function weeksAndDays(int $weeks, int $days): static { $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; return $this; } /** * Returns true if the interval is empty for each unit. * * @return bool */ public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonInterval::macro('twice', function () { * return $this->times(2); * }); * echo CarbonInterval::hours(2)->twice(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonInterval::mixin(new class { * public function daysToHours() { * return function () { * $this->hours += $this->days; * $this->days = 0; * * return $this; * }; * } * public function hoursToDays() { * return function () { * $this->days += $this->hours; * $this->hours = 0; * * return $this; * }; * } * }); * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; * echo CarbonInterval::days(5)->daysToHours() . "\n"; * ``` * * @param object|string $mixin * * @throws ReflectionException * * @return void */ public static function mixin($mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Call given macro. * * @param string $name * @param array $parameters * * @return mixed */ protected function callMacro(string $name, array $parameters) { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadFluentSetterException|Throwable * * @return static|int|float|string */ public function __call(string $method, array $parameters) { if (static::hasMacro($method)) { return static::bindMacroContext($this, function () use (&$method, &$parameters) { return $this->callMacro($method, $parameters); }); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); return $this->{$match['method']}($value, $match['unit']); } $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); try { $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); } } return $this; } protected function getForHumansInitialVariables($syntax, $short): array { if (\is_array($syntax)) { return $syntax; } if (\is_int($short)) { return [ 'parts' => $short, 'short' => false, ]; } if (\is_bool($syntax)) { return [ 'short' => $syntax, 'syntax' => CarbonInterface::DIFF_ABSOLUTE, ]; } return []; } /** * @param mixed $syntax * @param mixed $short * @param mixed $parts * @param mixed $options * * @return array */ protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array { $optionalSpace = ' '; $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; /** @var bool|string $join */ $join = $default === '' ? '' : ' '; /** @var bool|array|string $altNumbers */ $altNumbers = false; $aUnit = false; $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); $skip = array_map( static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit, (array) $skip, ); $skip = array_map( 'strtolower', array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''), ); $syntax ??= CarbonInterface::DIFF_ABSOLUTE; if ($parts === self::NO_LIMIT) { $parts = INF; } $options ??= static::getHumanDiffOptions(); if ($join === false) { $join = ' '; } elseif ($join === true) { $join = [ $default, $this->getTranslationMessage('list.1') ?? $default, ]; } if ($altNumbers && $altNumbers !== true) { $language = new Language($this->locale); $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { [$default, $last] = $join; if ($default !== ' ') { $optionalSpace = ''; } $join = function ($list) use ($default, $last) { if (\count($list) < 2) { return implode('', $list); } $end = array_pop($list); return implode($default, $list).$last.$end; }; } if (\is_string($join)) { if ($join !== ' ') { $optionalSpace = ''; } $glue = $join; $join = static fn ($list) => implode($glue, $list); } $interpolations = [ ':optional-space' => $optionalSpace, ]; $translator ??= isset($locale) ? Translator::get($locale) : null; return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator]; } protected static function getRoundingMethodFromOptions(int $options): ?string { if ($options & CarbonInterface::ROUND) { return 'round'; } if ($options & CarbonInterface::CEIL) { return 'ceil'; } if ($options & CarbonInterface::FLOOR) { return 'floor'; } return null; } /** * Returns interval values as an array where key are the unit names and values the counts. * * @return int[] */ public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; } /** * Returns interval non-zero values as an array where key are the unit names and values the counts. * * @return int[] */ public function getNonZeroValues(): array { return array_filter($this->toArray(), 'intval'); } /** * Returns interval values as an array where key are the unit names and values the counts * from the biggest non-zero one the the smallest non-zero one. * * @return int[] */ public function getValuesSequence(): array { $nonZeroValues = $this->getNonZeroValues(); if ($nonZeroValues === []) { return []; } $keys = array_keys($nonZeroValues); $firstKey = $keys[0]; $lastKey = $keys[\count($keys) - 1]; $values = []; $record = false; foreach ($this->toArray() as $unit => $count) { if ($unit === $firstKey) { $record = true; } if ($record) { $values[$unit] = $count; } if ($unit === $lastKey) { $record = false; } } return $values; } /** * Get the current interval in a human readable format in the current locale. * * @example * ``` * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; * ``` * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: -1: no limits) * @param int $options human diff options * * @throws Exception * * @return string */ public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string { /* @var TranslatorInterface|null $translator */ [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this ->getForHumansParameters($syntax, $short, $parts, $options); $interval = []; $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; $count = 1; $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); $declensionMode = null; $translator ??= $this->getLocalTranslator(); $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); if ($this->needsDeclension($declensionMode, $index, $parts)) { // Some languages have special pluralization for past and future tense. $key = $unit.'_'.$transId; $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); if ($result !== $key) { return $result; } } } $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); if ($result !== $unit) { return $result; } return null; }; $intervalValues = $this; $method = static::getRoundingMethodFromOptions($options); if ($method) { $previousCount = INF; while ( \count($intervalValues->getNonZeroValues()) > $parts && ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 ) { $index = min($count, $previousCount - 1) - 2; if ($index < 0) { break; } $intervalValues = $this->copy()->roundUnit( $keys[$index], 1, $method, ); $previousCount = $count; } } $diffIntervalArray = [ ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], ]; if (!empty($skip)) { foreach ($diffIntervalArray as $index => &$unitData) { $nextIndex = $index + 1; if ($unitData['value'] && isset($diffIntervalArray[$nextIndex]) && \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) ) { $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); $unitData['value'] = 0; } } } $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; } } if (!$absolute) { return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); }; $fallbackUnit = ['second', 's']; foreach ($diffIntervalArray as $diffIntervalData) { if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } // break the loop after we get the required number of parts in array if (\count($interval) >= $parts) { break; } // break the loop after we have reached the minimum unit if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } $actualParts = \count($interval); foreach ($interval as $index => &$item) { $item = $transChoice($item[0], $item[1], $index, $actualParts); } if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; $unit = $fallbackUnit[$short ? 1 : 0]; $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); } // join the interval parts by a space $time = $join($interval); unset($diffIntervalArray, $interval); if ($absolute) { return $time; } $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); if ($parts === 1) { if ($relativeToNow && $unit === 'day') { $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null; if ($specialTranslations && $options & $specialTranslations['option']) { $key = $specialTranslations[$isFuture ? 'future' : 'past']; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } } $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; } $time = [':time' => $time]; return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); } public function format(string $format): string { $output = parent::format($format); if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) { return $output; } $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate); return str_replace('(unknown)', $this->rawInterval->format('%a'), $output); } /** * Format the instance as a string using the forHumans() function. * * @throws Exception * * @return string */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if (!$format) { return $this->forHumans(); } if ($format instanceof Closure) { return $format($this); } return $this->format($format); } /** * Return native DateInterval PHP object matching the current instance. * * @example * ``` * var_dump(CarbonInterval::hours(2)->toDateInterval()); * ``` * * @return DateInterval */ public function toDateInterval(): DateInterval { return self::castIntervalToClass($this, DateInterval::class); } /** * Convert the interval to a CarbonPeriod. * * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. * * @return CarbonPeriod */ public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); } /** * Decompose the current interval into * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); } /** * Invert the interval. * * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this */ public function invert($inverted = null): static { $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; return $this; } protected function solveNegativeInterval(): static { if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { $this->years *= self::NEGATIVE; $this->months *= self::NEGATIVE; $this->dayz *= self::NEGATIVE; $this->hours *= self::NEGATIVE; $this->minutes *= self::NEGATIVE; $this->seconds *= self::NEGATIVE; $this->microseconds *= self::NEGATIVE; $this->invert(); } return $this; } /** * Add the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function sub($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } return $this->add($unit, -(float) $value); } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function subtract($unit, $value = 1): static { return $this->sub($unit, $value); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Multiply current instance given number of times. times() is naive, it multiplies each unit * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded * separately for each unit. * * Use times() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see multiply() * * @param float|int $factor * * @return $this */ public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; } /** * Divide current instance by a given divider. shares() is naive, it divides each unit separately * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours * and 7 minutes. * * Use shares() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see divide() * * @param float|int $divider * * @return $this */ public function shares($divider): static { return $this->times(1 / $divider); } protected function copyProperties(self $interval, $ignoreSign = false): static { $this->years = $interval->years; $this->months = $interval->months; $this->dayz = $interval->dayz; $this->hours = $interval->hours; $this->minutes = $interval->minutes; $this->seconds = $interval->seconds; $this->microseconds = $interval->microseconds; if (!$ignoreSign) { $this->invert = $interval->invert; } return $this; } /** * Multiply and cascade current instance by a given factor. * * @param float|int $factor * * @return $this */ public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); } /** * Divide and cascade current instance by a given divider. * * @param float|int $divider * * @return $this */ public function divide($divider): static { return $this->multiply(1 / $divider); } /** * Get the interval_spec string of a date interval. * * @param DateInterval $interval * * @return string */ public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), static::PERIOD_MONTHS => abs($interval->m), static::PERIOD_DAYS => abs($interval->d), ]); $skip = array_map([Unit::class, 'toNameIfUnit'], $skip); if ( $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) ) { $date = [ static::PERIOD_DAYS => abs($interval->days), ]; } $seconds = abs($interval->s); if ($microseconds && $interval->f > 0) { $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); } $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; foreach ($date as $key => $value) { $specString .= $value.$key; } if (\count($time) > 0) { $specString .= static::PERIOD_TIME_PREFIX; foreach ($time as $key => $value) { $specString .= $value.$key; } } return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; } /** * Get the interval_spec string. * * @return string */ public function spec(bool $microseconds = false): string { return static::getDateIntervalSpec($this, $microseconds); } /** * Comparing 2 date intervals. * * @param DateInterval $first * @param DateInterval $second * * @return int 0, 1 or -1 */ public static function compareDateIntervals(DateInterval $first, DateInterval $second): int { $current = Carbon::now(); $passed = $current->avoidMutation()->add($second); $current->add($first); return $current <=> $passed; } /** * Comparing with passed interval. * * @param DateInterval $interval * * @return int 0, 1 or -1 */ public function compare(DateInterval $interval): int { return static::compareDateIntervals($this, $interval); } /** * Convert overflowed values into bigger units. * * @return $this */ public function cascade(): static { return $this->doCascade(false); } public function hasNegativeValues(): bool { foreach ($this->toArray() as $value) { if ($value < 0) { return true; } } return false; } public function hasPositiveValues(): bool { foreach ($this->toArray() as $value) { if ($value > 0) { return true; } } return false; } /** * Get amount of given unit equivalent to the interval. * * @param string $unit * * @throws UnknownUnitException|UnitNotConfiguredException * * @return float */ public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see equalTo() * * @return bool */ public function eq($interval): bool { return $this->equalTo($interval); } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see notEqualTo() * * @return bool */ public function ne($interval): bool { return $this->notEqualTo($interval); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function notEqualTo($interval): bool { return !$this->eq($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThan() * * @return bool */ public function gt($interval): bool { return $this->greaterThan($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThanOrEqualTo() * * @return bool */ public function gte($interval): bool { return $this->greaterThanOrEqualTo($interval); } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThanOrEqualTo($interval): bool { return $this->greaterThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThan() * * @return bool */ public function lt($interval): bool { return $this->lessThan($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThanOrEqualTo() * * @return bool */ public function lte($interval): bool { return $this->lessThanOrEqualTo($interval); } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThanOrEqualTo($interval): bool { return $this->lessThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function between($interval1, $interval2, bool $equal = true): bool { return $equal ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) : $this->greaterThan($interval1) && $this->lessThan($interval2); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenIncluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenExcluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, false); } /** * Determines if the instance is between two others * * @example * ``` * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function isBetween($interval1, $interval2, bool $equal = true): bool { return $this->between($interval1, $interval2, $equal); } /** * Round the current instance at the given unit with given precision if specified and the given function. * * @throws Exception */ public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); } /** * Truncate the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function floorUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function ceilUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified. * * @param float|int|string|DateInterval|null $precision * @param string $function * * @throws Exception * * @return $this */ public function round($precision = 1, string $function = 'round'): static { return $this->roundWith($precision, $function); } /** * Round the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function floor(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function ceil(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'ceil'); } public function __unserialize(array $data): void { $properties = array_combine( array_map( static fn (mixed $key) => \is_string($key) ? str_replace('tzName', 'timezoneSetting', $key) : $key, array_keys($data), ), $data, ); if (method_exists(parent::class, '__unserialize')) { // PHP >= 8.2 parent::__unserialize($properties); return; } // PHP <= 8.1 // @codeCoverageIgnoreStart $properties = array_combine( array_map( static fn (string $property) => preg_replace('/^\0.+\0/', '', $property), array_keys($data), ), $data, ); $localStrictMode = $this->localStrictModeEnabled; $this->localStrictModeEnabled = false; $days = $properties['days'] ?? false; $this->days = $days === false ? false : (int) $days; $this->y = (int) ($properties['y'] ?? 0); $this->m = (int) ($properties['m'] ?? 0); $this->d = (int) ($properties['d'] ?? 0); $this->h = (int) ($properties['h'] ?? 0); $this->i = (int) ($properties['i'] ?? 0); $this->s = (int) ($properties['s'] ?? 0); $this->f = (float) ($properties['f'] ?? 0.0); // @phpstan-ignore-next-line $this->weekday = (int) ($properties['weekday'] ?? 0); // @phpstan-ignore-next-line $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0); // @phpstan-ignore-next-line $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0); $this->invert = (int) ($properties['invert'] ?? 0); // @phpstan-ignore-next-line $this->special_type = (int) ($properties['special_type'] ?? 0); // @phpstan-ignore-next-line $this->special_amount = (int) ($properties['special_amount'] ?? 0); // @phpstan-ignore-next-line $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0); // @phpstan-ignore-next-line $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0); parent::__construct(self::getDateIntervalSpec($this)); foreach ($properties as $property => $value) { if ($property === 'localStrictModeEnabled') { continue; } $this->$property = $value; } $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode; // @codeCoverageIgnoreEnd } /** * @template T * * @param T $interval * @param mixed $original * * @return T */ private static function withOriginal(mixed $interval, mixed $original): mixed { if ($interval instanceof self) { $interval->originalInput = $original; } return $interval; } private static function standardizeUnit(string $unit): string { $unit = rtrim($unit, 'sz').'s'; return $unit === 'days' ? 'dayz' : $unit; } private static function getFlipCascadeFactors(): array { if (!self::$flipCascadeFactors) { self::$flipCascadeFactors = []; foreach (self::getCascadeFactors() as $to => [$factor, $from]) { self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; } } return self::$flipCascadeFactors; } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object { $mainClass = DateInterval::class; if (!is_a($className, $mainClass, true)) { throw new InvalidCastException("$className is not a sub-class of $mainClass."); } $microseconds = $interval->f; $instance = self::buildInstance($interval, $className, $skip); if ($instance instanceof self) { $instance->originalInput = $interval; } if ($microseconds) { $instance->f = $microseconds; } if ($interval instanceof self && is_a($className, self::class, true)) { self::copyStep($interval, $instance); } self::copyNegativeUnits($interval, $instance); return self::withOriginal($instance, $interval); } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function buildInstance( DateInterval $interval, string $className, array $skip = [], ): object { $serialization = self::buildSerializationString($interval, $className, $skip); return match ($serialization) { null => new $className(static::getDateIntervalSpec($interval, false, $skip)), default => unserialize($serialization), }; } /** * As demonstrated by rlanvin (https://github.com/rlanvin) in * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438 * * Modifying the output of serialize() to change the class name and unserializing * the tweaked string allows creating new interval instances where the ->days * property can be set. It's not possible neither with `new` nto with `__set_state`. * * It has a non-negligible performance cost, so we'll use this method only if * $interval->days !== false. */ private static function buildSerializationString( DateInterval $interval, string $className, array $skip = [], ): ?string { if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) { return null; } // De-enhance CarbonInterval objects to be serializable back to DateInterval if ($interval instanceof self && !is_a($className, self::class, true)) { $interval = clone $interval; unset($interval->timezoneSetting); unset($interval->originalInput); unset($interval->startDate); unset($interval->endDate); unset($interval->rawInterval); unset($interval->absolute); unset($interval->initialValues); unset($interval->clock); unset($interval->step); unset($interval->localMonthsOverflow); unset($interval->localYearsOverflow); unset($interval->localStrictModeEnabled); unset($interval->localHumanDiffOptions); unset($interval->localToStringFormat); unset($interval->localSerializer); unset($interval->localMacros); unset($interval->localGenericMacros); unset($interval->localFormatFunction); unset($interval->localTranslator); } $serialization = serialize($interval); $inputClass = $interval::class; $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":'; if (!str_starts_with($serialization, $expectedStart)) { return null; // @codeCoverageIgnore } return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart)); } private static function copyStep(self $from, self $to): void { $to->setStep($from->getStep()); } private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void { $to->invert = $from->invert; foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { if ($from->$unit < 0) { self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE); } } } private function invertCascade(array $values): static { return $this->set(array_map(function ($value) { return -$value; }, $values))->doCascade(true)->invert(); } private function doCascade(bool $deep): static { $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { if ($$key === 'dayz') { $$key = 'daysExcludeWeeks'; } } $value = $newData[$source]; $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; $decimalPart = fmod($newData[$source], 1); if ($decimalPart !== 0.0) { $unit = $source; foreach ($previous as [$subUnit, $subFactor]) { $newData[$unit] -= $decimalPart; $newData[$subUnit] += $decimalPart * $subFactor; $decimalPart = fmod($newData[$subUnit], 1); if ($decimalPart === 0.0) { break; } $unit = $subUnit; } } array_unshift($previous, [$source, $factor]); } $positive = null; if (!$deep) { foreach ($newData as $value) { if ($value) { if ($positive === null) { $positive = ($value > 0); continue; } if (($value > 0) !== $positive) { return $this->invertCascade($originalData) ->solveNegativeInterval(); } } } } return $this->set($newData) ->solveNegativeInterval(); } private function needsDeclension(string $mode, int $index, int $parts): bool { return match ($mode) { 'last' => $index === $parts - 1, default => true, }; } private function checkIntegerValue(string $name, mixed $value): void { if (\is_int($value)) { return; } $this->assertSafeForInteger($name, $value); if (\is_float($value) && (((float) (int) $value) === $value)) { return; } if (!self::$floatSettersEnabled) { $type = \gettype($value); @trigger_error( "Since 2.70.0, it's deprecated to pass $type value for $name.\n". "It's truncated when stored as an integer interval unit.\n". "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", \E_USER_DEPRECATED, ); } } /** * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. */ private function assertSafeForInteger(string $name, mixed $value): void { if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); } } private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void { if (self::$floatSettersEnabled) { $floatValue = (float) $value; $base = (float) $integerValue; if ($floatValue === $base) { return; } $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; $upper = true; foreach ($units as $property => $name) { if ($name === $unit) { $upper = false; continue; } if (!$upper && $this->$property !== 0) { throw new RuntimeException( "You cannot set $unit to a float value as $name would be overridden, ". 'set it first to 0 explicitly if you really want to erase its value' ); } } $this->add($unit, $floatValue - $base); } } private function getInnerValues(): array { return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days]; } private function checkStartAndEnd(): void { if ( $this->initialValues !== null && ($this->startDate !== null || $this->endDate !== null) && $this->initialValues !== $this->getInnerValues() ) { $this->absolute = false; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; } } /** @return $this */ private function setSetting(string $setting, mixed $value): self { switch ($setting) { case 'timezoneSetting': return $value === null ? $this : $this->setTimezone($value); case 'step': $this->setStep($value); return $this; case 'localMonthsOverflow': return $value === null ? $this : $this->settings(['monthOverflow' => $value]); case 'localYearsOverflow': return $value === null ? $this : $this->settings(['yearOverflow' => $value]); case 'localStrictModeEnabled': case 'localHumanDiffOptions': case 'localToStringFormat': case 'localSerializer': case 'localMacros': case 'localGenericMacros': case 'localFormatFunction': case 'localTranslator': $this->$setting = $value; return $this; default: // Drop unknown settings return $this; } } private static function incrementUnit(DateInterval $instance, string $unit, int $value): void { if ($value === 0) { return; } // @codeCoverageIgnoreStart if (PHP_VERSION_ID !== 8_03_20) { $instance->$unit += $value; return; } // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value); // @codeCoverageIgnoreEnd } /** @codeCoverageIgnore */ private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void { switch ($unit) { case 'y': $instance->y = $value; break; case 'm': $instance->m = $value; break; case 'd': $instance->d = $value; break; case 'h': $instance->h = $value; break; case 'i': $instance->i = $value; break; case 's': $instance->s = $value; break; default: $instance->$unit = $value; } } }
PHP
{ "end_line": 1789, "name": "toArray", "signature": "public function toArray(): array", "start_line": 1777 }
{ "class_name": "CarbonInterval", "class_signature": "class CarbonInterval implements CarbonConverterInterface, UnitValue", "namespace": "Carbon" }
toPeriod
Carbon/src/Carbon/CarbonInterval.php
public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH], 'day' => ['week' => Carbon::DAYS_PER_WEEK], 'hour' => ['day' => Carbon::HOURS_PER_DAY], 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], ]; return $defaults[$source][$target] ?? null; } /** * Returns current config for days per week. * * @return int|float */ public static function getDaysPerWeek() { return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; } /** * Returns current config for hours per day. * * @return int|float */ public static function getHoursPerDay() { return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; } /** * Returns current config for minutes per hour. * * @return int|float */ public static function getMinutesPerHour() { return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; } /** * Returns current config for seconds per minute. * * @return int|float */ public static function getSecondsPerMinute() { return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMillisecondsPerSecond() { return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMicrosecondsPerMillisecond() { return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; } /** * Create a new CarbonInterval instance from specific values. * This is an alias for the constructor that allows better fluent * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than * (new CarbonInterval(1))->fn(). * * @param int $years * @param int $months * @param int $weeks * @param int $days * @param int $hours * @param int $minutes * @param int $seconds * @param int $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. * * @return static */ public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); } /** * Parse a string into a new CarbonInterval object according to the specified format. * * @example * ``` * echo Carboninterval::createFromFormat('H:i', '1:30'); * ``` * * @param string $format Format of the $interval input string * @param string|null $interval Input string to convert into an interval * * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. * * @return static */ public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; } /** * Return the original source used to create the current interval. * * @return array|int|string|DateInterval|mixed|null */ public function original() { return $this->originalInput; } /** * Return the start date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function start(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->startDate; } /** * Return the end date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function end(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->endDate; } /** * Get rid of the original input, start date and end date that may be kept in memory. * * @return $this */ public function optimize(): static { $this->originalInput = null; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; $this->absolute = false; return $this; } /** * Get a copy of the instance. * * @return static */ public function copy(): static { $date = new static(0); $date->copyProperties($this); $date->step = $this->step; return $date; } /** * Get a copy of the instance. * * @return static */ public function clone(): static { return $this->copy(); } /** * Provide static helpers to create instances. Allows CarbonInterval::years(3). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @return static|mixed|null */ public static function __callStatic(string $method, array $parameters) { try { $interval = new static(0); $localStrictModeEnabled = $interval->localStrictModeEnabled; $interval->localStrictModeEnabled = true; $result = static::hasMacro($method) ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { return $interval->callMacro($method, $parameters); }) : $interval->$method(...$parameters); $interval->localStrictModeEnabled = $localStrictModeEnabled; return $result; } catch (BadFluentSetterException $exception) { if (Carbon::isStrictModeEnabled()) { throw new BadFluentConstructorException($method, 0, $exception); } return null; } } /** * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. * * @param array $dump data as exported by var_export() * * @return static */ #[ReturnTypeWillChange] public static function __set_state($dump) { /** @noinspection PhpVoidFunctionResultUsedInspection */ /** @var DateInterval $dateInterval */ $dateInterval = parent::__set_state($dump); return static::instance($dateInterval); } /** * Return the current context from inside a macro callee or a new one if static. * * @return static */ protected static function this(): static { return end(static::$macroContextStack) ?: new static(0); } /** * Creates a CarbonInterval from string. * * Format: * * Suffix | Unit | Example | DateInterval expression * -------|---------|---------|------------------------ * y | years | 1y | P1Y * mo | months | 3mo | P3M * w | weeks | 2w | P2W * d | days | 28d | P28D * h | hours | 4h | PT4H * m | minutes | 12m | PT12M * s | seconds | 59s | PT59S * * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. * * Special cases: * - An empty string will return a zero interval * - Fractions are allowed for weeks, days, hours and minutes and will be converted * and rounded to the next smaller value (caution: 0.5w = 4d) * * @param string $intervalDefinition * * @throws InvalidIntervalException * * @return static */ public static function fromString(string $intervalDefinition): static { if (empty($intervalDefinition)) { return self::withOriginal(new static(0), $intervalDefinition); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $milliseconds = 0; $microseconds = 0; $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ([$part, $value, $unit] = array_shift($parts)) { $intValue = (int) $value; $fraction = (float) $value - $intValue; // Fix calculation precision switch (round($fraction, 6)) { case 1: $fraction = 0; $intValue++; break; case 0: $fraction = 0; break; } switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { case 'millennia': case 'millennium': $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; break; case 'century': case 'centuries': $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; break; case 'decade': case 'decades': $years += $intValue * CarbonInterface::YEARS_PER_DECADE; break; case 'year': case 'years': case 'y': case 'yr': case 'yrs': $years += $intValue; break; case 'quarter': case 'quarters': $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; break; case 'month': case 'months': case 'mo': case 'mos': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; } break; case 'second': case 'seconds': case 's': $seconds += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; } break; case 'millisecond': case 'milliseconds': case 'milli': case 'ms': $milliseconds += $intValue; if ($fraction) { $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); } break; case 'microsecond': case 'microseconds': case 'micro': case 'µs': $microseconds += $intValue; break; default: throw new InvalidIntervalException( "Invalid part $part in definition $intervalDefinition", ); } } return self::withOriginal( new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds), $intervalDefinition, ); } /** * Creates a CarbonInterval from string using a different locale. * * @param string $interval interval string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be used instead. * * @return static */ public static function parseFromLocale(string $interval, ?string $locale = null): static { return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE)); } /** * Create an interval from the difference between 2 dates. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $start * @param \Carbon\Carbon|\DateTimeInterface|mixed $end * * @return static */ public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; } /** * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function abs(bool $absolute = false): static { if ($absolute && $this->invert) { $this->invert(); } return $this; } /** * @alias abs * * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function absolute(bool $absolute = true): static { return $this->abs($absolute); } /** * Cast the current instance into the given class. * * @template T of DateInterval * * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { return self::castIntervalToClass($this, $className); } /** * Create a CarbonInterval instance from a DateInterval one. Can not instance * DateInterval objects created from DateTime::diff() as you can't externally * set the $days field. * * @param DateInterval $interval * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static */ public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static { if ($skipCopy && $interval instanceof static) { return $interval; } return self::castIntervalToClass($interval, static::class, $skip); } /** * Make a CarbonInterval instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static|null */ public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); } protected static function makeFromString(string $interval): ?self { $interval = preg_replace('/\s+/', ' ', trim($interval)); if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { return static::fromString($interval); } $intervalInstance = static::createFromDateString($interval); return $intervalInstance->isEmpty() ? null : $intervalInstance; } protected function resolveInterval($interval): ?self { if (!($interval instanceof self)) { return self::make($interval); } return $interval; } /** * Sets up a DateInterval from the relative parts of the string. * * @param string $datetime * * @return static * * @link https://php.net/manual/en/dateinterval.createfromdatestring.php */ public static function createFromDateString(string $datetime): static { $string = strtr($datetime, [ ',' => ' ', ' and ' => ' ', ]); $previousException = null; try { $interval = parent::createFromDateString($string); } catch (Throwable $exception) { $interval = null; $previousException = $exception; } $interval ?: throw new InvalidFormatException( 'Could not create interval from: '.var_export($datetime, true), previous: $previousException, ); if (!($interval instanceof static)) { $interval = static::instance($interval); } return self::withOriginal($interval, $datetime); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the CarbonInterval object. */ public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; } /** * Get a part of the CarbonInterval object. */ public function __get(string $name): int|float|string|null { return $this->get($name); } /** * Set a part of the CarbonInterval object. * * @param Unit|string|array $name * @param int $value * * @throws UnknownSetterException * * @return $this */ public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; } /** * Set a part of the CarbonInterval object. * * @param string $name * @param int $value * * @throws UnknownSetterException */ public function __set(string $name, $value) { $this->set($name, $value); } /** * Allow setting of weeks and days to be cumulative. * * @param int $weeks Number of weeks to set * @param int $days Number of days to set * * @return static */ public function weeksAndDays(int $weeks, int $days): static { $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; return $this; } /** * Returns true if the interval is empty for each unit. * * @return bool */ public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonInterval::macro('twice', function () { * return $this->times(2); * }); * echo CarbonInterval::hours(2)->twice(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonInterval::mixin(new class { * public function daysToHours() { * return function () { * $this->hours += $this->days; * $this->days = 0; * * return $this; * }; * } * public function hoursToDays() { * return function () { * $this->days += $this->hours; * $this->hours = 0; * * return $this; * }; * } * }); * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; * echo CarbonInterval::days(5)->daysToHours() . "\n"; * ``` * * @param object|string $mixin * * @throws ReflectionException * * @return void */ public static function mixin($mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Call given macro. * * @param string $name * @param array $parameters * * @return mixed */ protected function callMacro(string $name, array $parameters) { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadFluentSetterException|Throwable * * @return static|int|float|string */ public function __call(string $method, array $parameters) { if (static::hasMacro($method)) { return static::bindMacroContext($this, function () use (&$method, &$parameters) { return $this->callMacro($method, $parameters); }); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); return $this->{$match['method']}($value, $match['unit']); } $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); try { $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); } } return $this; } protected function getForHumansInitialVariables($syntax, $short): array { if (\is_array($syntax)) { return $syntax; } if (\is_int($short)) { return [ 'parts' => $short, 'short' => false, ]; } if (\is_bool($syntax)) { return [ 'short' => $syntax, 'syntax' => CarbonInterface::DIFF_ABSOLUTE, ]; } return []; } /** * @param mixed $syntax * @param mixed $short * @param mixed $parts * @param mixed $options * * @return array */ protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array { $optionalSpace = ' '; $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; /** @var bool|string $join */ $join = $default === '' ? '' : ' '; /** @var bool|array|string $altNumbers */ $altNumbers = false; $aUnit = false; $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); $skip = array_map( static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit, (array) $skip, ); $skip = array_map( 'strtolower', array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''), ); $syntax ??= CarbonInterface::DIFF_ABSOLUTE; if ($parts === self::NO_LIMIT) { $parts = INF; } $options ??= static::getHumanDiffOptions(); if ($join === false) { $join = ' '; } elseif ($join === true) { $join = [ $default, $this->getTranslationMessage('list.1') ?? $default, ]; } if ($altNumbers && $altNumbers !== true) { $language = new Language($this->locale); $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { [$default, $last] = $join; if ($default !== ' ') { $optionalSpace = ''; } $join = function ($list) use ($default, $last) { if (\count($list) < 2) { return implode('', $list); } $end = array_pop($list); return implode($default, $list).$last.$end; }; } if (\is_string($join)) { if ($join !== ' ') { $optionalSpace = ''; } $glue = $join; $join = static fn ($list) => implode($glue, $list); } $interpolations = [ ':optional-space' => $optionalSpace, ]; $translator ??= isset($locale) ? Translator::get($locale) : null; return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator]; } protected static function getRoundingMethodFromOptions(int $options): ?string { if ($options & CarbonInterface::ROUND) { return 'round'; } if ($options & CarbonInterface::CEIL) { return 'ceil'; } if ($options & CarbonInterface::FLOOR) { return 'floor'; } return null; } /** * Returns interval values as an array where key are the unit names and values the counts. * * @return int[] */ public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; } /** * Returns interval non-zero values as an array where key are the unit names and values the counts. * * @return int[] */ public function getNonZeroValues(): array { return array_filter($this->toArray(), 'intval'); } /** * Returns interval values as an array where key are the unit names and values the counts * from the biggest non-zero one the the smallest non-zero one. * * @return int[] */ public function getValuesSequence(): array { $nonZeroValues = $this->getNonZeroValues(); if ($nonZeroValues === []) { return []; } $keys = array_keys($nonZeroValues); $firstKey = $keys[0]; $lastKey = $keys[\count($keys) - 1]; $values = []; $record = false; foreach ($this->toArray() as $unit => $count) { if ($unit === $firstKey) { $record = true; } if ($record) { $values[$unit] = $count; } if ($unit === $lastKey) { $record = false; } } return $values; } /** * Get the current interval in a human readable format in the current locale. * * @example * ``` * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; * ``` * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: -1: no limits) * @param int $options human diff options * * @throws Exception * * @return string */ public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string { /* @var TranslatorInterface|null $translator */ [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this ->getForHumansParameters($syntax, $short, $parts, $options); $interval = []; $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; $count = 1; $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); $declensionMode = null; $translator ??= $this->getLocalTranslator(); $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); if ($this->needsDeclension($declensionMode, $index, $parts)) { // Some languages have special pluralization for past and future tense. $key = $unit.'_'.$transId; $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); if ($result !== $key) { return $result; } } } $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); if ($result !== $unit) { return $result; } return null; }; $intervalValues = $this; $method = static::getRoundingMethodFromOptions($options); if ($method) { $previousCount = INF; while ( \count($intervalValues->getNonZeroValues()) > $parts && ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 ) { $index = min($count, $previousCount - 1) - 2; if ($index < 0) { break; } $intervalValues = $this->copy()->roundUnit( $keys[$index], 1, $method, ); $previousCount = $count; } } $diffIntervalArray = [ ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], ]; if (!empty($skip)) { foreach ($diffIntervalArray as $index => &$unitData) { $nextIndex = $index + 1; if ($unitData['value'] && isset($diffIntervalArray[$nextIndex]) && \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) ) { $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); $unitData['value'] = 0; } } } $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; } } if (!$absolute) { return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); }; $fallbackUnit = ['second', 's']; foreach ($diffIntervalArray as $diffIntervalData) { if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } // break the loop after we get the required number of parts in array if (\count($interval) >= $parts) { break; } // break the loop after we have reached the minimum unit if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } $actualParts = \count($interval); foreach ($interval as $index => &$item) { $item = $transChoice($item[0], $item[1], $index, $actualParts); } if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; $unit = $fallbackUnit[$short ? 1 : 0]; $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); } // join the interval parts by a space $time = $join($interval); unset($diffIntervalArray, $interval); if ($absolute) { return $time; } $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); if ($parts === 1) { if ($relativeToNow && $unit === 'day') { $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null; if ($specialTranslations && $options & $specialTranslations['option']) { $key = $specialTranslations[$isFuture ? 'future' : 'past']; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } } $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; } $time = [':time' => $time]; return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); } public function format(string $format): string { $output = parent::format($format); if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) { return $output; } $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate); return str_replace('(unknown)', $this->rawInterval->format('%a'), $output); } /** * Format the instance as a string using the forHumans() function. * * @throws Exception * * @return string */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if (!$format) { return $this->forHumans(); } if ($format instanceof Closure) { return $format($this); } return $this->format($format); } /** * Return native DateInterval PHP object matching the current instance. * * @example * ``` * var_dump(CarbonInterval::hours(2)->toDateInterval()); * ``` * * @return DateInterval */ public function toDateInterval(): DateInterval { return self::castIntervalToClass($this, DateInterval::class); } /** * Convert the interval to a CarbonPeriod. * * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. * * @return CarbonPeriod */ public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); } /** * Decompose the current interval into * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); } /** * Invert the interval. * * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this */ public function invert($inverted = null): static { $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; return $this; } protected function solveNegativeInterval(): static { if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { $this->years *= self::NEGATIVE; $this->months *= self::NEGATIVE; $this->dayz *= self::NEGATIVE; $this->hours *= self::NEGATIVE; $this->minutes *= self::NEGATIVE; $this->seconds *= self::NEGATIVE; $this->microseconds *= self::NEGATIVE; $this->invert(); } return $this; } /** * Add the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function sub($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } return $this->add($unit, -(float) $value); } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function subtract($unit, $value = 1): static { return $this->sub($unit, $value); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Multiply current instance given number of times. times() is naive, it multiplies each unit * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded * separately for each unit. * * Use times() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see multiply() * * @param float|int $factor * * @return $this */ public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; } /** * Divide current instance by a given divider. shares() is naive, it divides each unit separately * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours * and 7 minutes. * * Use shares() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see divide() * * @param float|int $divider * * @return $this */ public function shares($divider): static { return $this->times(1 / $divider); } protected function copyProperties(self $interval, $ignoreSign = false): static { $this->years = $interval->years; $this->months = $interval->months; $this->dayz = $interval->dayz; $this->hours = $interval->hours; $this->minutes = $interval->minutes; $this->seconds = $interval->seconds; $this->microseconds = $interval->microseconds; if (!$ignoreSign) { $this->invert = $interval->invert; } return $this; } /** * Multiply and cascade current instance by a given factor. * * @param float|int $factor * * @return $this */ public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); } /** * Divide and cascade current instance by a given divider. * * @param float|int $divider * * @return $this */ public function divide($divider): static { return $this->multiply(1 / $divider); } /** * Get the interval_spec string of a date interval. * * @param DateInterval $interval * * @return string */ public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), static::PERIOD_MONTHS => abs($interval->m), static::PERIOD_DAYS => abs($interval->d), ]); $skip = array_map([Unit::class, 'toNameIfUnit'], $skip); if ( $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) ) { $date = [ static::PERIOD_DAYS => abs($interval->days), ]; } $seconds = abs($interval->s); if ($microseconds && $interval->f > 0) { $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); } $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; foreach ($date as $key => $value) { $specString .= $value.$key; } if (\count($time) > 0) { $specString .= static::PERIOD_TIME_PREFIX; foreach ($time as $key => $value) { $specString .= $value.$key; } } return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; } /** * Get the interval_spec string. * * @return string */ public function spec(bool $microseconds = false): string { return static::getDateIntervalSpec($this, $microseconds); } /** * Comparing 2 date intervals. * * @param DateInterval $first * @param DateInterval $second * * @return int 0, 1 or -1 */ public static function compareDateIntervals(DateInterval $first, DateInterval $second): int { $current = Carbon::now(); $passed = $current->avoidMutation()->add($second); $current->add($first); return $current <=> $passed; } /** * Comparing with passed interval. * * @param DateInterval $interval * * @return int 0, 1 or -1 */ public function compare(DateInterval $interval): int { return static::compareDateIntervals($this, $interval); } /** * Convert overflowed values into bigger units. * * @return $this */ public function cascade(): static { return $this->doCascade(false); } public function hasNegativeValues(): bool { foreach ($this->toArray() as $value) { if ($value < 0) { return true; } } return false; } public function hasPositiveValues(): bool { foreach ($this->toArray() as $value) { if ($value > 0) { return true; } } return false; } /** * Get amount of given unit equivalent to the interval. * * @param string $unit * * @throws UnknownUnitException|UnitNotConfiguredException * * @return float */ public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see equalTo() * * @return bool */ public function eq($interval): bool { return $this->equalTo($interval); } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see notEqualTo() * * @return bool */ public function ne($interval): bool { return $this->notEqualTo($interval); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function notEqualTo($interval): bool { return !$this->eq($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThan() * * @return bool */ public function gt($interval): bool { return $this->greaterThan($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThanOrEqualTo() * * @return bool */ public function gte($interval): bool { return $this->greaterThanOrEqualTo($interval); } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThanOrEqualTo($interval): bool { return $this->greaterThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThan() * * @return bool */ public function lt($interval): bool { return $this->lessThan($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThanOrEqualTo() * * @return bool */ public function lte($interval): bool { return $this->lessThanOrEqualTo($interval); } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThanOrEqualTo($interval): bool { return $this->lessThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function between($interval1, $interval2, bool $equal = true): bool { return $equal ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) : $this->greaterThan($interval1) && $this->lessThan($interval2); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenIncluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenExcluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, false); } /** * Determines if the instance is between two others * * @example * ``` * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function isBetween($interval1, $interval2, bool $equal = true): bool { return $this->between($interval1, $interval2, $equal); } /** * Round the current instance at the given unit with given precision if specified and the given function. * * @throws Exception */ public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); } /** * Truncate the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function floorUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function ceilUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified. * * @param float|int|string|DateInterval|null $precision * @param string $function * * @throws Exception * * @return $this */ public function round($precision = 1, string $function = 'round'): static { return $this->roundWith($precision, $function); } /** * Round the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function floor(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function ceil(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'ceil'); } public function __unserialize(array $data): void { $properties = array_combine( array_map( static fn (mixed $key) => \is_string($key) ? str_replace('tzName', 'timezoneSetting', $key) : $key, array_keys($data), ), $data, ); if (method_exists(parent::class, '__unserialize')) { // PHP >= 8.2 parent::__unserialize($properties); return; } // PHP <= 8.1 // @codeCoverageIgnoreStart $properties = array_combine( array_map( static fn (string $property) => preg_replace('/^\0.+\0/', '', $property), array_keys($data), ), $data, ); $localStrictMode = $this->localStrictModeEnabled; $this->localStrictModeEnabled = false; $days = $properties['days'] ?? false; $this->days = $days === false ? false : (int) $days; $this->y = (int) ($properties['y'] ?? 0); $this->m = (int) ($properties['m'] ?? 0); $this->d = (int) ($properties['d'] ?? 0); $this->h = (int) ($properties['h'] ?? 0); $this->i = (int) ($properties['i'] ?? 0); $this->s = (int) ($properties['s'] ?? 0); $this->f = (float) ($properties['f'] ?? 0.0); // @phpstan-ignore-next-line $this->weekday = (int) ($properties['weekday'] ?? 0); // @phpstan-ignore-next-line $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0); // @phpstan-ignore-next-line $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0); $this->invert = (int) ($properties['invert'] ?? 0); // @phpstan-ignore-next-line $this->special_type = (int) ($properties['special_type'] ?? 0); // @phpstan-ignore-next-line $this->special_amount = (int) ($properties['special_amount'] ?? 0); // @phpstan-ignore-next-line $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0); // @phpstan-ignore-next-line $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0); parent::__construct(self::getDateIntervalSpec($this)); foreach ($properties as $property => $value) { if ($property === 'localStrictModeEnabled') { continue; } $this->$property = $value; } $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode; // @codeCoverageIgnoreEnd } /** * @template T * * @param T $interval * @param mixed $original * * @return T */ private static function withOriginal(mixed $interval, mixed $original): mixed { if ($interval instanceof self) { $interval->originalInput = $original; } return $interval; } private static function standardizeUnit(string $unit): string { $unit = rtrim($unit, 'sz').'s'; return $unit === 'days' ? 'dayz' : $unit; } private static function getFlipCascadeFactors(): array { if (!self::$flipCascadeFactors) { self::$flipCascadeFactors = []; foreach (self::getCascadeFactors() as $to => [$factor, $from]) { self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; } } return self::$flipCascadeFactors; } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object { $mainClass = DateInterval::class; if (!is_a($className, $mainClass, true)) { throw new InvalidCastException("$className is not a sub-class of $mainClass."); } $microseconds = $interval->f; $instance = self::buildInstance($interval, $className, $skip); if ($instance instanceof self) { $instance->originalInput = $interval; } if ($microseconds) { $instance->f = $microseconds; } if ($interval instanceof self && is_a($className, self::class, true)) { self::copyStep($interval, $instance); } self::copyNegativeUnits($interval, $instance); return self::withOriginal($instance, $interval); } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function buildInstance( DateInterval $interval, string $className, array $skip = [], ): object { $serialization = self::buildSerializationString($interval, $className, $skip); return match ($serialization) { null => new $className(static::getDateIntervalSpec($interval, false, $skip)), default => unserialize($serialization), }; } /** * As demonstrated by rlanvin (https://github.com/rlanvin) in * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438 * * Modifying the output of serialize() to change the class name and unserializing * the tweaked string allows creating new interval instances where the ->days * property can be set. It's not possible neither with `new` nto with `__set_state`. * * It has a non-negligible performance cost, so we'll use this method only if * $interval->days !== false. */ private static function buildSerializationString( DateInterval $interval, string $className, array $skip = [], ): ?string { if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) { return null; } // De-enhance CarbonInterval objects to be serializable back to DateInterval if ($interval instanceof self && !is_a($className, self::class, true)) { $interval = clone $interval; unset($interval->timezoneSetting); unset($interval->originalInput); unset($interval->startDate); unset($interval->endDate); unset($interval->rawInterval); unset($interval->absolute); unset($interval->initialValues); unset($interval->clock); unset($interval->step); unset($interval->localMonthsOverflow); unset($interval->localYearsOverflow); unset($interval->localStrictModeEnabled); unset($interval->localHumanDiffOptions); unset($interval->localToStringFormat); unset($interval->localSerializer); unset($interval->localMacros); unset($interval->localGenericMacros); unset($interval->localFormatFunction); unset($interval->localTranslator); } $serialization = serialize($interval); $inputClass = $interval::class; $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":'; if (!str_starts_with($serialization, $expectedStart)) { return null; // @codeCoverageIgnore } return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart)); } private static function copyStep(self $from, self $to): void { $to->setStep($from->getStep()); } private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void { $to->invert = $from->invert; foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { if ($from->$unit < 0) { self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE); } } } private function invertCascade(array $values): static { return $this->set(array_map(function ($value) { return -$value; }, $values))->doCascade(true)->invert(); } private function doCascade(bool $deep): static { $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { if ($$key === 'dayz') { $$key = 'daysExcludeWeeks'; } } $value = $newData[$source]; $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; $decimalPart = fmod($newData[$source], 1); if ($decimalPart !== 0.0) { $unit = $source; foreach ($previous as [$subUnit, $subFactor]) { $newData[$unit] -= $decimalPart; $newData[$subUnit] += $decimalPart * $subFactor; $decimalPart = fmod($newData[$subUnit], 1); if ($decimalPart === 0.0) { break; } $unit = $subUnit; } } array_unshift($previous, [$source, $factor]); } $positive = null; if (!$deep) { foreach ($newData as $value) { if ($value) { if ($positive === null) { $positive = ($value > 0); continue; } if (($value > 0) !== $positive) { return $this->invertCascade($originalData) ->solveNegativeInterval(); } } } } return $this->set($newData) ->solveNegativeInterval(); } private function needsDeclension(string $mode, int $index, int $parts): bool { return match ($mode) { 'last' => $index === $parts - 1, default => true, }; } private function checkIntegerValue(string $name, mixed $value): void { if (\is_int($value)) { return; } $this->assertSafeForInteger($name, $value); if (\is_float($value) && (((float) (int) $value) === $value)) { return; } if (!self::$floatSettersEnabled) { $type = \gettype($value); @trigger_error( "Since 2.70.0, it's deprecated to pass $type value for $name.\n". "It's truncated when stored as an integer interval unit.\n". "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", \E_USER_DEPRECATED, ); } } /** * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. */ private function assertSafeForInteger(string $name, mixed $value): void { if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); } } private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void { if (self::$floatSettersEnabled) { $floatValue = (float) $value; $base = (float) $integerValue; if ($floatValue === $base) { return; } $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; $upper = true; foreach ($units as $property => $name) { if ($name === $unit) { $upper = false; continue; } if (!$upper && $this->$property !== 0) { throw new RuntimeException( "You cannot set $unit to a float value as $name would be overridden, ". 'set it first to 0 explicitly if you really want to erase its value' ); } } $this->add($unit, $floatValue - $base); } } private function getInnerValues(): array { return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days]; } private function checkStartAndEnd(): void { if ( $this->initialValues !== null && ($this->startDate !== null || $this->endDate !== null) && $this->initialValues !== $this->getInnerValues() ) { $this->absolute = false; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; } } /** @return $this */ private function setSetting(string $setting, mixed $value): self { switch ($setting) { case 'timezoneSetting': return $value === null ? $this : $this->setTimezone($value); case 'step': $this->setStep($value); return $this; case 'localMonthsOverflow': return $value === null ? $this : $this->settings(['monthOverflow' => $value]); case 'localYearsOverflow': return $value === null ? $this : $this->settings(['yearOverflow' => $value]); case 'localStrictModeEnabled': case 'localHumanDiffOptions': case 'localToStringFormat': case 'localSerializer': case 'localMacros': case 'localGenericMacros': case 'localFormatFunction': case 'localTranslator': $this->$setting = $value; return $this; default: // Drop unknown settings return $this; } } private static function incrementUnit(DateInterval $instance, string $unit, int $value): void { if ($value === 0) { return; } // @codeCoverageIgnoreStart if (PHP_VERSION_ID !== 8_03_20) { $instance->$unit += $value; return; } // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value); // @codeCoverageIgnoreEnd } /** @codeCoverageIgnore */ private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void { switch ($unit) { case 'y': $instance->y = $value; break; case 'm': $instance->m = $value; break; case 'd': $instance->d = $value; break; case 'h': $instance->h = $value; break; case 'i': $instance->i = $value; break; case 's': $instance->s = $value; break; default: $instance->$unit = $value; } } }
PHP
{ "end_line": 2163, "name": "toPeriod", "signature": "public function toPeriod(...$params): CarbonPeriod", "start_line": 2148 }
{ "class_name": "CarbonInterval", "class_signature": "class CarbonInterval implements CarbonConverterInterface, UnitValue", "namespace": "Carbon" }
stepBy
Carbon/src/Carbon/CarbonInterval.php
public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH], 'day' => ['week' => Carbon::DAYS_PER_WEEK], 'hour' => ['day' => Carbon::HOURS_PER_DAY], 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], ]; return $defaults[$source][$target] ?? null; } /** * Returns current config for days per week. * * @return int|float */ public static function getDaysPerWeek() { return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; } /** * Returns current config for hours per day. * * @return int|float */ public static function getHoursPerDay() { return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; } /** * Returns current config for minutes per hour. * * @return int|float */ public static function getMinutesPerHour() { return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; } /** * Returns current config for seconds per minute. * * @return int|float */ public static function getSecondsPerMinute() { return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMillisecondsPerSecond() { return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMicrosecondsPerMillisecond() { return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; } /** * Create a new CarbonInterval instance from specific values. * This is an alias for the constructor that allows better fluent * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than * (new CarbonInterval(1))->fn(). * * @param int $years * @param int $months * @param int $weeks * @param int $days * @param int $hours * @param int $minutes * @param int $seconds * @param int $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. * * @return static */ public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); } /** * Parse a string into a new CarbonInterval object according to the specified format. * * @example * ``` * echo Carboninterval::createFromFormat('H:i', '1:30'); * ``` * * @param string $format Format of the $interval input string * @param string|null $interval Input string to convert into an interval * * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. * * @return static */ public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; } /** * Return the original source used to create the current interval. * * @return array|int|string|DateInterval|mixed|null */ public function original() { return $this->originalInput; } /** * Return the start date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function start(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->startDate; } /** * Return the end date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function end(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->endDate; } /** * Get rid of the original input, start date and end date that may be kept in memory. * * @return $this */ public function optimize(): static { $this->originalInput = null; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; $this->absolute = false; return $this; } /** * Get a copy of the instance. * * @return static */ public function copy(): static { $date = new static(0); $date->copyProperties($this); $date->step = $this->step; return $date; } /** * Get a copy of the instance. * * @return static */ public function clone(): static { return $this->copy(); } /** * Provide static helpers to create instances. Allows CarbonInterval::years(3). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @return static|mixed|null */ public static function __callStatic(string $method, array $parameters) { try { $interval = new static(0); $localStrictModeEnabled = $interval->localStrictModeEnabled; $interval->localStrictModeEnabled = true; $result = static::hasMacro($method) ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { return $interval->callMacro($method, $parameters); }) : $interval->$method(...$parameters); $interval->localStrictModeEnabled = $localStrictModeEnabled; return $result; } catch (BadFluentSetterException $exception) { if (Carbon::isStrictModeEnabled()) { throw new BadFluentConstructorException($method, 0, $exception); } return null; } } /** * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. * * @param array $dump data as exported by var_export() * * @return static */ #[ReturnTypeWillChange] public static function __set_state($dump) { /** @noinspection PhpVoidFunctionResultUsedInspection */ /** @var DateInterval $dateInterval */ $dateInterval = parent::__set_state($dump); return static::instance($dateInterval); } /** * Return the current context from inside a macro callee or a new one if static. * * @return static */ protected static function this(): static { return end(static::$macroContextStack) ?: new static(0); } /** * Creates a CarbonInterval from string. * * Format: * * Suffix | Unit | Example | DateInterval expression * -------|---------|---------|------------------------ * y | years | 1y | P1Y * mo | months | 3mo | P3M * w | weeks | 2w | P2W * d | days | 28d | P28D * h | hours | 4h | PT4H * m | minutes | 12m | PT12M * s | seconds | 59s | PT59S * * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. * * Special cases: * - An empty string will return a zero interval * - Fractions are allowed for weeks, days, hours and minutes and will be converted * and rounded to the next smaller value (caution: 0.5w = 4d) * * @param string $intervalDefinition * * @throws InvalidIntervalException * * @return static */ public static function fromString(string $intervalDefinition): static { if (empty($intervalDefinition)) { return self::withOriginal(new static(0), $intervalDefinition); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $milliseconds = 0; $microseconds = 0; $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ([$part, $value, $unit] = array_shift($parts)) { $intValue = (int) $value; $fraction = (float) $value - $intValue; // Fix calculation precision switch (round($fraction, 6)) { case 1: $fraction = 0; $intValue++; break; case 0: $fraction = 0; break; } switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { case 'millennia': case 'millennium': $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; break; case 'century': case 'centuries': $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; break; case 'decade': case 'decades': $years += $intValue * CarbonInterface::YEARS_PER_DECADE; break; case 'year': case 'years': case 'y': case 'yr': case 'yrs': $years += $intValue; break; case 'quarter': case 'quarters': $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; break; case 'month': case 'months': case 'mo': case 'mos': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; } break; case 'second': case 'seconds': case 's': $seconds += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; } break; case 'millisecond': case 'milliseconds': case 'milli': case 'ms': $milliseconds += $intValue; if ($fraction) { $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); } break; case 'microsecond': case 'microseconds': case 'micro': case 'µs': $microseconds += $intValue; break; default: throw new InvalidIntervalException( "Invalid part $part in definition $intervalDefinition", ); } } return self::withOriginal( new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds), $intervalDefinition, ); } /** * Creates a CarbonInterval from string using a different locale. * * @param string $interval interval string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be used instead. * * @return static */ public static function parseFromLocale(string $interval, ?string $locale = null): static { return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE)); } /** * Create an interval from the difference between 2 dates. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $start * @param \Carbon\Carbon|\DateTimeInterface|mixed $end * * @return static */ public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; } /** * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function abs(bool $absolute = false): static { if ($absolute && $this->invert) { $this->invert(); } return $this; } /** * @alias abs * * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function absolute(bool $absolute = true): static { return $this->abs($absolute); } /** * Cast the current instance into the given class. * * @template T of DateInterval * * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { return self::castIntervalToClass($this, $className); } /** * Create a CarbonInterval instance from a DateInterval one. Can not instance * DateInterval objects created from DateTime::diff() as you can't externally * set the $days field. * * @param DateInterval $interval * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static */ public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static { if ($skipCopy && $interval instanceof static) { return $interval; } return self::castIntervalToClass($interval, static::class, $skip); } /** * Make a CarbonInterval instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static|null */ public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); } protected static function makeFromString(string $interval): ?self { $interval = preg_replace('/\s+/', ' ', trim($interval)); if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { return static::fromString($interval); } $intervalInstance = static::createFromDateString($interval); return $intervalInstance->isEmpty() ? null : $intervalInstance; } protected function resolveInterval($interval): ?self { if (!($interval instanceof self)) { return self::make($interval); } return $interval; } /** * Sets up a DateInterval from the relative parts of the string. * * @param string $datetime * * @return static * * @link https://php.net/manual/en/dateinterval.createfromdatestring.php */ public static function createFromDateString(string $datetime): static { $string = strtr($datetime, [ ',' => ' ', ' and ' => ' ', ]); $previousException = null; try { $interval = parent::createFromDateString($string); } catch (Throwable $exception) { $interval = null; $previousException = $exception; } $interval ?: throw new InvalidFormatException( 'Could not create interval from: '.var_export($datetime, true), previous: $previousException, ); if (!($interval instanceof static)) { $interval = static::instance($interval); } return self::withOriginal($interval, $datetime); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the CarbonInterval object. */ public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; } /** * Get a part of the CarbonInterval object. */ public function __get(string $name): int|float|string|null { return $this->get($name); } /** * Set a part of the CarbonInterval object. * * @param Unit|string|array $name * @param int $value * * @throws UnknownSetterException * * @return $this */ public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; } /** * Set a part of the CarbonInterval object. * * @param string $name * @param int $value * * @throws UnknownSetterException */ public function __set(string $name, $value) { $this->set($name, $value); } /** * Allow setting of weeks and days to be cumulative. * * @param int $weeks Number of weeks to set * @param int $days Number of days to set * * @return static */ public function weeksAndDays(int $weeks, int $days): static { $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; return $this; } /** * Returns true if the interval is empty for each unit. * * @return bool */ public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonInterval::macro('twice', function () { * return $this->times(2); * }); * echo CarbonInterval::hours(2)->twice(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonInterval::mixin(new class { * public function daysToHours() { * return function () { * $this->hours += $this->days; * $this->days = 0; * * return $this; * }; * } * public function hoursToDays() { * return function () { * $this->days += $this->hours; * $this->hours = 0; * * return $this; * }; * } * }); * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; * echo CarbonInterval::days(5)->daysToHours() . "\n"; * ``` * * @param object|string $mixin * * @throws ReflectionException * * @return void */ public static function mixin($mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Call given macro. * * @param string $name * @param array $parameters * * @return mixed */ protected function callMacro(string $name, array $parameters) { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadFluentSetterException|Throwable * * @return static|int|float|string */ public function __call(string $method, array $parameters) { if (static::hasMacro($method)) { return static::bindMacroContext($this, function () use (&$method, &$parameters) { return $this->callMacro($method, $parameters); }); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); return $this->{$match['method']}($value, $match['unit']); } $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); try { $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); } } return $this; } protected function getForHumansInitialVariables($syntax, $short): array { if (\is_array($syntax)) { return $syntax; } if (\is_int($short)) { return [ 'parts' => $short, 'short' => false, ]; } if (\is_bool($syntax)) { return [ 'short' => $syntax, 'syntax' => CarbonInterface::DIFF_ABSOLUTE, ]; } return []; } /** * @param mixed $syntax * @param mixed $short * @param mixed $parts * @param mixed $options * * @return array */ protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array { $optionalSpace = ' '; $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; /** @var bool|string $join */ $join = $default === '' ? '' : ' '; /** @var bool|array|string $altNumbers */ $altNumbers = false; $aUnit = false; $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); $skip = array_map( static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit, (array) $skip, ); $skip = array_map( 'strtolower', array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''), ); $syntax ??= CarbonInterface::DIFF_ABSOLUTE; if ($parts === self::NO_LIMIT) { $parts = INF; } $options ??= static::getHumanDiffOptions(); if ($join === false) { $join = ' '; } elseif ($join === true) { $join = [ $default, $this->getTranslationMessage('list.1') ?? $default, ]; } if ($altNumbers && $altNumbers !== true) { $language = new Language($this->locale); $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { [$default, $last] = $join; if ($default !== ' ') { $optionalSpace = ''; } $join = function ($list) use ($default, $last) { if (\count($list) < 2) { return implode('', $list); } $end = array_pop($list); return implode($default, $list).$last.$end; }; } if (\is_string($join)) { if ($join !== ' ') { $optionalSpace = ''; } $glue = $join; $join = static fn ($list) => implode($glue, $list); } $interpolations = [ ':optional-space' => $optionalSpace, ]; $translator ??= isset($locale) ? Translator::get($locale) : null; return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator]; } protected static function getRoundingMethodFromOptions(int $options): ?string { if ($options & CarbonInterface::ROUND) { return 'round'; } if ($options & CarbonInterface::CEIL) { return 'ceil'; } if ($options & CarbonInterface::FLOOR) { return 'floor'; } return null; } /** * Returns interval values as an array where key are the unit names and values the counts. * * @return int[] */ public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; } /** * Returns interval non-zero values as an array where key are the unit names and values the counts. * * @return int[] */ public function getNonZeroValues(): array { return array_filter($this->toArray(), 'intval'); } /** * Returns interval values as an array where key are the unit names and values the counts * from the biggest non-zero one the the smallest non-zero one. * * @return int[] */ public function getValuesSequence(): array { $nonZeroValues = $this->getNonZeroValues(); if ($nonZeroValues === []) { return []; } $keys = array_keys($nonZeroValues); $firstKey = $keys[0]; $lastKey = $keys[\count($keys) - 1]; $values = []; $record = false; foreach ($this->toArray() as $unit => $count) { if ($unit === $firstKey) { $record = true; } if ($record) { $values[$unit] = $count; } if ($unit === $lastKey) { $record = false; } } return $values; } /** * Get the current interval in a human readable format in the current locale. * * @example * ``` * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; * ``` * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: -1: no limits) * @param int $options human diff options * * @throws Exception * * @return string */ public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string { /* @var TranslatorInterface|null $translator */ [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this ->getForHumansParameters($syntax, $short, $parts, $options); $interval = []; $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; $count = 1; $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); $declensionMode = null; $translator ??= $this->getLocalTranslator(); $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); if ($this->needsDeclension($declensionMode, $index, $parts)) { // Some languages have special pluralization for past and future tense. $key = $unit.'_'.$transId; $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); if ($result !== $key) { return $result; } } } $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); if ($result !== $unit) { return $result; } return null; }; $intervalValues = $this; $method = static::getRoundingMethodFromOptions($options); if ($method) { $previousCount = INF; while ( \count($intervalValues->getNonZeroValues()) > $parts && ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 ) { $index = min($count, $previousCount - 1) - 2; if ($index < 0) { break; } $intervalValues = $this->copy()->roundUnit( $keys[$index], 1, $method, ); $previousCount = $count; } } $diffIntervalArray = [ ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], ]; if (!empty($skip)) { foreach ($diffIntervalArray as $index => &$unitData) { $nextIndex = $index + 1; if ($unitData['value'] && isset($diffIntervalArray[$nextIndex]) && \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) ) { $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); $unitData['value'] = 0; } } } $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; } } if (!$absolute) { return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); }; $fallbackUnit = ['second', 's']; foreach ($diffIntervalArray as $diffIntervalData) { if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } // break the loop after we get the required number of parts in array if (\count($interval) >= $parts) { break; } // break the loop after we have reached the minimum unit if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } $actualParts = \count($interval); foreach ($interval as $index => &$item) { $item = $transChoice($item[0], $item[1], $index, $actualParts); } if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; $unit = $fallbackUnit[$short ? 1 : 0]; $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); } // join the interval parts by a space $time = $join($interval); unset($diffIntervalArray, $interval); if ($absolute) { return $time; } $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); if ($parts === 1) { if ($relativeToNow && $unit === 'day') { $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null; if ($specialTranslations && $options & $specialTranslations['option']) { $key = $specialTranslations[$isFuture ? 'future' : 'past']; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } } $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; } $time = [':time' => $time]; return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); } public function format(string $format): string { $output = parent::format($format); if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) { return $output; } $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate); return str_replace('(unknown)', $this->rawInterval->format('%a'), $output); } /** * Format the instance as a string using the forHumans() function. * * @throws Exception * * @return string */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if (!$format) { return $this->forHumans(); } if ($format instanceof Closure) { return $format($this); } return $this->format($format); } /** * Return native DateInterval PHP object matching the current instance. * * @example * ``` * var_dump(CarbonInterval::hours(2)->toDateInterval()); * ``` * * @return DateInterval */ public function toDateInterval(): DateInterval { return self::castIntervalToClass($this, DateInterval::class); } /** * Convert the interval to a CarbonPeriod. * * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. * * @return CarbonPeriod */ public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); } /** * Decompose the current interval into * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); } /** * Invert the interval. * * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this */ public function invert($inverted = null): static { $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; return $this; } protected function solveNegativeInterval(): static { if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { $this->years *= self::NEGATIVE; $this->months *= self::NEGATIVE; $this->dayz *= self::NEGATIVE; $this->hours *= self::NEGATIVE; $this->minutes *= self::NEGATIVE; $this->seconds *= self::NEGATIVE; $this->microseconds *= self::NEGATIVE; $this->invert(); } return $this; } /** * Add the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function sub($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } return $this->add($unit, -(float) $value); } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function subtract($unit, $value = 1): static { return $this->sub($unit, $value); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Multiply current instance given number of times. times() is naive, it multiplies each unit * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded * separately for each unit. * * Use times() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see multiply() * * @param float|int $factor * * @return $this */ public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; } /** * Divide current instance by a given divider. shares() is naive, it divides each unit separately * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours * and 7 minutes. * * Use shares() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see divide() * * @param float|int $divider * * @return $this */ public function shares($divider): static { return $this->times(1 / $divider); } protected function copyProperties(self $interval, $ignoreSign = false): static { $this->years = $interval->years; $this->months = $interval->months; $this->dayz = $interval->dayz; $this->hours = $interval->hours; $this->minutes = $interval->minutes; $this->seconds = $interval->seconds; $this->microseconds = $interval->microseconds; if (!$ignoreSign) { $this->invert = $interval->invert; } return $this; } /** * Multiply and cascade current instance by a given factor. * * @param float|int $factor * * @return $this */ public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); } /** * Divide and cascade current instance by a given divider. * * @param float|int $divider * * @return $this */ public function divide($divider): static { return $this->multiply(1 / $divider); } /** * Get the interval_spec string of a date interval. * * @param DateInterval $interval * * @return string */ public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), static::PERIOD_MONTHS => abs($interval->m), static::PERIOD_DAYS => abs($interval->d), ]); $skip = array_map([Unit::class, 'toNameIfUnit'], $skip); if ( $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) ) { $date = [ static::PERIOD_DAYS => abs($interval->days), ]; } $seconds = abs($interval->s); if ($microseconds && $interval->f > 0) { $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); } $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; foreach ($date as $key => $value) { $specString .= $value.$key; } if (\count($time) > 0) { $specString .= static::PERIOD_TIME_PREFIX; foreach ($time as $key => $value) { $specString .= $value.$key; } } return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; } /** * Get the interval_spec string. * * @return string */ public function spec(bool $microseconds = false): string { return static::getDateIntervalSpec($this, $microseconds); } /** * Comparing 2 date intervals. * * @param DateInterval $first * @param DateInterval $second * * @return int 0, 1 or -1 */ public static function compareDateIntervals(DateInterval $first, DateInterval $second): int { $current = Carbon::now(); $passed = $current->avoidMutation()->add($second); $current->add($first); return $current <=> $passed; } /** * Comparing with passed interval. * * @param DateInterval $interval * * @return int 0, 1 or -1 */ public function compare(DateInterval $interval): int { return static::compareDateIntervals($this, $interval); } /** * Convert overflowed values into bigger units. * * @return $this */ public function cascade(): static { return $this->doCascade(false); } public function hasNegativeValues(): bool { foreach ($this->toArray() as $value) { if ($value < 0) { return true; } } return false; } public function hasPositiveValues(): bool { foreach ($this->toArray() as $value) { if ($value > 0) { return true; } } return false; } /** * Get amount of given unit equivalent to the interval. * * @param string $unit * * @throws UnknownUnitException|UnitNotConfiguredException * * @return float */ public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see equalTo() * * @return bool */ public function eq($interval): bool { return $this->equalTo($interval); } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see notEqualTo() * * @return bool */ public function ne($interval): bool { return $this->notEqualTo($interval); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function notEqualTo($interval): bool { return !$this->eq($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThan() * * @return bool */ public function gt($interval): bool { return $this->greaterThan($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThanOrEqualTo() * * @return bool */ public function gte($interval): bool { return $this->greaterThanOrEqualTo($interval); } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThanOrEqualTo($interval): bool { return $this->greaterThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThan() * * @return bool */ public function lt($interval): bool { return $this->lessThan($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThanOrEqualTo() * * @return bool */ public function lte($interval): bool { return $this->lessThanOrEqualTo($interval); } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThanOrEqualTo($interval): bool { return $this->lessThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function between($interval1, $interval2, bool $equal = true): bool { return $equal ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) : $this->greaterThan($interval1) && $this->lessThan($interval2); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenIncluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenExcluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, false); } /** * Determines if the instance is between two others * * @example * ``` * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function isBetween($interval1, $interval2, bool $equal = true): bool { return $this->between($interval1, $interval2, $equal); } /** * Round the current instance at the given unit with given precision if specified and the given function. * * @throws Exception */ public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); } /** * Truncate the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function floorUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function ceilUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified. * * @param float|int|string|DateInterval|null $precision * @param string $function * * @throws Exception * * @return $this */ public function round($precision = 1, string $function = 'round'): static { return $this->roundWith($precision, $function); } /** * Round the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function floor(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function ceil(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'ceil'); } public function __unserialize(array $data): void { $properties = array_combine( array_map( static fn (mixed $key) => \is_string($key) ? str_replace('tzName', 'timezoneSetting', $key) : $key, array_keys($data), ), $data, ); if (method_exists(parent::class, '__unserialize')) { // PHP >= 8.2 parent::__unserialize($properties); return; } // PHP <= 8.1 // @codeCoverageIgnoreStart $properties = array_combine( array_map( static fn (string $property) => preg_replace('/^\0.+\0/', '', $property), array_keys($data), ), $data, ); $localStrictMode = $this->localStrictModeEnabled; $this->localStrictModeEnabled = false; $days = $properties['days'] ?? false; $this->days = $days === false ? false : (int) $days; $this->y = (int) ($properties['y'] ?? 0); $this->m = (int) ($properties['m'] ?? 0); $this->d = (int) ($properties['d'] ?? 0); $this->h = (int) ($properties['h'] ?? 0); $this->i = (int) ($properties['i'] ?? 0); $this->s = (int) ($properties['s'] ?? 0); $this->f = (float) ($properties['f'] ?? 0.0); // @phpstan-ignore-next-line $this->weekday = (int) ($properties['weekday'] ?? 0); // @phpstan-ignore-next-line $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0); // @phpstan-ignore-next-line $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0); $this->invert = (int) ($properties['invert'] ?? 0); // @phpstan-ignore-next-line $this->special_type = (int) ($properties['special_type'] ?? 0); // @phpstan-ignore-next-line $this->special_amount = (int) ($properties['special_amount'] ?? 0); // @phpstan-ignore-next-line $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0); // @phpstan-ignore-next-line $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0); parent::__construct(self::getDateIntervalSpec($this)); foreach ($properties as $property => $value) { if ($property === 'localStrictModeEnabled') { continue; } $this->$property = $value; } $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode; // @codeCoverageIgnoreEnd } /** * @template T * * @param T $interval * @param mixed $original * * @return T */ private static function withOriginal(mixed $interval, mixed $original): mixed { if ($interval instanceof self) { $interval->originalInput = $original; } return $interval; } private static function standardizeUnit(string $unit): string { $unit = rtrim($unit, 'sz').'s'; return $unit === 'days' ? 'dayz' : $unit; } private static function getFlipCascadeFactors(): array { if (!self::$flipCascadeFactors) { self::$flipCascadeFactors = []; foreach (self::getCascadeFactors() as $to => [$factor, $from]) { self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; } } return self::$flipCascadeFactors; } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object { $mainClass = DateInterval::class; if (!is_a($className, $mainClass, true)) { throw new InvalidCastException("$className is not a sub-class of $mainClass."); } $microseconds = $interval->f; $instance = self::buildInstance($interval, $className, $skip); if ($instance instanceof self) { $instance->originalInput = $interval; } if ($microseconds) { $instance->f = $microseconds; } if ($interval instanceof self && is_a($className, self::class, true)) { self::copyStep($interval, $instance); } self::copyNegativeUnits($interval, $instance); return self::withOriginal($instance, $interval); } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function buildInstance( DateInterval $interval, string $className, array $skip = [], ): object { $serialization = self::buildSerializationString($interval, $className, $skip); return match ($serialization) { null => new $className(static::getDateIntervalSpec($interval, false, $skip)), default => unserialize($serialization), }; } /** * As demonstrated by rlanvin (https://github.com/rlanvin) in * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438 * * Modifying the output of serialize() to change the class name and unserializing * the tweaked string allows creating new interval instances where the ->days * property can be set. It's not possible neither with `new` nto with `__set_state`. * * It has a non-negligible performance cost, so we'll use this method only if * $interval->days !== false. */ private static function buildSerializationString( DateInterval $interval, string $className, array $skip = [], ): ?string { if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) { return null; } // De-enhance CarbonInterval objects to be serializable back to DateInterval if ($interval instanceof self && !is_a($className, self::class, true)) { $interval = clone $interval; unset($interval->timezoneSetting); unset($interval->originalInput); unset($interval->startDate); unset($interval->endDate); unset($interval->rawInterval); unset($interval->absolute); unset($interval->initialValues); unset($interval->clock); unset($interval->step); unset($interval->localMonthsOverflow); unset($interval->localYearsOverflow); unset($interval->localStrictModeEnabled); unset($interval->localHumanDiffOptions); unset($interval->localToStringFormat); unset($interval->localSerializer); unset($interval->localMacros); unset($interval->localGenericMacros); unset($interval->localFormatFunction); unset($interval->localTranslator); } $serialization = serialize($interval); $inputClass = $interval::class; $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":'; if (!str_starts_with($serialization, $expectedStart)) { return null; // @codeCoverageIgnore } return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart)); } private static function copyStep(self $from, self $to): void { $to->setStep($from->getStep()); } private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void { $to->invert = $from->invert; foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { if ($from->$unit < 0) { self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE); } } } private function invertCascade(array $values): static { return $this->set(array_map(function ($value) { return -$value; }, $values))->doCascade(true)->invert(); } private function doCascade(bool $deep): static { $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { if ($$key === 'dayz') { $$key = 'daysExcludeWeeks'; } } $value = $newData[$source]; $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; $decimalPart = fmod($newData[$source], 1); if ($decimalPart !== 0.0) { $unit = $source; foreach ($previous as [$subUnit, $subFactor]) { $newData[$unit] -= $decimalPart; $newData[$subUnit] += $decimalPart * $subFactor; $decimalPart = fmod($newData[$subUnit], 1); if ($decimalPart === 0.0) { break; } $unit = $subUnit; } } array_unshift($previous, [$source, $factor]); } $positive = null; if (!$deep) { foreach ($newData as $value) { if ($value) { if ($positive === null) { $positive = ($value > 0); continue; } if (($value > 0) !== $positive) { return $this->invertCascade($originalData) ->solveNegativeInterval(); } } } } return $this->set($newData) ->solveNegativeInterval(); } private function needsDeclension(string $mode, int $index, int $parts): bool { return match ($mode) { 'last' => $index === $parts - 1, default => true, }; } private function checkIntegerValue(string $name, mixed $value): void { if (\is_int($value)) { return; } $this->assertSafeForInteger($name, $value); if (\is_float($value) && (((float) (int) $value) === $value)) { return; } if (!self::$floatSettersEnabled) { $type = \gettype($value); @trigger_error( "Since 2.70.0, it's deprecated to pass $type value for $name.\n". "It's truncated when stored as an integer interval unit.\n". "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", \E_USER_DEPRECATED, ); } } /** * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. */ private function assertSafeForInteger(string $name, mixed $value): void { if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); } } private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void { if (self::$floatSettersEnabled) { $floatValue = (float) $value; $base = (float) $integerValue; if ($floatValue === $base) { return; } $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; $upper = true; foreach ($units as $property => $name) { if ($name === $unit) { $upper = false; continue; } if (!$upper && $this->$property !== 0) { throw new RuntimeException( "You cannot set $unit to a float value as $name would be overridden, ". 'set it first to 0 explicitly if you really want to erase its value' ); } } $this->add($unit, $floatValue - $base); } } private function getInnerValues(): array { return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days]; } private function checkStartAndEnd(): void { if ( $this->initialValues !== null && ($this->startDate !== null || $this->endDate !== null) && $this->initialValues !== $this->getInnerValues() ) { $this->absolute = false; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; } } /** @return $this */ private function setSetting(string $setting, mixed $value): self { switch ($setting) { case 'timezoneSetting': return $value === null ? $this : $this->setTimezone($value); case 'step': $this->setStep($value); return $this; case 'localMonthsOverflow': return $value === null ? $this : $this->settings(['monthOverflow' => $value]); case 'localYearsOverflow': return $value === null ? $this : $this->settings(['yearOverflow' => $value]); case 'localStrictModeEnabled': case 'localHumanDiffOptions': case 'localToStringFormat': case 'localSerializer': case 'localMacros': case 'localGenericMacros': case 'localFormatFunction': case 'localTranslator': $this->$setting = $value; return $this; default: // Drop unknown settings return $this; } } private static function incrementUnit(DateInterval $instance, string $unit, int $value): void { if ($value === 0) { return; } // @codeCoverageIgnoreStart if (PHP_VERSION_ID !== 8_03_20) { $instance->$unit += $value; return; } // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value); // @codeCoverageIgnoreEnd } /** @codeCoverageIgnore */ private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void { switch ($unit) { case 'y': $instance->y = $value; break; case 'm': $instance->m = $value; break; case 'd': $instance->d = $value; break; case 'h': $instance->h = $value; break; case 'i': $instance->i = $value; break; case 's': $instance->s = $value; break; default: $instance->$unit = $value; } } }
PHP
{ "end_line": 2192, "name": "stepBy", "signature": "public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod", "start_line": 2173 }
{ "class_name": "CarbonInterval", "class_signature": "class CarbonInterval implements CarbonConverterInterface, UnitValue", "namespace": "Carbon" }
add
Carbon/src/Carbon/CarbonInterval.php
public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH], 'day' => ['week' => Carbon::DAYS_PER_WEEK], 'hour' => ['day' => Carbon::HOURS_PER_DAY], 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], ]; return $defaults[$source][$target] ?? null; } /** * Returns current config for days per week. * * @return int|float */ public static function getDaysPerWeek() { return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; } /** * Returns current config for hours per day. * * @return int|float */ public static function getHoursPerDay() { return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; } /** * Returns current config for minutes per hour. * * @return int|float */ public static function getMinutesPerHour() { return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; } /** * Returns current config for seconds per minute. * * @return int|float */ public static function getSecondsPerMinute() { return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMillisecondsPerSecond() { return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMicrosecondsPerMillisecond() { return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; } /** * Create a new CarbonInterval instance from specific values. * This is an alias for the constructor that allows better fluent * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than * (new CarbonInterval(1))->fn(). * * @param int $years * @param int $months * @param int $weeks * @param int $days * @param int $hours * @param int $minutes * @param int $seconds * @param int $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. * * @return static */ public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); } /** * Parse a string into a new CarbonInterval object according to the specified format. * * @example * ``` * echo Carboninterval::createFromFormat('H:i', '1:30'); * ``` * * @param string $format Format of the $interval input string * @param string|null $interval Input string to convert into an interval * * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. * * @return static */ public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; } /** * Return the original source used to create the current interval. * * @return array|int|string|DateInterval|mixed|null */ public function original() { return $this->originalInput; } /** * Return the start date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function start(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->startDate; } /** * Return the end date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function end(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->endDate; } /** * Get rid of the original input, start date and end date that may be kept in memory. * * @return $this */ public function optimize(): static { $this->originalInput = null; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; $this->absolute = false; return $this; } /** * Get a copy of the instance. * * @return static */ public function copy(): static { $date = new static(0); $date->copyProperties($this); $date->step = $this->step; return $date; } /** * Get a copy of the instance. * * @return static */ public function clone(): static { return $this->copy(); } /** * Provide static helpers to create instances. Allows CarbonInterval::years(3). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @return static|mixed|null */ public static function __callStatic(string $method, array $parameters) { try { $interval = new static(0); $localStrictModeEnabled = $interval->localStrictModeEnabled; $interval->localStrictModeEnabled = true; $result = static::hasMacro($method) ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { return $interval->callMacro($method, $parameters); }) : $interval->$method(...$parameters); $interval->localStrictModeEnabled = $localStrictModeEnabled; return $result; } catch (BadFluentSetterException $exception) { if (Carbon::isStrictModeEnabled()) { throw new BadFluentConstructorException($method, 0, $exception); } return null; } } /** * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. * * @param array $dump data as exported by var_export() * * @return static */ #[ReturnTypeWillChange] public static function __set_state($dump) { /** @noinspection PhpVoidFunctionResultUsedInspection */ /** @var DateInterval $dateInterval */ $dateInterval = parent::__set_state($dump); return static::instance($dateInterval); } /** * Return the current context from inside a macro callee or a new one if static. * * @return static */ protected static function this(): static { return end(static::$macroContextStack) ?: new static(0); } /** * Creates a CarbonInterval from string. * * Format: * * Suffix | Unit | Example | DateInterval expression * -------|---------|---------|------------------------ * y | years | 1y | P1Y * mo | months | 3mo | P3M * w | weeks | 2w | P2W * d | days | 28d | P28D * h | hours | 4h | PT4H * m | minutes | 12m | PT12M * s | seconds | 59s | PT59S * * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. * * Special cases: * - An empty string will return a zero interval * - Fractions are allowed for weeks, days, hours and minutes and will be converted * and rounded to the next smaller value (caution: 0.5w = 4d) * * @param string $intervalDefinition * * @throws InvalidIntervalException * * @return static */ public static function fromString(string $intervalDefinition): static { if (empty($intervalDefinition)) { return self::withOriginal(new static(0), $intervalDefinition); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $milliseconds = 0; $microseconds = 0; $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ([$part, $value, $unit] = array_shift($parts)) { $intValue = (int) $value; $fraction = (float) $value - $intValue; // Fix calculation precision switch (round($fraction, 6)) { case 1: $fraction = 0; $intValue++; break; case 0: $fraction = 0; break; } switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { case 'millennia': case 'millennium': $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; break; case 'century': case 'centuries': $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; break; case 'decade': case 'decades': $years += $intValue * CarbonInterface::YEARS_PER_DECADE; break; case 'year': case 'years': case 'y': case 'yr': case 'yrs': $years += $intValue; break; case 'quarter': case 'quarters': $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; break; case 'month': case 'months': case 'mo': case 'mos': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; } break; case 'second': case 'seconds': case 's': $seconds += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; } break; case 'millisecond': case 'milliseconds': case 'milli': case 'ms': $milliseconds += $intValue; if ($fraction) { $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); } break; case 'microsecond': case 'microseconds': case 'micro': case 'µs': $microseconds += $intValue; break; default: throw new InvalidIntervalException( "Invalid part $part in definition $intervalDefinition", ); } } return self::withOriginal( new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds), $intervalDefinition, ); } /** * Creates a CarbonInterval from string using a different locale. * * @param string $interval interval string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be used instead. * * @return static */ public static function parseFromLocale(string $interval, ?string $locale = null): static { return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE)); } /** * Create an interval from the difference between 2 dates. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $start * @param \Carbon\Carbon|\DateTimeInterface|mixed $end * * @return static */ public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; } /** * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function abs(bool $absolute = false): static { if ($absolute && $this->invert) { $this->invert(); } return $this; } /** * @alias abs * * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function absolute(bool $absolute = true): static { return $this->abs($absolute); } /** * Cast the current instance into the given class. * * @template T of DateInterval * * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { return self::castIntervalToClass($this, $className); } /** * Create a CarbonInterval instance from a DateInterval one. Can not instance * DateInterval objects created from DateTime::diff() as you can't externally * set the $days field. * * @param DateInterval $interval * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static */ public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static { if ($skipCopy && $interval instanceof static) { return $interval; } return self::castIntervalToClass($interval, static::class, $skip); } /** * Make a CarbonInterval instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static|null */ public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); } protected static function makeFromString(string $interval): ?self { $interval = preg_replace('/\s+/', ' ', trim($interval)); if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { return static::fromString($interval); } $intervalInstance = static::createFromDateString($interval); return $intervalInstance->isEmpty() ? null : $intervalInstance; } protected function resolveInterval($interval): ?self { if (!($interval instanceof self)) { return self::make($interval); } return $interval; } /** * Sets up a DateInterval from the relative parts of the string. * * @param string $datetime * * @return static * * @link https://php.net/manual/en/dateinterval.createfromdatestring.php */ public static function createFromDateString(string $datetime): static { $string = strtr($datetime, [ ',' => ' ', ' and ' => ' ', ]); $previousException = null; try { $interval = parent::createFromDateString($string); } catch (Throwable $exception) { $interval = null; $previousException = $exception; } $interval ?: throw new InvalidFormatException( 'Could not create interval from: '.var_export($datetime, true), previous: $previousException, ); if (!($interval instanceof static)) { $interval = static::instance($interval); } return self::withOriginal($interval, $datetime); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the CarbonInterval object. */ public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; } /** * Get a part of the CarbonInterval object. */ public function __get(string $name): int|float|string|null { return $this->get($name); } /** * Set a part of the CarbonInterval object. * * @param Unit|string|array $name * @param int $value * * @throws UnknownSetterException * * @return $this */ public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; } /** * Set a part of the CarbonInterval object. * * @param string $name * @param int $value * * @throws UnknownSetterException */ public function __set(string $name, $value) { $this->set($name, $value); } /** * Allow setting of weeks and days to be cumulative. * * @param int $weeks Number of weeks to set * @param int $days Number of days to set * * @return static */ public function weeksAndDays(int $weeks, int $days): static { $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; return $this; } /** * Returns true if the interval is empty for each unit. * * @return bool */ public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonInterval::macro('twice', function () { * return $this->times(2); * }); * echo CarbonInterval::hours(2)->twice(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonInterval::mixin(new class { * public function daysToHours() { * return function () { * $this->hours += $this->days; * $this->days = 0; * * return $this; * }; * } * public function hoursToDays() { * return function () { * $this->days += $this->hours; * $this->hours = 0; * * return $this; * }; * } * }); * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; * echo CarbonInterval::days(5)->daysToHours() . "\n"; * ``` * * @param object|string $mixin * * @throws ReflectionException * * @return void */ public static function mixin($mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Call given macro. * * @param string $name * @param array $parameters * * @return mixed */ protected function callMacro(string $name, array $parameters) { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadFluentSetterException|Throwable * * @return static|int|float|string */ public function __call(string $method, array $parameters) { if (static::hasMacro($method)) { return static::bindMacroContext($this, function () use (&$method, &$parameters) { return $this->callMacro($method, $parameters); }); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); return $this->{$match['method']}($value, $match['unit']); } $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); try { $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); } } return $this; } protected function getForHumansInitialVariables($syntax, $short): array { if (\is_array($syntax)) { return $syntax; } if (\is_int($short)) { return [ 'parts' => $short, 'short' => false, ]; } if (\is_bool($syntax)) { return [ 'short' => $syntax, 'syntax' => CarbonInterface::DIFF_ABSOLUTE, ]; } return []; } /** * @param mixed $syntax * @param mixed $short * @param mixed $parts * @param mixed $options * * @return array */ protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array { $optionalSpace = ' '; $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; /** @var bool|string $join */ $join = $default === '' ? '' : ' '; /** @var bool|array|string $altNumbers */ $altNumbers = false; $aUnit = false; $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); $skip = array_map( static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit, (array) $skip, ); $skip = array_map( 'strtolower', array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''), ); $syntax ??= CarbonInterface::DIFF_ABSOLUTE; if ($parts === self::NO_LIMIT) { $parts = INF; } $options ??= static::getHumanDiffOptions(); if ($join === false) { $join = ' '; } elseif ($join === true) { $join = [ $default, $this->getTranslationMessage('list.1') ?? $default, ]; } if ($altNumbers && $altNumbers !== true) { $language = new Language($this->locale); $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { [$default, $last] = $join; if ($default !== ' ') { $optionalSpace = ''; } $join = function ($list) use ($default, $last) { if (\count($list) < 2) { return implode('', $list); } $end = array_pop($list); return implode($default, $list).$last.$end; }; } if (\is_string($join)) { if ($join !== ' ') { $optionalSpace = ''; } $glue = $join; $join = static fn ($list) => implode($glue, $list); } $interpolations = [ ':optional-space' => $optionalSpace, ]; $translator ??= isset($locale) ? Translator::get($locale) : null; return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator]; } protected static function getRoundingMethodFromOptions(int $options): ?string { if ($options & CarbonInterface::ROUND) { return 'round'; } if ($options & CarbonInterface::CEIL) { return 'ceil'; } if ($options & CarbonInterface::FLOOR) { return 'floor'; } return null; } /** * Returns interval values as an array where key are the unit names and values the counts. * * @return int[] */ public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; } /** * Returns interval non-zero values as an array where key are the unit names and values the counts. * * @return int[] */ public function getNonZeroValues(): array { return array_filter($this->toArray(), 'intval'); } /** * Returns interval values as an array where key are the unit names and values the counts * from the biggest non-zero one the the smallest non-zero one. * * @return int[] */ public function getValuesSequence(): array { $nonZeroValues = $this->getNonZeroValues(); if ($nonZeroValues === []) { return []; } $keys = array_keys($nonZeroValues); $firstKey = $keys[0]; $lastKey = $keys[\count($keys) - 1]; $values = []; $record = false; foreach ($this->toArray() as $unit => $count) { if ($unit === $firstKey) { $record = true; } if ($record) { $values[$unit] = $count; } if ($unit === $lastKey) { $record = false; } } return $values; } /** * Get the current interval in a human readable format in the current locale. * * @example * ``` * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; * ``` * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: -1: no limits) * @param int $options human diff options * * @throws Exception * * @return string */ public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string { /* @var TranslatorInterface|null $translator */ [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this ->getForHumansParameters($syntax, $short, $parts, $options); $interval = []; $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; $count = 1; $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); $declensionMode = null; $translator ??= $this->getLocalTranslator(); $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); if ($this->needsDeclension($declensionMode, $index, $parts)) { // Some languages have special pluralization for past and future tense. $key = $unit.'_'.$transId; $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); if ($result !== $key) { return $result; } } } $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); if ($result !== $unit) { return $result; } return null; }; $intervalValues = $this; $method = static::getRoundingMethodFromOptions($options); if ($method) { $previousCount = INF; while ( \count($intervalValues->getNonZeroValues()) > $parts && ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 ) { $index = min($count, $previousCount - 1) - 2; if ($index < 0) { break; } $intervalValues = $this->copy()->roundUnit( $keys[$index], 1, $method, ); $previousCount = $count; } } $diffIntervalArray = [ ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], ]; if (!empty($skip)) { foreach ($diffIntervalArray as $index => &$unitData) { $nextIndex = $index + 1; if ($unitData['value'] && isset($diffIntervalArray[$nextIndex]) && \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) ) { $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); $unitData['value'] = 0; } } } $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; } } if (!$absolute) { return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); }; $fallbackUnit = ['second', 's']; foreach ($diffIntervalArray as $diffIntervalData) { if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } // break the loop after we get the required number of parts in array if (\count($interval) >= $parts) { break; } // break the loop after we have reached the minimum unit if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } $actualParts = \count($interval); foreach ($interval as $index => &$item) { $item = $transChoice($item[0], $item[1], $index, $actualParts); } if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; $unit = $fallbackUnit[$short ? 1 : 0]; $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); } // join the interval parts by a space $time = $join($interval); unset($diffIntervalArray, $interval); if ($absolute) { return $time; } $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); if ($parts === 1) { if ($relativeToNow && $unit === 'day') { $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null; if ($specialTranslations && $options & $specialTranslations['option']) { $key = $specialTranslations[$isFuture ? 'future' : 'past']; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } } $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; } $time = [':time' => $time]; return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); } public function format(string $format): string { $output = parent::format($format); if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) { return $output; } $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate); return str_replace('(unknown)', $this->rawInterval->format('%a'), $output); } /** * Format the instance as a string using the forHumans() function. * * @throws Exception * * @return string */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if (!$format) { return $this->forHumans(); } if ($format instanceof Closure) { return $format($this); } return $this->format($format); } /** * Return native DateInterval PHP object matching the current instance. * * @example * ``` * var_dump(CarbonInterval::hours(2)->toDateInterval()); * ``` * * @return DateInterval */ public function toDateInterval(): DateInterval { return self::castIntervalToClass($this, DateInterval::class); } /** * Convert the interval to a CarbonPeriod. * * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. * * @return CarbonPeriod */ public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); } /** * Decompose the current interval into * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); } /** * Invert the interval. * * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this */ public function invert($inverted = null): static { $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; return $this; } protected function solveNegativeInterval(): static { if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { $this->years *= self::NEGATIVE; $this->months *= self::NEGATIVE; $this->dayz *= self::NEGATIVE; $this->hours *= self::NEGATIVE; $this->minutes *= self::NEGATIVE; $this->seconds *= self::NEGATIVE; $this->microseconds *= self::NEGATIVE; $this->invert(); } return $this; } /** * Add the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function sub($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } return $this->add($unit, -(float) $value); } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function subtract($unit, $value = 1): static { return $this->sub($unit, $value); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Multiply current instance given number of times. times() is naive, it multiplies each unit * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded * separately for each unit. * * Use times() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see multiply() * * @param float|int $factor * * @return $this */ public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; } /** * Divide current instance by a given divider. shares() is naive, it divides each unit separately * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours * and 7 minutes. * * Use shares() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see divide() * * @param float|int $divider * * @return $this */ public function shares($divider): static { return $this->times(1 / $divider); } protected function copyProperties(self $interval, $ignoreSign = false): static { $this->years = $interval->years; $this->months = $interval->months; $this->dayz = $interval->dayz; $this->hours = $interval->hours; $this->minutes = $interval->minutes; $this->seconds = $interval->seconds; $this->microseconds = $interval->microseconds; if (!$ignoreSign) { $this->invert = $interval->invert; } return $this; } /** * Multiply and cascade current instance by a given factor. * * @param float|int $factor * * @return $this */ public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); } /** * Divide and cascade current instance by a given divider. * * @param float|int $divider * * @return $this */ public function divide($divider): static { return $this->multiply(1 / $divider); } /** * Get the interval_spec string of a date interval. * * @param DateInterval $interval * * @return string */ public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), static::PERIOD_MONTHS => abs($interval->m), static::PERIOD_DAYS => abs($interval->d), ]); $skip = array_map([Unit::class, 'toNameIfUnit'], $skip); if ( $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) ) { $date = [ static::PERIOD_DAYS => abs($interval->days), ]; } $seconds = abs($interval->s); if ($microseconds && $interval->f > 0) { $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); } $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; foreach ($date as $key => $value) { $specString .= $value.$key; } if (\count($time) > 0) { $specString .= static::PERIOD_TIME_PREFIX; foreach ($time as $key => $value) { $specString .= $value.$key; } } return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; } /** * Get the interval_spec string. * * @return string */ public function spec(bool $microseconds = false): string { return static::getDateIntervalSpec($this, $microseconds); } /** * Comparing 2 date intervals. * * @param DateInterval $first * @param DateInterval $second * * @return int 0, 1 or -1 */ public static function compareDateIntervals(DateInterval $first, DateInterval $second): int { $current = Carbon::now(); $passed = $current->avoidMutation()->add($second); $current->add($first); return $current <=> $passed; } /** * Comparing with passed interval. * * @param DateInterval $interval * * @return int 0, 1 or -1 */ public function compare(DateInterval $interval): int { return static::compareDateIntervals($this, $interval); } /** * Convert overflowed values into bigger units. * * @return $this */ public function cascade(): static { return $this->doCascade(false); } public function hasNegativeValues(): bool { foreach ($this->toArray() as $value) { if ($value < 0) { return true; } } return false; } public function hasPositiveValues(): bool { foreach ($this->toArray() as $value) { if ($value > 0) { return true; } } return false; } /** * Get amount of given unit equivalent to the interval. * * @param string $unit * * @throws UnknownUnitException|UnitNotConfiguredException * * @return float */ public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see equalTo() * * @return bool */ public function eq($interval): bool { return $this->equalTo($interval); } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see notEqualTo() * * @return bool */ public function ne($interval): bool { return $this->notEqualTo($interval); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function notEqualTo($interval): bool { return !$this->eq($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThan() * * @return bool */ public function gt($interval): bool { return $this->greaterThan($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThanOrEqualTo() * * @return bool */ public function gte($interval): bool { return $this->greaterThanOrEqualTo($interval); } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThanOrEqualTo($interval): bool { return $this->greaterThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThan() * * @return bool */ public function lt($interval): bool { return $this->lessThan($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThanOrEqualTo() * * @return bool */ public function lte($interval): bool { return $this->lessThanOrEqualTo($interval); } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThanOrEqualTo($interval): bool { return $this->lessThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function between($interval1, $interval2, bool $equal = true): bool { return $equal ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) : $this->greaterThan($interval1) && $this->lessThan($interval2); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenIncluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenExcluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, false); } /** * Determines if the instance is between two others * * @example * ``` * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function isBetween($interval1, $interval2, bool $equal = true): bool { return $this->between($interval1, $interval2, $equal); } /** * Round the current instance at the given unit with given precision if specified and the given function. * * @throws Exception */ public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); } /** * Truncate the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function floorUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function ceilUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified. * * @param float|int|string|DateInterval|null $precision * @param string $function * * @throws Exception * * @return $this */ public function round($precision = 1, string $function = 'round'): static { return $this->roundWith($precision, $function); } /** * Round the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function floor(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function ceil(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'ceil'); } public function __unserialize(array $data): void { $properties = array_combine( array_map( static fn (mixed $key) => \is_string($key) ? str_replace('tzName', 'timezoneSetting', $key) : $key, array_keys($data), ), $data, ); if (method_exists(parent::class, '__unserialize')) { // PHP >= 8.2 parent::__unserialize($properties); return; } // PHP <= 8.1 // @codeCoverageIgnoreStart $properties = array_combine( array_map( static fn (string $property) => preg_replace('/^\0.+\0/', '', $property), array_keys($data), ), $data, ); $localStrictMode = $this->localStrictModeEnabled; $this->localStrictModeEnabled = false; $days = $properties['days'] ?? false; $this->days = $days === false ? false : (int) $days; $this->y = (int) ($properties['y'] ?? 0); $this->m = (int) ($properties['m'] ?? 0); $this->d = (int) ($properties['d'] ?? 0); $this->h = (int) ($properties['h'] ?? 0); $this->i = (int) ($properties['i'] ?? 0); $this->s = (int) ($properties['s'] ?? 0); $this->f = (float) ($properties['f'] ?? 0.0); // @phpstan-ignore-next-line $this->weekday = (int) ($properties['weekday'] ?? 0); // @phpstan-ignore-next-line $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0); // @phpstan-ignore-next-line $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0); $this->invert = (int) ($properties['invert'] ?? 0); // @phpstan-ignore-next-line $this->special_type = (int) ($properties['special_type'] ?? 0); // @phpstan-ignore-next-line $this->special_amount = (int) ($properties['special_amount'] ?? 0); // @phpstan-ignore-next-line $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0); // @phpstan-ignore-next-line $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0); parent::__construct(self::getDateIntervalSpec($this)); foreach ($properties as $property => $value) { if ($property === 'localStrictModeEnabled') { continue; } $this->$property = $value; } $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode; // @codeCoverageIgnoreEnd } /** * @template T * * @param T $interval * @param mixed $original * * @return T */ private static function withOriginal(mixed $interval, mixed $original): mixed { if ($interval instanceof self) { $interval->originalInput = $original; } return $interval; } private static function standardizeUnit(string $unit): string { $unit = rtrim($unit, 'sz').'s'; return $unit === 'days' ? 'dayz' : $unit; } private static function getFlipCascadeFactors(): array { if (!self::$flipCascadeFactors) { self::$flipCascadeFactors = []; foreach (self::getCascadeFactors() as $to => [$factor, $from]) { self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; } } return self::$flipCascadeFactors; } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object { $mainClass = DateInterval::class; if (!is_a($className, $mainClass, true)) { throw new InvalidCastException("$className is not a sub-class of $mainClass."); } $microseconds = $interval->f; $instance = self::buildInstance($interval, $className, $skip); if ($instance instanceof self) { $instance->originalInput = $interval; } if ($microseconds) { $instance->f = $microseconds; } if ($interval instanceof self && is_a($className, self::class, true)) { self::copyStep($interval, $instance); } self::copyNegativeUnits($interval, $instance); return self::withOriginal($instance, $interval); } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function buildInstance( DateInterval $interval, string $className, array $skip = [], ): object { $serialization = self::buildSerializationString($interval, $className, $skip); return match ($serialization) { null => new $className(static::getDateIntervalSpec($interval, false, $skip)), default => unserialize($serialization), }; } /** * As demonstrated by rlanvin (https://github.com/rlanvin) in * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438 * * Modifying the output of serialize() to change the class name and unserializing * the tweaked string allows creating new interval instances where the ->days * property can be set. It's not possible neither with `new` nto with `__set_state`. * * It has a non-negligible performance cost, so we'll use this method only if * $interval->days !== false. */ private static function buildSerializationString( DateInterval $interval, string $className, array $skip = [], ): ?string { if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) { return null; } // De-enhance CarbonInterval objects to be serializable back to DateInterval if ($interval instanceof self && !is_a($className, self::class, true)) { $interval = clone $interval; unset($interval->timezoneSetting); unset($interval->originalInput); unset($interval->startDate); unset($interval->endDate); unset($interval->rawInterval); unset($interval->absolute); unset($interval->initialValues); unset($interval->clock); unset($interval->step); unset($interval->localMonthsOverflow); unset($interval->localYearsOverflow); unset($interval->localStrictModeEnabled); unset($interval->localHumanDiffOptions); unset($interval->localToStringFormat); unset($interval->localSerializer); unset($interval->localMacros); unset($interval->localGenericMacros); unset($interval->localFormatFunction); unset($interval->localTranslator); } $serialization = serialize($interval); $inputClass = $interval::class; $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":'; if (!str_starts_with($serialization, $expectedStart)) { return null; // @codeCoverageIgnore } return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart)); } private static function copyStep(self $from, self $to): void { $to->setStep($from->getStep()); } private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void { $to->invert = $from->invert; foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { if ($from->$unit < 0) { self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE); } } } private function invertCascade(array $values): static { return $this->set(array_map(function ($value) { return -$value; }, $values))->doCascade(true)->invert(); } private function doCascade(bool $deep): static { $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { if ($$key === 'dayz') { $$key = 'daysExcludeWeeks'; } } $value = $newData[$source]; $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; $decimalPart = fmod($newData[$source], 1); if ($decimalPart !== 0.0) { $unit = $source; foreach ($previous as [$subUnit, $subFactor]) { $newData[$unit] -= $decimalPart; $newData[$subUnit] += $decimalPart * $subFactor; $decimalPart = fmod($newData[$subUnit], 1); if ($decimalPart === 0.0) { break; } $unit = $subUnit; } } array_unshift($previous, [$source, $factor]); } $positive = null; if (!$deep) { foreach ($newData as $value) { if ($value) { if ($positive === null) { $positive = ($value > 0); continue; } if (($value > 0) !== $positive) { return $this->invertCascade($originalData) ->solveNegativeInterval(); } } } } return $this->set($newData) ->solveNegativeInterval(); } private function needsDeclension(string $mode, int $index, int $parts): bool { return match ($mode) { 'last' => $index === $parts - 1, default => true, }; } private function checkIntegerValue(string $name, mixed $value): void { if (\is_int($value)) { return; } $this->assertSafeForInteger($name, $value); if (\is_float($value) && (((float) (int) $value) === $value)) { return; } if (!self::$floatSettersEnabled) { $type = \gettype($value); @trigger_error( "Since 2.70.0, it's deprecated to pass $type value for $name.\n". "It's truncated when stored as an integer interval unit.\n". "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", \E_USER_DEPRECATED, ); } } /** * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. */ private function assertSafeForInteger(string $name, mixed $value): void { if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); } } private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void { if (self::$floatSettersEnabled) { $floatValue = (float) $value; $base = (float) $integerValue; if ($floatValue === $base) { return; } $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; $upper = true; foreach ($units as $property => $name) { if ($name === $unit) { $upper = false; continue; } if (!$upper && $this->$property !== 0) { throw new RuntimeException( "You cannot set $unit to a float value as $name would be overridden, ". 'set it first to 0 explicitly if you really want to erase its value' ); } } $this->add($unit, $floatValue - $base); } } private function getInnerValues(): array { return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days]; } private function checkStartAndEnd(): void { if ( $this->initialValues !== null && ($this->startDate !== null || $this->endDate !== null) && $this->initialValues !== $this->getInnerValues() ) { $this->absolute = false; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; } } /** @return $this */ private function setSetting(string $setting, mixed $value): self { switch ($setting) { case 'timezoneSetting': return $value === null ? $this : $this->setTimezone($value); case 'step': $this->setStep($value); return $this; case 'localMonthsOverflow': return $value === null ? $this : $this->settings(['monthOverflow' => $value]); case 'localYearsOverflow': return $value === null ? $this : $this->settings(['yearOverflow' => $value]); case 'localStrictModeEnabled': case 'localHumanDiffOptions': case 'localToStringFormat': case 'localSerializer': case 'localMacros': case 'localGenericMacros': case 'localFormatFunction': case 'localTranslator': $this->$setting = $value; return $this; default: // Drop unknown settings return $this; } } private static function incrementUnit(DateInterval $instance, string $unit, int $value): void { if ($value === 0) { return; } // @codeCoverageIgnoreStart if (PHP_VERSION_ID !== 8_03_20) { $instance->$unit += $value; return; } // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value); // @codeCoverageIgnoreEnd } /** @codeCoverageIgnore */ private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void { switch ($unit) { case 'y': $instance->y = $value; break; case 'm': $instance->m = $value; break; case 'd': $instance->d = $value; break; case 'h': $instance->h = $value; break; case 'i': $instance->i = $value; break; case 's': $instance->s = $value; break; default: $instance->$unit = $value; } } }
PHP
{ "end_line": 2266, "name": "add", "signature": "public function add($unit, $value = 1): static", "start_line": 2233 }
{ "class_name": "CarbonInterval", "class_signature": "class CarbonInterval implements CarbonConverterInterface, UnitValue", "namespace": "Carbon" }
plus
Carbon/src/Carbon/CarbonInterval.php
public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH], 'day' => ['week' => Carbon::DAYS_PER_WEEK], 'hour' => ['day' => Carbon::HOURS_PER_DAY], 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], ]; return $defaults[$source][$target] ?? null; } /** * Returns current config for days per week. * * @return int|float */ public static function getDaysPerWeek() { return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; } /** * Returns current config for hours per day. * * @return int|float */ public static function getHoursPerDay() { return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; } /** * Returns current config for minutes per hour. * * @return int|float */ public static function getMinutesPerHour() { return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; } /** * Returns current config for seconds per minute. * * @return int|float */ public static function getSecondsPerMinute() { return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMillisecondsPerSecond() { return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMicrosecondsPerMillisecond() { return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; } /** * Create a new CarbonInterval instance from specific values. * This is an alias for the constructor that allows better fluent * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than * (new CarbonInterval(1))->fn(). * * @param int $years * @param int $months * @param int $weeks * @param int $days * @param int $hours * @param int $minutes * @param int $seconds * @param int $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. * * @return static */ public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); } /** * Parse a string into a new CarbonInterval object according to the specified format. * * @example * ``` * echo Carboninterval::createFromFormat('H:i', '1:30'); * ``` * * @param string $format Format of the $interval input string * @param string|null $interval Input string to convert into an interval * * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. * * @return static */ public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; } /** * Return the original source used to create the current interval. * * @return array|int|string|DateInterval|mixed|null */ public function original() { return $this->originalInput; } /** * Return the start date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function start(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->startDate; } /** * Return the end date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function end(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->endDate; } /** * Get rid of the original input, start date and end date that may be kept in memory. * * @return $this */ public function optimize(): static { $this->originalInput = null; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; $this->absolute = false; return $this; } /** * Get a copy of the instance. * * @return static */ public function copy(): static { $date = new static(0); $date->copyProperties($this); $date->step = $this->step; return $date; } /** * Get a copy of the instance. * * @return static */ public function clone(): static { return $this->copy(); } /** * Provide static helpers to create instances. Allows CarbonInterval::years(3). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @return static|mixed|null */ public static function __callStatic(string $method, array $parameters) { try { $interval = new static(0); $localStrictModeEnabled = $interval->localStrictModeEnabled; $interval->localStrictModeEnabled = true; $result = static::hasMacro($method) ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { return $interval->callMacro($method, $parameters); }) : $interval->$method(...$parameters); $interval->localStrictModeEnabled = $localStrictModeEnabled; return $result; } catch (BadFluentSetterException $exception) { if (Carbon::isStrictModeEnabled()) { throw new BadFluentConstructorException($method, 0, $exception); } return null; } } /** * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. * * @param array $dump data as exported by var_export() * * @return static */ #[ReturnTypeWillChange] public static function __set_state($dump) { /** @noinspection PhpVoidFunctionResultUsedInspection */ /** @var DateInterval $dateInterval */ $dateInterval = parent::__set_state($dump); return static::instance($dateInterval); } /** * Return the current context from inside a macro callee or a new one if static. * * @return static */ protected static function this(): static { return end(static::$macroContextStack) ?: new static(0); } /** * Creates a CarbonInterval from string. * * Format: * * Suffix | Unit | Example | DateInterval expression * -------|---------|---------|------------------------ * y | years | 1y | P1Y * mo | months | 3mo | P3M * w | weeks | 2w | P2W * d | days | 28d | P28D * h | hours | 4h | PT4H * m | minutes | 12m | PT12M * s | seconds | 59s | PT59S * * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. * * Special cases: * - An empty string will return a zero interval * - Fractions are allowed for weeks, days, hours and minutes and will be converted * and rounded to the next smaller value (caution: 0.5w = 4d) * * @param string $intervalDefinition * * @throws InvalidIntervalException * * @return static */ public static function fromString(string $intervalDefinition): static { if (empty($intervalDefinition)) { return self::withOriginal(new static(0), $intervalDefinition); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $milliseconds = 0; $microseconds = 0; $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ([$part, $value, $unit] = array_shift($parts)) { $intValue = (int) $value; $fraction = (float) $value - $intValue; // Fix calculation precision switch (round($fraction, 6)) { case 1: $fraction = 0; $intValue++; break; case 0: $fraction = 0; break; } switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { case 'millennia': case 'millennium': $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; break; case 'century': case 'centuries': $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; break; case 'decade': case 'decades': $years += $intValue * CarbonInterface::YEARS_PER_DECADE; break; case 'year': case 'years': case 'y': case 'yr': case 'yrs': $years += $intValue; break; case 'quarter': case 'quarters': $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; break; case 'month': case 'months': case 'mo': case 'mos': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; } break; case 'second': case 'seconds': case 's': $seconds += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; } break; case 'millisecond': case 'milliseconds': case 'milli': case 'ms': $milliseconds += $intValue; if ($fraction) { $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); } break; case 'microsecond': case 'microseconds': case 'micro': case 'µs': $microseconds += $intValue; break; default: throw new InvalidIntervalException( "Invalid part $part in definition $intervalDefinition", ); } } return self::withOriginal( new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds), $intervalDefinition, ); } /** * Creates a CarbonInterval from string using a different locale. * * @param string $interval interval string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be used instead. * * @return static */ public static function parseFromLocale(string $interval, ?string $locale = null): static { return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE)); } /** * Create an interval from the difference between 2 dates. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $start * @param \Carbon\Carbon|\DateTimeInterface|mixed $end * * @return static */ public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; } /** * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function abs(bool $absolute = false): static { if ($absolute && $this->invert) { $this->invert(); } return $this; } /** * @alias abs * * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function absolute(bool $absolute = true): static { return $this->abs($absolute); } /** * Cast the current instance into the given class. * * @template T of DateInterval * * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { return self::castIntervalToClass($this, $className); } /** * Create a CarbonInterval instance from a DateInterval one. Can not instance * DateInterval objects created from DateTime::diff() as you can't externally * set the $days field. * * @param DateInterval $interval * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static */ public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static { if ($skipCopy && $interval instanceof static) { return $interval; } return self::castIntervalToClass($interval, static::class, $skip); } /** * Make a CarbonInterval instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static|null */ public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); } protected static function makeFromString(string $interval): ?self { $interval = preg_replace('/\s+/', ' ', trim($interval)); if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { return static::fromString($interval); } $intervalInstance = static::createFromDateString($interval); return $intervalInstance->isEmpty() ? null : $intervalInstance; } protected function resolveInterval($interval): ?self { if (!($interval instanceof self)) { return self::make($interval); } return $interval; } /** * Sets up a DateInterval from the relative parts of the string. * * @param string $datetime * * @return static * * @link https://php.net/manual/en/dateinterval.createfromdatestring.php */ public static function createFromDateString(string $datetime): static { $string = strtr($datetime, [ ',' => ' ', ' and ' => ' ', ]); $previousException = null; try { $interval = parent::createFromDateString($string); } catch (Throwable $exception) { $interval = null; $previousException = $exception; } $interval ?: throw new InvalidFormatException( 'Could not create interval from: '.var_export($datetime, true), previous: $previousException, ); if (!($interval instanceof static)) { $interval = static::instance($interval); } return self::withOriginal($interval, $datetime); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the CarbonInterval object. */ public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; } /** * Get a part of the CarbonInterval object. */ public function __get(string $name): int|float|string|null { return $this->get($name); } /** * Set a part of the CarbonInterval object. * * @param Unit|string|array $name * @param int $value * * @throws UnknownSetterException * * @return $this */ public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; } /** * Set a part of the CarbonInterval object. * * @param string $name * @param int $value * * @throws UnknownSetterException */ public function __set(string $name, $value) { $this->set($name, $value); } /** * Allow setting of weeks and days to be cumulative. * * @param int $weeks Number of weeks to set * @param int $days Number of days to set * * @return static */ public function weeksAndDays(int $weeks, int $days): static { $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; return $this; } /** * Returns true if the interval is empty for each unit. * * @return bool */ public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonInterval::macro('twice', function () { * return $this->times(2); * }); * echo CarbonInterval::hours(2)->twice(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonInterval::mixin(new class { * public function daysToHours() { * return function () { * $this->hours += $this->days; * $this->days = 0; * * return $this; * }; * } * public function hoursToDays() { * return function () { * $this->days += $this->hours; * $this->hours = 0; * * return $this; * }; * } * }); * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; * echo CarbonInterval::days(5)->daysToHours() . "\n"; * ``` * * @param object|string $mixin * * @throws ReflectionException * * @return void */ public static function mixin($mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Call given macro. * * @param string $name * @param array $parameters * * @return mixed */ protected function callMacro(string $name, array $parameters) { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadFluentSetterException|Throwable * * @return static|int|float|string */ public function __call(string $method, array $parameters) { if (static::hasMacro($method)) { return static::bindMacroContext($this, function () use (&$method, &$parameters) { return $this->callMacro($method, $parameters); }); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); return $this->{$match['method']}($value, $match['unit']); } $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); try { $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); } } return $this; } protected function getForHumansInitialVariables($syntax, $short): array { if (\is_array($syntax)) { return $syntax; } if (\is_int($short)) { return [ 'parts' => $short, 'short' => false, ]; } if (\is_bool($syntax)) { return [ 'short' => $syntax, 'syntax' => CarbonInterface::DIFF_ABSOLUTE, ]; } return []; } /** * @param mixed $syntax * @param mixed $short * @param mixed $parts * @param mixed $options * * @return array */ protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array { $optionalSpace = ' '; $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; /** @var bool|string $join */ $join = $default === '' ? '' : ' '; /** @var bool|array|string $altNumbers */ $altNumbers = false; $aUnit = false; $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); $skip = array_map( static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit, (array) $skip, ); $skip = array_map( 'strtolower', array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''), ); $syntax ??= CarbonInterface::DIFF_ABSOLUTE; if ($parts === self::NO_LIMIT) { $parts = INF; } $options ??= static::getHumanDiffOptions(); if ($join === false) { $join = ' '; } elseif ($join === true) { $join = [ $default, $this->getTranslationMessage('list.1') ?? $default, ]; } if ($altNumbers && $altNumbers !== true) { $language = new Language($this->locale); $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { [$default, $last] = $join; if ($default !== ' ') { $optionalSpace = ''; } $join = function ($list) use ($default, $last) { if (\count($list) < 2) { return implode('', $list); } $end = array_pop($list); return implode($default, $list).$last.$end; }; } if (\is_string($join)) { if ($join !== ' ') { $optionalSpace = ''; } $glue = $join; $join = static fn ($list) => implode($glue, $list); } $interpolations = [ ':optional-space' => $optionalSpace, ]; $translator ??= isset($locale) ? Translator::get($locale) : null; return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator]; } protected static function getRoundingMethodFromOptions(int $options): ?string { if ($options & CarbonInterface::ROUND) { return 'round'; } if ($options & CarbonInterface::CEIL) { return 'ceil'; } if ($options & CarbonInterface::FLOOR) { return 'floor'; } return null; } /** * Returns interval values as an array where key are the unit names and values the counts. * * @return int[] */ public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; } /** * Returns interval non-zero values as an array where key are the unit names and values the counts. * * @return int[] */ public function getNonZeroValues(): array { return array_filter($this->toArray(), 'intval'); } /** * Returns interval values as an array where key are the unit names and values the counts * from the biggest non-zero one the the smallest non-zero one. * * @return int[] */ public function getValuesSequence(): array { $nonZeroValues = $this->getNonZeroValues(); if ($nonZeroValues === []) { return []; } $keys = array_keys($nonZeroValues); $firstKey = $keys[0]; $lastKey = $keys[\count($keys) - 1]; $values = []; $record = false; foreach ($this->toArray() as $unit => $count) { if ($unit === $firstKey) { $record = true; } if ($record) { $values[$unit] = $count; } if ($unit === $lastKey) { $record = false; } } return $values; } /** * Get the current interval in a human readable format in the current locale. * * @example * ``` * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; * ``` * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: -1: no limits) * @param int $options human diff options * * @throws Exception * * @return string */ public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string { /* @var TranslatorInterface|null $translator */ [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this ->getForHumansParameters($syntax, $short, $parts, $options); $interval = []; $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; $count = 1; $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); $declensionMode = null; $translator ??= $this->getLocalTranslator(); $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); if ($this->needsDeclension($declensionMode, $index, $parts)) { // Some languages have special pluralization for past and future tense. $key = $unit.'_'.$transId; $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); if ($result !== $key) { return $result; } } } $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); if ($result !== $unit) { return $result; } return null; }; $intervalValues = $this; $method = static::getRoundingMethodFromOptions($options); if ($method) { $previousCount = INF; while ( \count($intervalValues->getNonZeroValues()) > $parts && ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 ) { $index = min($count, $previousCount - 1) - 2; if ($index < 0) { break; } $intervalValues = $this->copy()->roundUnit( $keys[$index], 1, $method, ); $previousCount = $count; } } $diffIntervalArray = [ ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], ]; if (!empty($skip)) { foreach ($diffIntervalArray as $index => &$unitData) { $nextIndex = $index + 1; if ($unitData['value'] && isset($diffIntervalArray[$nextIndex]) && \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) ) { $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); $unitData['value'] = 0; } } } $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; } } if (!$absolute) { return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); }; $fallbackUnit = ['second', 's']; foreach ($diffIntervalArray as $diffIntervalData) { if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } // break the loop after we get the required number of parts in array if (\count($interval) >= $parts) { break; } // break the loop after we have reached the minimum unit if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } $actualParts = \count($interval); foreach ($interval as $index => &$item) { $item = $transChoice($item[0], $item[1], $index, $actualParts); } if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; $unit = $fallbackUnit[$short ? 1 : 0]; $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); } // join the interval parts by a space $time = $join($interval); unset($diffIntervalArray, $interval); if ($absolute) { return $time; } $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); if ($parts === 1) { if ($relativeToNow && $unit === 'day') { $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null; if ($specialTranslations && $options & $specialTranslations['option']) { $key = $specialTranslations[$isFuture ? 'future' : 'past']; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } } $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; } $time = [':time' => $time]; return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); } public function format(string $format): string { $output = parent::format($format); if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) { return $output; } $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate); return str_replace('(unknown)', $this->rawInterval->format('%a'), $output); } /** * Format the instance as a string using the forHumans() function. * * @throws Exception * * @return string */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if (!$format) { return $this->forHumans(); } if ($format instanceof Closure) { return $format($this); } return $this->format($format); } /** * Return native DateInterval PHP object matching the current instance. * * @example * ``` * var_dump(CarbonInterval::hours(2)->toDateInterval()); * ``` * * @return DateInterval */ public function toDateInterval(): DateInterval { return self::castIntervalToClass($this, DateInterval::class); } /** * Convert the interval to a CarbonPeriod. * * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. * * @return CarbonPeriod */ public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); } /** * Decompose the current interval into * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); } /** * Invert the interval. * * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this */ public function invert($inverted = null): static { $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; return $this; } protected function solveNegativeInterval(): static { if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { $this->years *= self::NEGATIVE; $this->months *= self::NEGATIVE; $this->dayz *= self::NEGATIVE; $this->hours *= self::NEGATIVE; $this->minutes *= self::NEGATIVE; $this->seconds *= self::NEGATIVE; $this->microseconds *= self::NEGATIVE; $this->invert(); } return $this; } /** * Add the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function sub($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } return $this->add($unit, -(float) $value); } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function subtract($unit, $value = 1): static { return $this->sub($unit, $value); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Multiply current instance given number of times. times() is naive, it multiplies each unit * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded * separately for each unit. * * Use times() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see multiply() * * @param float|int $factor * * @return $this */ public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; } /** * Divide current instance by a given divider. shares() is naive, it divides each unit separately * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours * and 7 minutes. * * Use shares() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see divide() * * @param float|int $divider * * @return $this */ public function shares($divider): static { return $this->times(1 / $divider); } protected function copyProperties(self $interval, $ignoreSign = false): static { $this->years = $interval->years; $this->months = $interval->months; $this->dayz = $interval->dayz; $this->hours = $interval->hours; $this->minutes = $interval->minutes; $this->seconds = $interval->seconds; $this->microseconds = $interval->microseconds; if (!$ignoreSign) { $this->invert = $interval->invert; } return $this; } /** * Multiply and cascade current instance by a given factor. * * @param float|int $factor * * @return $this */ public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); } /** * Divide and cascade current instance by a given divider. * * @param float|int $divider * * @return $this */ public function divide($divider): static { return $this->multiply(1 / $divider); } /** * Get the interval_spec string of a date interval. * * @param DateInterval $interval * * @return string */ public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), static::PERIOD_MONTHS => abs($interval->m), static::PERIOD_DAYS => abs($interval->d), ]); $skip = array_map([Unit::class, 'toNameIfUnit'], $skip); if ( $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) ) { $date = [ static::PERIOD_DAYS => abs($interval->days), ]; } $seconds = abs($interval->s); if ($microseconds && $interval->f > 0) { $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); } $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; foreach ($date as $key => $value) { $specString .= $value.$key; } if (\count($time) > 0) { $specString .= static::PERIOD_TIME_PREFIX; foreach ($time as $key => $value) { $specString .= $value.$key; } } return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; } /** * Get the interval_spec string. * * @return string */ public function spec(bool $microseconds = false): string { return static::getDateIntervalSpec($this, $microseconds); } /** * Comparing 2 date intervals. * * @param DateInterval $first * @param DateInterval $second * * @return int 0, 1 or -1 */ public static function compareDateIntervals(DateInterval $first, DateInterval $second): int { $current = Carbon::now(); $passed = $current->avoidMutation()->add($second); $current->add($first); return $current <=> $passed; } /** * Comparing with passed interval. * * @param DateInterval $interval * * @return int 0, 1 or -1 */ public function compare(DateInterval $interval): int { return static::compareDateIntervals($this, $interval); } /** * Convert overflowed values into bigger units. * * @return $this */ public function cascade(): static { return $this->doCascade(false); } public function hasNegativeValues(): bool { foreach ($this->toArray() as $value) { if ($value < 0) { return true; } } return false; } public function hasPositiveValues(): bool { foreach ($this->toArray() as $value) { if ($value > 0) { return true; } } return false; } /** * Get amount of given unit equivalent to the interval. * * @param string $unit * * @throws UnknownUnitException|UnitNotConfiguredException * * @return float */ public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see equalTo() * * @return bool */ public function eq($interval): bool { return $this->equalTo($interval); } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see notEqualTo() * * @return bool */ public function ne($interval): bool { return $this->notEqualTo($interval); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function notEqualTo($interval): bool { return !$this->eq($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThan() * * @return bool */ public function gt($interval): bool { return $this->greaterThan($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThanOrEqualTo() * * @return bool */ public function gte($interval): bool { return $this->greaterThanOrEqualTo($interval); } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThanOrEqualTo($interval): bool { return $this->greaterThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThan() * * @return bool */ public function lt($interval): bool { return $this->lessThan($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThanOrEqualTo() * * @return bool */ public function lte($interval): bool { return $this->lessThanOrEqualTo($interval); } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThanOrEqualTo($interval): bool { return $this->lessThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function between($interval1, $interval2, bool $equal = true): bool { return $equal ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) : $this->greaterThan($interval1) && $this->lessThan($interval2); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenIncluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenExcluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, false); } /** * Determines if the instance is between two others * * @example * ``` * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function isBetween($interval1, $interval2, bool $equal = true): bool { return $this->between($interval1, $interval2, $equal); } /** * Round the current instance at the given unit with given precision if specified and the given function. * * @throws Exception */ public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); } /** * Truncate the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function floorUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function ceilUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified. * * @param float|int|string|DateInterval|null $precision * @param string $function * * @throws Exception * * @return $this */ public function round($precision = 1, string $function = 'round'): static { return $this->roundWith($precision, $function); } /** * Round the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function floor(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function ceil(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'ceil'); } public function __unserialize(array $data): void { $properties = array_combine( array_map( static fn (mixed $key) => \is_string($key) ? str_replace('tzName', 'timezoneSetting', $key) : $key, array_keys($data), ), $data, ); if (method_exists(parent::class, '__unserialize')) { // PHP >= 8.2 parent::__unserialize($properties); return; } // PHP <= 8.1 // @codeCoverageIgnoreStart $properties = array_combine( array_map( static fn (string $property) => preg_replace('/^\0.+\0/', '', $property), array_keys($data), ), $data, ); $localStrictMode = $this->localStrictModeEnabled; $this->localStrictModeEnabled = false; $days = $properties['days'] ?? false; $this->days = $days === false ? false : (int) $days; $this->y = (int) ($properties['y'] ?? 0); $this->m = (int) ($properties['m'] ?? 0); $this->d = (int) ($properties['d'] ?? 0); $this->h = (int) ($properties['h'] ?? 0); $this->i = (int) ($properties['i'] ?? 0); $this->s = (int) ($properties['s'] ?? 0); $this->f = (float) ($properties['f'] ?? 0.0); // @phpstan-ignore-next-line $this->weekday = (int) ($properties['weekday'] ?? 0); // @phpstan-ignore-next-line $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0); // @phpstan-ignore-next-line $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0); $this->invert = (int) ($properties['invert'] ?? 0); // @phpstan-ignore-next-line $this->special_type = (int) ($properties['special_type'] ?? 0); // @phpstan-ignore-next-line $this->special_amount = (int) ($properties['special_amount'] ?? 0); // @phpstan-ignore-next-line $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0); // @phpstan-ignore-next-line $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0); parent::__construct(self::getDateIntervalSpec($this)); foreach ($properties as $property => $value) { if ($property === 'localStrictModeEnabled') { continue; } $this->$property = $value; } $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode; // @codeCoverageIgnoreEnd } /** * @template T * * @param T $interval * @param mixed $original * * @return T */ private static function withOriginal(mixed $interval, mixed $original): mixed { if ($interval instanceof self) { $interval->originalInput = $original; } return $interval; } private static function standardizeUnit(string $unit): string { $unit = rtrim($unit, 'sz').'s'; return $unit === 'days' ? 'dayz' : $unit; } private static function getFlipCascadeFactors(): array { if (!self::$flipCascadeFactors) { self::$flipCascadeFactors = []; foreach (self::getCascadeFactors() as $to => [$factor, $from]) { self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; } } return self::$flipCascadeFactors; } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object { $mainClass = DateInterval::class; if (!is_a($className, $mainClass, true)) { throw new InvalidCastException("$className is not a sub-class of $mainClass."); } $microseconds = $interval->f; $instance = self::buildInstance($interval, $className, $skip); if ($instance instanceof self) { $instance->originalInput = $interval; } if ($microseconds) { $instance->f = $microseconds; } if ($interval instanceof self && is_a($className, self::class, true)) { self::copyStep($interval, $instance); } self::copyNegativeUnits($interval, $instance); return self::withOriginal($instance, $interval); } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function buildInstance( DateInterval $interval, string $className, array $skip = [], ): object { $serialization = self::buildSerializationString($interval, $className, $skip); return match ($serialization) { null => new $className(static::getDateIntervalSpec($interval, false, $skip)), default => unserialize($serialization), }; } /** * As demonstrated by rlanvin (https://github.com/rlanvin) in * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438 * * Modifying the output of serialize() to change the class name and unserializing * the tweaked string allows creating new interval instances where the ->days * property can be set. It's not possible neither with `new` nto with `__set_state`. * * It has a non-negligible performance cost, so we'll use this method only if * $interval->days !== false. */ private static function buildSerializationString( DateInterval $interval, string $className, array $skip = [], ): ?string { if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) { return null; } // De-enhance CarbonInterval objects to be serializable back to DateInterval if ($interval instanceof self && !is_a($className, self::class, true)) { $interval = clone $interval; unset($interval->timezoneSetting); unset($interval->originalInput); unset($interval->startDate); unset($interval->endDate); unset($interval->rawInterval); unset($interval->absolute); unset($interval->initialValues); unset($interval->clock); unset($interval->step); unset($interval->localMonthsOverflow); unset($interval->localYearsOverflow); unset($interval->localStrictModeEnabled); unset($interval->localHumanDiffOptions); unset($interval->localToStringFormat); unset($interval->localSerializer); unset($interval->localMacros); unset($interval->localGenericMacros); unset($interval->localFormatFunction); unset($interval->localTranslator); } $serialization = serialize($interval); $inputClass = $interval::class; $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":'; if (!str_starts_with($serialization, $expectedStart)) { return null; // @codeCoverageIgnore } return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart)); } private static function copyStep(self $from, self $to): void { $to->setStep($from->getStep()); } private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void { $to->invert = $from->invert; foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { if ($from->$unit < 0) { self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE); } } } private function invertCascade(array $values): static { return $this->set(array_map(function ($value) { return -$value; }, $values))->doCascade(true)->invert(); } private function doCascade(bool $deep): static { $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { if ($$key === 'dayz') { $$key = 'daysExcludeWeeks'; } } $value = $newData[$source]; $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; $decimalPart = fmod($newData[$source], 1); if ($decimalPart !== 0.0) { $unit = $source; foreach ($previous as [$subUnit, $subFactor]) { $newData[$unit] -= $decimalPart; $newData[$subUnit] += $decimalPart * $subFactor; $decimalPart = fmod($newData[$subUnit], 1); if ($decimalPart === 0.0) { break; } $unit = $subUnit; } } array_unshift($previous, [$source, $factor]); } $positive = null; if (!$deep) { foreach ($newData as $value) { if ($value) { if ($positive === null) { $positive = ($value > 0); continue; } if (($value > 0) !== $positive) { return $this->invertCascade($originalData) ->solveNegativeInterval(); } } } } return $this->set($newData) ->solveNegativeInterval(); } private function needsDeclension(string $mode, int $index, int $parts): bool { return match ($mode) { 'last' => $index === $parts - 1, default => true, }; } private function checkIntegerValue(string $name, mixed $value): void { if (\is_int($value)) { return; } $this->assertSafeForInteger($name, $value); if (\is_float($value) && (((float) (int) $value) === $value)) { return; } if (!self::$floatSettersEnabled) { $type = \gettype($value); @trigger_error( "Since 2.70.0, it's deprecated to pass $type value for $name.\n". "It's truncated when stored as an integer interval unit.\n". "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", \E_USER_DEPRECATED, ); } } /** * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. */ private function assertSafeForInteger(string $name, mixed $value): void { if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); } } private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void { if (self::$floatSettersEnabled) { $floatValue = (float) $value; $base = (float) $integerValue; if ($floatValue === $base) { return; } $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; $upper = true; foreach ($units as $property => $name) { if ($name === $unit) { $upper = false; continue; } if (!$upper && $this->$property !== 0) { throw new RuntimeException( "You cannot set $unit to a float value as $name would be overridden, ". 'set it first to 0 explicitly if you really want to erase its value' ); } } $this->add($unit, $floatValue - $base); } } private function getInnerValues(): array { return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days]; } private function checkStartAndEnd(): void { if ( $this->initialValues !== null && ($this->startDate !== null || $this->endDate !== null) && $this->initialValues !== $this->getInnerValues() ) { $this->absolute = false; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; } } /** @return $this */ private function setSetting(string $setting, mixed $value): self { switch ($setting) { case 'timezoneSetting': return $value === null ? $this : $this->setTimezone($value); case 'step': $this->setStep($value); return $this; case 'localMonthsOverflow': return $value === null ? $this : $this->settings(['monthOverflow' => $value]); case 'localYearsOverflow': return $value === null ? $this : $this->settings(['yearOverflow' => $value]); case 'localStrictModeEnabled': case 'localHumanDiffOptions': case 'localToStringFormat': case 'localSerializer': case 'localMacros': case 'localGenericMacros': case 'localFormatFunction': case 'localTranslator': $this->$setting = $value; return $this; default: // Drop unknown settings return $this; } } private static function incrementUnit(DateInterval $instance, string $unit, int $value): void { if ($value === 0) { return; } // @codeCoverageIgnoreStart if (PHP_VERSION_ID !== 8_03_20) { $instance->$unit += $value; return; } // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value); // @codeCoverageIgnoreEnd } /** @codeCoverageIgnore */ private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void { switch ($unit) { case 'y': $instance->y = $value; break; case 'm': $instance->m = $value; break; case 'd': $instance->d = $value; break; case 'h': $instance->h = $value; break; case 'i': $instance->i = $value; break; case 's': $instance->s = $value; break; default: $instance->$unit = $value; } } }
PHP
{ "end_line": 2326, "name": "plus", "signature": "public function plus(", "start_line": 2312 }
{ "class_name": "CarbonInterval", "class_signature": "class CarbonInterval implements CarbonConverterInterface, UnitValue", "namespace": "Carbon" }
minus
Carbon/src/Carbon/CarbonInterval.php
public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH], 'day' => ['week' => Carbon::DAYS_PER_WEEK], 'hour' => ['day' => Carbon::HOURS_PER_DAY], 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], ]; return $defaults[$source][$target] ?? null; } /** * Returns current config for days per week. * * @return int|float */ public static function getDaysPerWeek() { return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; } /** * Returns current config for hours per day. * * @return int|float */ public static function getHoursPerDay() { return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; } /** * Returns current config for minutes per hour. * * @return int|float */ public static function getMinutesPerHour() { return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; } /** * Returns current config for seconds per minute. * * @return int|float */ public static function getSecondsPerMinute() { return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMillisecondsPerSecond() { return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMicrosecondsPerMillisecond() { return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; } /** * Create a new CarbonInterval instance from specific values. * This is an alias for the constructor that allows better fluent * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than * (new CarbonInterval(1))->fn(). * * @param int $years * @param int $months * @param int $weeks * @param int $days * @param int $hours * @param int $minutes * @param int $seconds * @param int $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. * * @return static */ public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); } /** * Parse a string into a new CarbonInterval object according to the specified format. * * @example * ``` * echo Carboninterval::createFromFormat('H:i', '1:30'); * ``` * * @param string $format Format of the $interval input string * @param string|null $interval Input string to convert into an interval * * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. * * @return static */ public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; } /** * Return the original source used to create the current interval. * * @return array|int|string|DateInterval|mixed|null */ public function original() { return $this->originalInput; } /** * Return the start date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function start(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->startDate; } /** * Return the end date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function end(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->endDate; } /** * Get rid of the original input, start date and end date that may be kept in memory. * * @return $this */ public function optimize(): static { $this->originalInput = null; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; $this->absolute = false; return $this; } /** * Get a copy of the instance. * * @return static */ public function copy(): static { $date = new static(0); $date->copyProperties($this); $date->step = $this->step; return $date; } /** * Get a copy of the instance. * * @return static */ public function clone(): static { return $this->copy(); } /** * Provide static helpers to create instances. Allows CarbonInterval::years(3). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @return static|mixed|null */ public static function __callStatic(string $method, array $parameters) { try { $interval = new static(0); $localStrictModeEnabled = $interval->localStrictModeEnabled; $interval->localStrictModeEnabled = true; $result = static::hasMacro($method) ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { return $interval->callMacro($method, $parameters); }) : $interval->$method(...$parameters); $interval->localStrictModeEnabled = $localStrictModeEnabled; return $result; } catch (BadFluentSetterException $exception) { if (Carbon::isStrictModeEnabled()) { throw new BadFluentConstructorException($method, 0, $exception); } return null; } } /** * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. * * @param array $dump data as exported by var_export() * * @return static */ #[ReturnTypeWillChange] public static function __set_state($dump) { /** @noinspection PhpVoidFunctionResultUsedInspection */ /** @var DateInterval $dateInterval */ $dateInterval = parent::__set_state($dump); return static::instance($dateInterval); } /** * Return the current context from inside a macro callee or a new one if static. * * @return static */ protected static function this(): static { return end(static::$macroContextStack) ?: new static(0); } /** * Creates a CarbonInterval from string. * * Format: * * Suffix | Unit | Example | DateInterval expression * -------|---------|---------|------------------------ * y | years | 1y | P1Y * mo | months | 3mo | P3M * w | weeks | 2w | P2W * d | days | 28d | P28D * h | hours | 4h | PT4H * m | minutes | 12m | PT12M * s | seconds | 59s | PT59S * * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. * * Special cases: * - An empty string will return a zero interval * - Fractions are allowed for weeks, days, hours and minutes and will be converted * and rounded to the next smaller value (caution: 0.5w = 4d) * * @param string $intervalDefinition * * @throws InvalidIntervalException * * @return static */ public static function fromString(string $intervalDefinition): static { if (empty($intervalDefinition)) { return self::withOriginal(new static(0), $intervalDefinition); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $milliseconds = 0; $microseconds = 0; $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ([$part, $value, $unit] = array_shift($parts)) { $intValue = (int) $value; $fraction = (float) $value - $intValue; // Fix calculation precision switch (round($fraction, 6)) { case 1: $fraction = 0; $intValue++; break; case 0: $fraction = 0; break; } switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { case 'millennia': case 'millennium': $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; break; case 'century': case 'centuries': $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; break; case 'decade': case 'decades': $years += $intValue * CarbonInterface::YEARS_PER_DECADE; break; case 'year': case 'years': case 'y': case 'yr': case 'yrs': $years += $intValue; break; case 'quarter': case 'quarters': $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; break; case 'month': case 'months': case 'mo': case 'mos': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; } break; case 'second': case 'seconds': case 's': $seconds += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; } break; case 'millisecond': case 'milliseconds': case 'milli': case 'ms': $milliseconds += $intValue; if ($fraction) { $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); } break; case 'microsecond': case 'microseconds': case 'micro': case 'µs': $microseconds += $intValue; break; default: throw new InvalidIntervalException( "Invalid part $part in definition $intervalDefinition", ); } } return self::withOriginal( new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds), $intervalDefinition, ); } /** * Creates a CarbonInterval from string using a different locale. * * @param string $interval interval string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be used instead. * * @return static */ public static function parseFromLocale(string $interval, ?string $locale = null): static { return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE)); } /** * Create an interval from the difference between 2 dates. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $start * @param \Carbon\Carbon|\DateTimeInterface|mixed $end * * @return static */ public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; } /** * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function abs(bool $absolute = false): static { if ($absolute && $this->invert) { $this->invert(); } return $this; } /** * @alias abs * * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function absolute(bool $absolute = true): static { return $this->abs($absolute); } /** * Cast the current instance into the given class. * * @template T of DateInterval * * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { return self::castIntervalToClass($this, $className); } /** * Create a CarbonInterval instance from a DateInterval one. Can not instance * DateInterval objects created from DateTime::diff() as you can't externally * set the $days field. * * @param DateInterval $interval * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static */ public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static { if ($skipCopy && $interval instanceof static) { return $interval; } return self::castIntervalToClass($interval, static::class, $skip); } /** * Make a CarbonInterval instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static|null */ public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); } protected static function makeFromString(string $interval): ?self { $interval = preg_replace('/\s+/', ' ', trim($interval)); if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { return static::fromString($interval); } $intervalInstance = static::createFromDateString($interval); return $intervalInstance->isEmpty() ? null : $intervalInstance; } protected function resolveInterval($interval): ?self { if (!($interval instanceof self)) { return self::make($interval); } return $interval; } /** * Sets up a DateInterval from the relative parts of the string. * * @param string $datetime * * @return static * * @link https://php.net/manual/en/dateinterval.createfromdatestring.php */ public static function createFromDateString(string $datetime): static { $string = strtr($datetime, [ ',' => ' ', ' and ' => ' ', ]); $previousException = null; try { $interval = parent::createFromDateString($string); } catch (Throwable $exception) { $interval = null; $previousException = $exception; } $interval ?: throw new InvalidFormatException( 'Could not create interval from: '.var_export($datetime, true), previous: $previousException, ); if (!($interval instanceof static)) { $interval = static::instance($interval); } return self::withOriginal($interval, $datetime); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the CarbonInterval object. */ public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; } /** * Get a part of the CarbonInterval object. */ public function __get(string $name): int|float|string|null { return $this->get($name); } /** * Set a part of the CarbonInterval object. * * @param Unit|string|array $name * @param int $value * * @throws UnknownSetterException * * @return $this */ public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; } /** * Set a part of the CarbonInterval object. * * @param string $name * @param int $value * * @throws UnknownSetterException */ public function __set(string $name, $value) { $this->set($name, $value); } /** * Allow setting of weeks and days to be cumulative. * * @param int $weeks Number of weeks to set * @param int $days Number of days to set * * @return static */ public function weeksAndDays(int $weeks, int $days): static { $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; return $this; } /** * Returns true if the interval is empty for each unit. * * @return bool */ public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonInterval::macro('twice', function () { * return $this->times(2); * }); * echo CarbonInterval::hours(2)->twice(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonInterval::mixin(new class { * public function daysToHours() { * return function () { * $this->hours += $this->days; * $this->days = 0; * * return $this; * }; * } * public function hoursToDays() { * return function () { * $this->days += $this->hours; * $this->hours = 0; * * return $this; * }; * } * }); * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; * echo CarbonInterval::days(5)->daysToHours() . "\n"; * ``` * * @param object|string $mixin * * @throws ReflectionException * * @return void */ public static function mixin($mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Call given macro. * * @param string $name * @param array $parameters * * @return mixed */ protected function callMacro(string $name, array $parameters) { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadFluentSetterException|Throwable * * @return static|int|float|string */ public function __call(string $method, array $parameters) { if (static::hasMacro($method)) { return static::bindMacroContext($this, function () use (&$method, &$parameters) { return $this->callMacro($method, $parameters); }); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); return $this->{$match['method']}($value, $match['unit']); } $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); try { $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); } } return $this; } protected function getForHumansInitialVariables($syntax, $short): array { if (\is_array($syntax)) { return $syntax; } if (\is_int($short)) { return [ 'parts' => $short, 'short' => false, ]; } if (\is_bool($syntax)) { return [ 'short' => $syntax, 'syntax' => CarbonInterface::DIFF_ABSOLUTE, ]; } return []; } /** * @param mixed $syntax * @param mixed $short * @param mixed $parts * @param mixed $options * * @return array */ protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array { $optionalSpace = ' '; $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; /** @var bool|string $join */ $join = $default === '' ? '' : ' '; /** @var bool|array|string $altNumbers */ $altNumbers = false; $aUnit = false; $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); $skip = array_map( static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit, (array) $skip, ); $skip = array_map( 'strtolower', array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''), ); $syntax ??= CarbonInterface::DIFF_ABSOLUTE; if ($parts === self::NO_LIMIT) { $parts = INF; } $options ??= static::getHumanDiffOptions(); if ($join === false) { $join = ' '; } elseif ($join === true) { $join = [ $default, $this->getTranslationMessage('list.1') ?? $default, ]; } if ($altNumbers && $altNumbers !== true) { $language = new Language($this->locale); $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { [$default, $last] = $join; if ($default !== ' ') { $optionalSpace = ''; } $join = function ($list) use ($default, $last) { if (\count($list) < 2) { return implode('', $list); } $end = array_pop($list); return implode($default, $list).$last.$end; }; } if (\is_string($join)) { if ($join !== ' ') { $optionalSpace = ''; } $glue = $join; $join = static fn ($list) => implode($glue, $list); } $interpolations = [ ':optional-space' => $optionalSpace, ]; $translator ??= isset($locale) ? Translator::get($locale) : null; return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator]; } protected static function getRoundingMethodFromOptions(int $options): ?string { if ($options & CarbonInterface::ROUND) { return 'round'; } if ($options & CarbonInterface::CEIL) { return 'ceil'; } if ($options & CarbonInterface::FLOOR) { return 'floor'; } return null; } /** * Returns interval values as an array where key are the unit names and values the counts. * * @return int[] */ public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; } /** * Returns interval non-zero values as an array where key are the unit names and values the counts. * * @return int[] */ public function getNonZeroValues(): array { return array_filter($this->toArray(), 'intval'); } /** * Returns interval values as an array where key are the unit names and values the counts * from the biggest non-zero one the the smallest non-zero one. * * @return int[] */ public function getValuesSequence(): array { $nonZeroValues = $this->getNonZeroValues(); if ($nonZeroValues === []) { return []; } $keys = array_keys($nonZeroValues); $firstKey = $keys[0]; $lastKey = $keys[\count($keys) - 1]; $values = []; $record = false; foreach ($this->toArray() as $unit => $count) { if ($unit === $firstKey) { $record = true; } if ($record) { $values[$unit] = $count; } if ($unit === $lastKey) { $record = false; } } return $values; } /** * Get the current interval in a human readable format in the current locale. * * @example * ``` * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; * ``` * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: -1: no limits) * @param int $options human diff options * * @throws Exception * * @return string */ public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string { /* @var TranslatorInterface|null $translator */ [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this ->getForHumansParameters($syntax, $short, $parts, $options); $interval = []; $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; $count = 1; $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); $declensionMode = null; $translator ??= $this->getLocalTranslator(); $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); if ($this->needsDeclension($declensionMode, $index, $parts)) { // Some languages have special pluralization for past and future tense. $key = $unit.'_'.$transId; $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); if ($result !== $key) { return $result; } } } $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); if ($result !== $unit) { return $result; } return null; }; $intervalValues = $this; $method = static::getRoundingMethodFromOptions($options); if ($method) { $previousCount = INF; while ( \count($intervalValues->getNonZeroValues()) > $parts && ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 ) { $index = min($count, $previousCount - 1) - 2; if ($index < 0) { break; } $intervalValues = $this->copy()->roundUnit( $keys[$index], 1, $method, ); $previousCount = $count; } } $diffIntervalArray = [ ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], ]; if (!empty($skip)) { foreach ($diffIntervalArray as $index => &$unitData) { $nextIndex = $index + 1; if ($unitData['value'] && isset($diffIntervalArray[$nextIndex]) && \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) ) { $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); $unitData['value'] = 0; } } } $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; } } if (!$absolute) { return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); }; $fallbackUnit = ['second', 's']; foreach ($diffIntervalArray as $diffIntervalData) { if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } // break the loop after we get the required number of parts in array if (\count($interval) >= $parts) { break; } // break the loop after we have reached the minimum unit if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } $actualParts = \count($interval); foreach ($interval as $index => &$item) { $item = $transChoice($item[0], $item[1], $index, $actualParts); } if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; $unit = $fallbackUnit[$short ? 1 : 0]; $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); } // join the interval parts by a space $time = $join($interval); unset($diffIntervalArray, $interval); if ($absolute) { return $time; } $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); if ($parts === 1) { if ($relativeToNow && $unit === 'day') { $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null; if ($specialTranslations && $options & $specialTranslations['option']) { $key = $specialTranslations[$isFuture ? 'future' : 'past']; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } } $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; } $time = [':time' => $time]; return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); } public function format(string $format): string { $output = parent::format($format); if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) { return $output; } $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate); return str_replace('(unknown)', $this->rawInterval->format('%a'), $output); } /** * Format the instance as a string using the forHumans() function. * * @throws Exception * * @return string */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if (!$format) { return $this->forHumans(); } if ($format instanceof Closure) { return $format($this); } return $this->format($format); } /** * Return native DateInterval PHP object matching the current instance. * * @example * ``` * var_dump(CarbonInterval::hours(2)->toDateInterval()); * ``` * * @return DateInterval */ public function toDateInterval(): DateInterval { return self::castIntervalToClass($this, DateInterval::class); } /** * Convert the interval to a CarbonPeriod. * * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. * * @return CarbonPeriod */ public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); } /** * Decompose the current interval into * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); } /** * Invert the interval. * * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this */ public function invert($inverted = null): static { $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; return $this; } protected function solveNegativeInterval(): static { if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { $this->years *= self::NEGATIVE; $this->months *= self::NEGATIVE; $this->dayz *= self::NEGATIVE; $this->hours *= self::NEGATIVE; $this->minutes *= self::NEGATIVE; $this->seconds *= self::NEGATIVE; $this->microseconds *= self::NEGATIVE; $this->invert(); } return $this; } /** * Add the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function sub($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } return $this->add($unit, -(float) $value); } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function subtract($unit, $value = 1): static { return $this->sub($unit, $value); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Multiply current instance given number of times. times() is naive, it multiplies each unit * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded * separately for each unit. * * Use times() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see multiply() * * @param float|int $factor * * @return $this */ public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; } /** * Divide current instance by a given divider. shares() is naive, it divides each unit separately * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours * and 7 minutes. * * Use shares() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see divide() * * @param float|int $divider * * @return $this */ public function shares($divider): static { return $this->times(1 / $divider); } protected function copyProperties(self $interval, $ignoreSign = false): static { $this->years = $interval->years; $this->months = $interval->months; $this->dayz = $interval->dayz; $this->hours = $interval->hours; $this->minutes = $interval->minutes; $this->seconds = $interval->seconds; $this->microseconds = $interval->microseconds; if (!$ignoreSign) { $this->invert = $interval->invert; } return $this; } /** * Multiply and cascade current instance by a given factor. * * @param float|int $factor * * @return $this */ public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); } /** * Divide and cascade current instance by a given divider. * * @param float|int $divider * * @return $this */ public function divide($divider): static { return $this->multiply(1 / $divider); } /** * Get the interval_spec string of a date interval. * * @param DateInterval $interval * * @return string */ public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), static::PERIOD_MONTHS => abs($interval->m), static::PERIOD_DAYS => abs($interval->d), ]); $skip = array_map([Unit::class, 'toNameIfUnit'], $skip); if ( $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) ) { $date = [ static::PERIOD_DAYS => abs($interval->days), ]; } $seconds = abs($interval->s); if ($microseconds && $interval->f > 0) { $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); } $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; foreach ($date as $key => $value) { $specString .= $value.$key; } if (\count($time) > 0) { $specString .= static::PERIOD_TIME_PREFIX; foreach ($time as $key => $value) { $specString .= $value.$key; } } return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; } /** * Get the interval_spec string. * * @return string */ public function spec(bool $microseconds = false): string { return static::getDateIntervalSpec($this, $microseconds); } /** * Comparing 2 date intervals. * * @param DateInterval $first * @param DateInterval $second * * @return int 0, 1 or -1 */ public static function compareDateIntervals(DateInterval $first, DateInterval $second): int { $current = Carbon::now(); $passed = $current->avoidMutation()->add($second); $current->add($first); return $current <=> $passed; } /** * Comparing with passed interval. * * @param DateInterval $interval * * @return int 0, 1 or -1 */ public function compare(DateInterval $interval): int { return static::compareDateIntervals($this, $interval); } /** * Convert overflowed values into bigger units. * * @return $this */ public function cascade(): static { return $this->doCascade(false); } public function hasNegativeValues(): bool { foreach ($this->toArray() as $value) { if ($value < 0) { return true; } } return false; } public function hasPositiveValues(): bool { foreach ($this->toArray() as $value) { if ($value > 0) { return true; } } return false; } /** * Get amount of given unit equivalent to the interval. * * @param string $unit * * @throws UnknownUnitException|UnitNotConfiguredException * * @return float */ public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see equalTo() * * @return bool */ public function eq($interval): bool { return $this->equalTo($interval); } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see notEqualTo() * * @return bool */ public function ne($interval): bool { return $this->notEqualTo($interval); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function notEqualTo($interval): bool { return !$this->eq($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThan() * * @return bool */ public function gt($interval): bool { return $this->greaterThan($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThanOrEqualTo() * * @return bool */ public function gte($interval): bool { return $this->greaterThanOrEqualTo($interval); } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThanOrEqualTo($interval): bool { return $this->greaterThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThan() * * @return bool */ public function lt($interval): bool { return $this->lessThan($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThanOrEqualTo() * * @return bool */ public function lte($interval): bool { return $this->lessThanOrEqualTo($interval); } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThanOrEqualTo($interval): bool { return $this->lessThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function between($interval1, $interval2, bool $equal = true): bool { return $equal ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) : $this->greaterThan($interval1) && $this->lessThan($interval2); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenIncluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenExcluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, false); } /** * Determines if the instance is between two others * * @example * ``` * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function isBetween($interval1, $interval2, bool $equal = true): bool { return $this->between($interval1, $interval2, $equal); } /** * Round the current instance at the given unit with given precision if specified and the given function. * * @throws Exception */ public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); } /** * Truncate the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function floorUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function ceilUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified. * * @param float|int|string|DateInterval|null $precision * @param string $function * * @throws Exception * * @return $this */ public function round($precision = 1, string $function = 'round'): static { return $this->roundWith($precision, $function); } /** * Round the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function floor(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function ceil(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'ceil'); } public function __unserialize(array $data): void { $properties = array_combine( array_map( static fn (mixed $key) => \is_string($key) ? str_replace('tzName', 'timezoneSetting', $key) : $key, array_keys($data), ), $data, ); if (method_exists(parent::class, '__unserialize')) { // PHP >= 8.2 parent::__unserialize($properties); return; } // PHP <= 8.1 // @codeCoverageIgnoreStart $properties = array_combine( array_map( static fn (string $property) => preg_replace('/^\0.+\0/', '', $property), array_keys($data), ), $data, ); $localStrictMode = $this->localStrictModeEnabled; $this->localStrictModeEnabled = false; $days = $properties['days'] ?? false; $this->days = $days === false ? false : (int) $days; $this->y = (int) ($properties['y'] ?? 0); $this->m = (int) ($properties['m'] ?? 0); $this->d = (int) ($properties['d'] ?? 0); $this->h = (int) ($properties['h'] ?? 0); $this->i = (int) ($properties['i'] ?? 0); $this->s = (int) ($properties['s'] ?? 0); $this->f = (float) ($properties['f'] ?? 0.0); // @phpstan-ignore-next-line $this->weekday = (int) ($properties['weekday'] ?? 0); // @phpstan-ignore-next-line $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0); // @phpstan-ignore-next-line $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0); $this->invert = (int) ($properties['invert'] ?? 0); // @phpstan-ignore-next-line $this->special_type = (int) ($properties['special_type'] ?? 0); // @phpstan-ignore-next-line $this->special_amount = (int) ($properties['special_amount'] ?? 0); // @phpstan-ignore-next-line $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0); // @phpstan-ignore-next-line $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0); parent::__construct(self::getDateIntervalSpec($this)); foreach ($properties as $property => $value) { if ($property === 'localStrictModeEnabled') { continue; } $this->$property = $value; } $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode; // @codeCoverageIgnoreEnd } /** * @template T * * @param T $interval * @param mixed $original * * @return T */ private static function withOriginal(mixed $interval, mixed $original): mixed { if ($interval instanceof self) { $interval->originalInput = $original; } return $interval; } private static function standardizeUnit(string $unit): string { $unit = rtrim($unit, 'sz').'s'; return $unit === 'days' ? 'dayz' : $unit; } private static function getFlipCascadeFactors(): array { if (!self::$flipCascadeFactors) { self::$flipCascadeFactors = []; foreach (self::getCascadeFactors() as $to => [$factor, $from]) { self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; } } return self::$flipCascadeFactors; } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object { $mainClass = DateInterval::class; if (!is_a($className, $mainClass, true)) { throw new InvalidCastException("$className is not a sub-class of $mainClass."); } $microseconds = $interval->f; $instance = self::buildInstance($interval, $className, $skip); if ($instance instanceof self) { $instance->originalInput = $interval; } if ($microseconds) { $instance->f = $microseconds; } if ($interval instanceof self && is_a($className, self::class, true)) { self::copyStep($interval, $instance); } self::copyNegativeUnits($interval, $instance); return self::withOriginal($instance, $interval); } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function buildInstance( DateInterval $interval, string $className, array $skip = [], ): object { $serialization = self::buildSerializationString($interval, $className, $skip); return match ($serialization) { null => new $className(static::getDateIntervalSpec($interval, false, $skip)), default => unserialize($serialization), }; } /** * As demonstrated by rlanvin (https://github.com/rlanvin) in * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438 * * Modifying the output of serialize() to change the class name and unserializing * the tweaked string allows creating new interval instances where the ->days * property can be set. It's not possible neither with `new` nto with `__set_state`. * * It has a non-negligible performance cost, so we'll use this method only if * $interval->days !== false. */ private static function buildSerializationString( DateInterval $interval, string $className, array $skip = [], ): ?string { if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) { return null; } // De-enhance CarbonInterval objects to be serializable back to DateInterval if ($interval instanceof self && !is_a($className, self::class, true)) { $interval = clone $interval; unset($interval->timezoneSetting); unset($interval->originalInput); unset($interval->startDate); unset($interval->endDate); unset($interval->rawInterval); unset($interval->absolute); unset($interval->initialValues); unset($interval->clock); unset($interval->step); unset($interval->localMonthsOverflow); unset($interval->localYearsOverflow); unset($interval->localStrictModeEnabled); unset($interval->localHumanDiffOptions); unset($interval->localToStringFormat); unset($interval->localSerializer); unset($interval->localMacros); unset($interval->localGenericMacros); unset($interval->localFormatFunction); unset($interval->localTranslator); } $serialization = serialize($interval); $inputClass = $interval::class; $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":'; if (!str_starts_with($serialization, $expectedStart)) { return null; // @codeCoverageIgnore } return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart)); } private static function copyStep(self $from, self $to): void { $to->setStep($from->getStep()); } private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void { $to->invert = $from->invert; foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { if ($from->$unit < 0) { self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE); } } } private function invertCascade(array $values): static { return $this->set(array_map(function ($value) { return -$value; }, $values))->doCascade(true)->invert(); } private function doCascade(bool $deep): static { $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { if ($$key === 'dayz') { $$key = 'daysExcludeWeeks'; } } $value = $newData[$source]; $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; $decimalPart = fmod($newData[$source], 1); if ($decimalPart !== 0.0) { $unit = $source; foreach ($previous as [$subUnit, $subFactor]) { $newData[$unit] -= $decimalPart; $newData[$subUnit] += $decimalPart * $subFactor; $decimalPart = fmod($newData[$subUnit], 1); if ($decimalPart === 0.0) { break; } $unit = $subUnit; } } array_unshift($previous, [$source, $factor]); } $positive = null; if (!$deep) { foreach ($newData as $value) { if ($value) { if ($positive === null) { $positive = ($value > 0); continue; } if (($value > 0) !== $positive) { return $this->invertCascade($originalData) ->solveNegativeInterval(); } } } } return $this->set($newData) ->solveNegativeInterval(); } private function needsDeclension(string $mode, int $index, int $parts): bool { return match ($mode) { 'last' => $index === $parts - 1, default => true, }; } private function checkIntegerValue(string $name, mixed $value): void { if (\is_int($value)) { return; } $this->assertSafeForInteger($name, $value); if (\is_float($value) && (((float) (int) $value) === $value)) { return; } if (!self::$floatSettersEnabled) { $type = \gettype($value); @trigger_error( "Since 2.70.0, it's deprecated to pass $type value for $name.\n". "It's truncated when stored as an integer interval unit.\n". "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", \E_USER_DEPRECATED, ); } } /** * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. */ private function assertSafeForInteger(string $name, mixed $value): void { if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); } } private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void { if (self::$floatSettersEnabled) { $floatValue = (float) $value; $base = (float) $integerValue; if ($floatValue === $base) { return; } $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; $upper = true; foreach ($units as $property => $name) { if ($name === $unit) { $upper = false; continue; } if (!$upper && $this->$property !== 0) { throw new RuntimeException( "You cannot set $unit to a float value as $name would be overridden, ". 'set it first to 0 explicitly if you really want to erase its value' ); } } $this->add($unit, $floatValue - $base); } } private function getInnerValues(): array { return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days]; } private function checkStartAndEnd(): void { if ( $this->initialValues !== null && ($this->startDate !== null || $this->endDate !== null) && $this->initialValues !== $this->getInnerValues() ) { $this->absolute = false; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; } } /** @return $this */ private function setSetting(string $setting, mixed $value): self { switch ($setting) { case 'timezoneSetting': return $value === null ? $this : $this->setTimezone($value); case 'step': $this->setStep($value); return $this; case 'localMonthsOverflow': return $value === null ? $this : $this->settings(['monthOverflow' => $value]); case 'localYearsOverflow': return $value === null ? $this : $this->settings(['yearOverflow' => $value]); case 'localStrictModeEnabled': case 'localHumanDiffOptions': case 'localToStringFormat': case 'localSerializer': case 'localMacros': case 'localGenericMacros': case 'localFormatFunction': case 'localTranslator': $this->$setting = $value; return $this; default: // Drop unknown settings return $this; } } private static function incrementUnit(DateInterval $instance, string $unit, int $value): void { if ($value === 0) { return; } // @codeCoverageIgnoreStart if (PHP_VERSION_ID !== 8_03_20) { $instance->$unit += $value; return; } // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value); // @codeCoverageIgnoreEnd } /** @codeCoverageIgnore */ private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void { switch ($unit) { case 'y': $instance->y = $value; break; case 'm': $instance->m = $value; break; case 'd': $instance->d = $value; break; case 'h': $instance->h = $value; break; case 'i': $instance->i = $value; break; case 's': $instance->s = $value; break; default: $instance->$unit = $value; } } }
PHP
{ "end_line": 2356, "name": "minus", "signature": "public function minus(", "start_line": 2342 }
{ "class_name": "CarbonInterval", "class_signature": "class CarbonInterval implements CarbonConverterInterface, UnitValue", "namespace": "Carbon" }
times
Carbon/src/Carbon/CarbonInterval.php
public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH], 'day' => ['week' => Carbon::DAYS_PER_WEEK], 'hour' => ['day' => Carbon::HOURS_PER_DAY], 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], ]; return $defaults[$source][$target] ?? null; } /** * Returns current config for days per week. * * @return int|float */ public static function getDaysPerWeek() { return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; } /** * Returns current config for hours per day. * * @return int|float */ public static function getHoursPerDay() { return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; } /** * Returns current config for minutes per hour. * * @return int|float */ public static function getMinutesPerHour() { return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; } /** * Returns current config for seconds per minute. * * @return int|float */ public static function getSecondsPerMinute() { return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMillisecondsPerSecond() { return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMicrosecondsPerMillisecond() { return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; } /** * Create a new CarbonInterval instance from specific values. * This is an alias for the constructor that allows better fluent * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than * (new CarbonInterval(1))->fn(). * * @param int $years * @param int $months * @param int $weeks * @param int $days * @param int $hours * @param int $minutes * @param int $seconds * @param int $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. * * @return static */ public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); } /** * Parse a string into a new CarbonInterval object according to the specified format. * * @example * ``` * echo Carboninterval::createFromFormat('H:i', '1:30'); * ``` * * @param string $format Format of the $interval input string * @param string|null $interval Input string to convert into an interval * * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. * * @return static */ public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; } /** * Return the original source used to create the current interval. * * @return array|int|string|DateInterval|mixed|null */ public function original() { return $this->originalInput; } /** * Return the start date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function start(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->startDate; } /** * Return the end date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function end(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->endDate; } /** * Get rid of the original input, start date and end date that may be kept in memory. * * @return $this */ public function optimize(): static { $this->originalInput = null; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; $this->absolute = false; return $this; } /** * Get a copy of the instance. * * @return static */ public function copy(): static { $date = new static(0); $date->copyProperties($this); $date->step = $this->step; return $date; } /** * Get a copy of the instance. * * @return static */ public function clone(): static { return $this->copy(); } /** * Provide static helpers to create instances. Allows CarbonInterval::years(3). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @return static|mixed|null */ public static function __callStatic(string $method, array $parameters) { try { $interval = new static(0); $localStrictModeEnabled = $interval->localStrictModeEnabled; $interval->localStrictModeEnabled = true; $result = static::hasMacro($method) ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { return $interval->callMacro($method, $parameters); }) : $interval->$method(...$parameters); $interval->localStrictModeEnabled = $localStrictModeEnabled; return $result; } catch (BadFluentSetterException $exception) { if (Carbon::isStrictModeEnabled()) { throw new BadFluentConstructorException($method, 0, $exception); } return null; } } /** * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. * * @param array $dump data as exported by var_export() * * @return static */ #[ReturnTypeWillChange] public static function __set_state($dump) { /** @noinspection PhpVoidFunctionResultUsedInspection */ /** @var DateInterval $dateInterval */ $dateInterval = parent::__set_state($dump); return static::instance($dateInterval); } /** * Return the current context from inside a macro callee or a new one if static. * * @return static */ protected static function this(): static { return end(static::$macroContextStack) ?: new static(0); } /** * Creates a CarbonInterval from string. * * Format: * * Suffix | Unit | Example | DateInterval expression * -------|---------|---------|------------------------ * y | years | 1y | P1Y * mo | months | 3mo | P3M * w | weeks | 2w | P2W * d | days | 28d | P28D * h | hours | 4h | PT4H * m | minutes | 12m | PT12M * s | seconds | 59s | PT59S * * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. * * Special cases: * - An empty string will return a zero interval * - Fractions are allowed for weeks, days, hours and minutes and will be converted * and rounded to the next smaller value (caution: 0.5w = 4d) * * @param string $intervalDefinition * * @throws InvalidIntervalException * * @return static */ public static function fromString(string $intervalDefinition): static { if (empty($intervalDefinition)) { return self::withOriginal(new static(0), $intervalDefinition); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $milliseconds = 0; $microseconds = 0; $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ([$part, $value, $unit] = array_shift($parts)) { $intValue = (int) $value; $fraction = (float) $value - $intValue; // Fix calculation precision switch (round($fraction, 6)) { case 1: $fraction = 0; $intValue++; break; case 0: $fraction = 0; break; } switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { case 'millennia': case 'millennium': $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; break; case 'century': case 'centuries': $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; break; case 'decade': case 'decades': $years += $intValue * CarbonInterface::YEARS_PER_DECADE; break; case 'year': case 'years': case 'y': case 'yr': case 'yrs': $years += $intValue; break; case 'quarter': case 'quarters': $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; break; case 'month': case 'months': case 'mo': case 'mos': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; } break; case 'second': case 'seconds': case 's': $seconds += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; } break; case 'millisecond': case 'milliseconds': case 'milli': case 'ms': $milliseconds += $intValue; if ($fraction) { $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); } break; case 'microsecond': case 'microseconds': case 'micro': case 'µs': $microseconds += $intValue; break; default: throw new InvalidIntervalException( "Invalid part $part in definition $intervalDefinition", ); } } return self::withOriginal( new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds), $intervalDefinition, ); } /** * Creates a CarbonInterval from string using a different locale. * * @param string $interval interval string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be used instead. * * @return static */ public static function parseFromLocale(string $interval, ?string $locale = null): static { return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE)); } /** * Create an interval from the difference between 2 dates. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $start * @param \Carbon\Carbon|\DateTimeInterface|mixed $end * * @return static */ public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; } /** * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function abs(bool $absolute = false): static { if ($absolute && $this->invert) { $this->invert(); } return $this; } /** * @alias abs * * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function absolute(bool $absolute = true): static { return $this->abs($absolute); } /** * Cast the current instance into the given class. * * @template T of DateInterval * * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { return self::castIntervalToClass($this, $className); } /** * Create a CarbonInterval instance from a DateInterval one. Can not instance * DateInterval objects created from DateTime::diff() as you can't externally * set the $days field. * * @param DateInterval $interval * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static */ public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static { if ($skipCopy && $interval instanceof static) { return $interval; } return self::castIntervalToClass($interval, static::class, $skip); } /** * Make a CarbonInterval instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static|null */ public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); } protected static function makeFromString(string $interval): ?self { $interval = preg_replace('/\s+/', ' ', trim($interval)); if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { return static::fromString($interval); } $intervalInstance = static::createFromDateString($interval); return $intervalInstance->isEmpty() ? null : $intervalInstance; } protected function resolveInterval($interval): ?self { if (!($interval instanceof self)) { return self::make($interval); } return $interval; } /** * Sets up a DateInterval from the relative parts of the string. * * @param string $datetime * * @return static * * @link https://php.net/manual/en/dateinterval.createfromdatestring.php */ public static function createFromDateString(string $datetime): static { $string = strtr($datetime, [ ',' => ' ', ' and ' => ' ', ]); $previousException = null; try { $interval = parent::createFromDateString($string); } catch (Throwable $exception) { $interval = null; $previousException = $exception; } $interval ?: throw new InvalidFormatException( 'Could not create interval from: '.var_export($datetime, true), previous: $previousException, ); if (!($interval instanceof static)) { $interval = static::instance($interval); } return self::withOriginal($interval, $datetime); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the CarbonInterval object. */ public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; } /** * Get a part of the CarbonInterval object. */ public function __get(string $name): int|float|string|null { return $this->get($name); } /** * Set a part of the CarbonInterval object. * * @param Unit|string|array $name * @param int $value * * @throws UnknownSetterException * * @return $this */ public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; } /** * Set a part of the CarbonInterval object. * * @param string $name * @param int $value * * @throws UnknownSetterException */ public function __set(string $name, $value) { $this->set($name, $value); } /** * Allow setting of weeks and days to be cumulative. * * @param int $weeks Number of weeks to set * @param int $days Number of days to set * * @return static */ public function weeksAndDays(int $weeks, int $days): static { $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; return $this; } /** * Returns true if the interval is empty for each unit. * * @return bool */ public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonInterval::macro('twice', function () { * return $this->times(2); * }); * echo CarbonInterval::hours(2)->twice(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonInterval::mixin(new class { * public function daysToHours() { * return function () { * $this->hours += $this->days; * $this->days = 0; * * return $this; * }; * } * public function hoursToDays() { * return function () { * $this->days += $this->hours; * $this->hours = 0; * * return $this; * }; * } * }); * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; * echo CarbonInterval::days(5)->daysToHours() . "\n"; * ``` * * @param object|string $mixin * * @throws ReflectionException * * @return void */ public static function mixin($mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Call given macro. * * @param string $name * @param array $parameters * * @return mixed */ protected function callMacro(string $name, array $parameters) { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadFluentSetterException|Throwable * * @return static|int|float|string */ public function __call(string $method, array $parameters) { if (static::hasMacro($method)) { return static::bindMacroContext($this, function () use (&$method, &$parameters) { return $this->callMacro($method, $parameters); }); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); return $this->{$match['method']}($value, $match['unit']); } $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); try { $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); } } return $this; } protected function getForHumansInitialVariables($syntax, $short): array { if (\is_array($syntax)) { return $syntax; } if (\is_int($short)) { return [ 'parts' => $short, 'short' => false, ]; } if (\is_bool($syntax)) { return [ 'short' => $syntax, 'syntax' => CarbonInterface::DIFF_ABSOLUTE, ]; } return []; } /** * @param mixed $syntax * @param mixed $short * @param mixed $parts * @param mixed $options * * @return array */ protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array { $optionalSpace = ' '; $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; /** @var bool|string $join */ $join = $default === '' ? '' : ' '; /** @var bool|array|string $altNumbers */ $altNumbers = false; $aUnit = false; $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); $skip = array_map( static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit, (array) $skip, ); $skip = array_map( 'strtolower', array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''), ); $syntax ??= CarbonInterface::DIFF_ABSOLUTE; if ($parts === self::NO_LIMIT) { $parts = INF; } $options ??= static::getHumanDiffOptions(); if ($join === false) { $join = ' '; } elseif ($join === true) { $join = [ $default, $this->getTranslationMessage('list.1') ?? $default, ]; } if ($altNumbers && $altNumbers !== true) { $language = new Language($this->locale); $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { [$default, $last] = $join; if ($default !== ' ') { $optionalSpace = ''; } $join = function ($list) use ($default, $last) { if (\count($list) < 2) { return implode('', $list); } $end = array_pop($list); return implode($default, $list).$last.$end; }; } if (\is_string($join)) { if ($join !== ' ') { $optionalSpace = ''; } $glue = $join; $join = static fn ($list) => implode($glue, $list); } $interpolations = [ ':optional-space' => $optionalSpace, ]; $translator ??= isset($locale) ? Translator::get($locale) : null; return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator]; } protected static function getRoundingMethodFromOptions(int $options): ?string { if ($options & CarbonInterface::ROUND) { return 'round'; } if ($options & CarbonInterface::CEIL) { return 'ceil'; } if ($options & CarbonInterface::FLOOR) { return 'floor'; } return null; } /** * Returns interval values as an array where key are the unit names and values the counts. * * @return int[] */ public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; } /** * Returns interval non-zero values as an array where key are the unit names and values the counts. * * @return int[] */ public function getNonZeroValues(): array { return array_filter($this->toArray(), 'intval'); } /** * Returns interval values as an array where key are the unit names and values the counts * from the biggest non-zero one the the smallest non-zero one. * * @return int[] */ public function getValuesSequence(): array { $nonZeroValues = $this->getNonZeroValues(); if ($nonZeroValues === []) { return []; } $keys = array_keys($nonZeroValues); $firstKey = $keys[0]; $lastKey = $keys[\count($keys) - 1]; $values = []; $record = false; foreach ($this->toArray() as $unit => $count) { if ($unit === $firstKey) { $record = true; } if ($record) { $values[$unit] = $count; } if ($unit === $lastKey) { $record = false; } } return $values; } /** * Get the current interval in a human readable format in the current locale. * * @example * ``` * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; * ``` * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: -1: no limits) * @param int $options human diff options * * @throws Exception * * @return string */ public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string { /* @var TranslatorInterface|null $translator */ [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this ->getForHumansParameters($syntax, $short, $parts, $options); $interval = []; $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; $count = 1; $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); $declensionMode = null; $translator ??= $this->getLocalTranslator(); $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); if ($this->needsDeclension($declensionMode, $index, $parts)) { // Some languages have special pluralization for past and future tense. $key = $unit.'_'.$transId; $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); if ($result !== $key) { return $result; } } } $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); if ($result !== $unit) { return $result; } return null; }; $intervalValues = $this; $method = static::getRoundingMethodFromOptions($options); if ($method) { $previousCount = INF; while ( \count($intervalValues->getNonZeroValues()) > $parts && ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 ) { $index = min($count, $previousCount - 1) - 2; if ($index < 0) { break; } $intervalValues = $this->copy()->roundUnit( $keys[$index], 1, $method, ); $previousCount = $count; } } $diffIntervalArray = [ ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], ]; if (!empty($skip)) { foreach ($diffIntervalArray as $index => &$unitData) { $nextIndex = $index + 1; if ($unitData['value'] && isset($diffIntervalArray[$nextIndex]) && \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) ) { $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); $unitData['value'] = 0; } } } $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; } } if (!$absolute) { return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); }; $fallbackUnit = ['second', 's']; foreach ($diffIntervalArray as $diffIntervalData) { if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } // break the loop after we get the required number of parts in array if (\count($interval) >= $parts) { break; } // break the loop after we have reached the minimum unit if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } $actualParts = \count($interval); foreach ($interval as $index => &$item) { $item = $transChoice($item[0], $item[1], $index, $actualParts); } if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; $unit = $fallbackUnit[$short ? 1 : 0]; $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); } // join the interval parts by a space $time = $join($interval); unset($diffIntervalArray, $interval); if ($absolute) { return $time; } $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); if ($parts === 1) { if ($relativeToNow && $unit === 'day') { $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null; if ($specialTranslations && $options & $specialTranslations['option']) { $key = $specialTranslations[$isFuture ? 'future' : 'past']; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } } $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; } $time = [':time' => $time]; return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); } public function format(string $format): string { $output = parent::format($format); if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) { return $output; } $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate); return str_replace('(unknown)', $this->rawInterval->format('%a'), $output); } /** * Format the instance as a string using the forHumans() function. * * @throws Exception * * @return string */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if (!$format) { return $this->forHumans(); } if ($format instanceof Closure) { return $format($this); } return $this->format($format); } /** * Return native DateInterval PHP object matching the current instance. * * @example * ``` * var_dump(CarbonInterval::hours(2)->toDateInterval()); * ``` * * @return DateInterval */ public function toDateInterval(): DateInterval { return self::castIntervalToClass($this, DateInterval::class); } /** * Convert the interval to a CarbonPeriod. * * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. * * @return CarbonPeriod */ public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); } /** * Decompose the current interval into * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); } /** * Invert the interval. * * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this */ public function invert($inverted = null): static { $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; return $this; } protected function solveNegativeInterval(): static { if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { $this->years *= self::NEGATIVE; $this->months *= self::NEGATIVE; $this->dayz *= self::NEGATIVE; $this->hours *= self::NEGATIVE; $this->minutes *= self::NEGATIVE; $this->seconds *= self::NEGATIVE; $this->microseconds *= self::NEGATIVE; $this->invert(); } return $this; } /** * Add the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function sub($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } return $this->add($unit, -(float) $value); } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function subtract($unit, $value = 1): static { return $this->sub($unit, $value); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Multiply current instance given number of times. times() is naive, it multiplies each unit * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded * separately for each unit. * * Use times() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see multiply() * * @param float|int $factor * * @return $this */ public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; } /** * Divide current instance by a given divider. shares() is naive, it divides each unit separately * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours * and 7 minutes. * * Use shares() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see divide() * * @param float|int $divider * * @return $this */ public function shares($divider): static { return $this->times(1 / $divider); } protected function copyProperties(self $interval, $ignoreSign = false): static { $this->years = $interval->years; $this->months = $interval->months; $this->dayz = $interval->dayz; $this->hours = $interval->hours; $this->minutes = $interval->minutes; $this->seconds = $interval->seconds; $this->microseconds = $interval->microseconds; if (!$ignoreSign) { $this->invert = $interval->invert; } return $this; } /** * Multiply and cascade current instance by a given factor. * * @param float|int $factor * * @return $this */ public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); } /** * Divide and cascade current instance by a given divider. * * @param float|int $divider * * @return $this */ public function divide($divider): static { return $this->multiply(1 / $divider); } /** * Get the interval_spec string of a date interval. * * @param DateInterval $interval * * @return string */ public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), static::PERIOD_MONTHS => abs($interval->m), static::PERIOD_DAYS => abs($interval->d), ]); $skip = array_map([Unit::class, 'toNameIfUnit'], $skip); if ( $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) ) { $date = [ static::PERIOD_DAYS => abs($interval->days), ]; } $seconds = abs($interval->s); if ($microseconds && $interval->f > 0) { $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); } $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; foreach ($date as $key => $value) { $specString .= $value.$key; } if (\count($time) > 0) { $specString .= static::PERIOD_TIME_PREFIX; foreach ($time as $key => $value) { $specString .= $value.$key; } } return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; } /** * Get the interval_spec string. * * @return string */ public function spec(bool $microseconds = false): string { return static::getDateIntervalSpec($this, $microseconds); } /** * Comparing 2 date intervals. * * @param DateInterval $first * @param DateInterval $second * * @return int 0, 1 or -1 */ public static function compareDateIntervals(DateInterval $first, DateInterval $second): int { $current = Carbon::now(); $passed = $current->avoidMutation()->add($second); $current->add($first); return $current <=> $passed; } /** * Comparing with passed interval. * * @param DateInterval $interval * * @return int 0, 1 or -1 */ public function compare(DateInterval $interval): int { return static::compareDateIntervals($this, $interval); } /** * Convert overflowed values into bigger units. * * @return $this */ public function cascade(): static { return $this->doCascade(false); } public function hasNegativeValues(): bool { foreach ($this->toArray() as $value) { if ($value < 0) { return true; } } return false; } public function hasPositiveValues(): bool { foreach ($this->toArray() as $value) { if ($value > 0) { return true; } } return false; } /** * Get amount of given unit equivalent to the interval. * * @param string $unit * * @throws UnknownUnitException|UnitNotConfiguredException * * @return float */ public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see equalTo() * * @return bool */ public function eq($interval): bool { return $this->equalTo($interval); } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see notEqualTo() * * @return bool */ public function ne($interval): bool { return $this->notEqualTo($interval); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function notEqualTo($interval): bool { return !$this->eq($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThan() * * @return bool */ public function gt($interval): bool { return $this->greaterThan($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThanOrEqualTo() * * @return bool */ public function gte($interval): bool { return $this->greaterThanOrEqualTo($interval); } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThanOrEqualTo($interval): bool { return $this->greaterThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThan() * * @return bool */ public function lt($interval): bool { return $this->lessThan($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThanOrEqualTo() * * @return bool */ public function lte($interval): bool { return $this->lessThanOrEqualTo($interval); } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThanOrEqualTo($interval): bool { return $this->lessThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function between($interval1, $interval2, bool $equal = true): bool { return $equal ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) : $this->greaterThan($interval1) && $this->lessThan($interval2); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenIncluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenExcluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, false); } /** * Determines if the instance is between two others * * @example * ``` * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function isBetween($interval1, $interval2, bool $equal = true): bool { return $this->between($interval1, $interval2, $equal); } /** * Round the current instance at the given unit with given precision if specified and the given function. * * @throws Exception */ public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); } /** * Truncate the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function floorUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function ceilUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified. * * @param float|int|string|DateInterval|null $precision * @param string $function * * @throws Exception * * @return $this */ public function round($precision = 1, string $function = 'round'): static { return $this->roundWith($precision, $function); } /** * Round the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function floor(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function ceil(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'ceil'); } public function __unserialize(array $data): void { $properties = array_combine( array_map( static fn (mixed $key) => \is_string($key) ? str_replace('tzName', 'timezoneSetting', $key) : $key, array_keys($data), ), $data, ); if (method_exists(parent::class, '__unserialize')) { // PHP >= 8.2 parent::__unserialize($properties); return; } // PHP <= 8.1 // @codeCoverageIgnoreStart $properties = array_combine( array_map( static fn (string $property) => preg_replace('/^\0.+\0/', '', $property), array_keys($data), ), $data, ); $localStrictMode = $this->localStrictModeEnabled; $this->localStrictModeEnabled = false; $days = $properties['days'] ?? false; $this->days = $days === false ? false : (int) $days; $this->y = (int) ($properties['y'] ?? 0); $this->m = (int) ($properties['m'] ?? 0); $this->d = (int) ($properties['d'] ?? 0); $this->h = (int) ($properties['h'] ?? 0); $this->i = (int) ($properties['i'] ?? 0); $this->s = (int) ($properties['s'] ?? 0); $this->f = (float) ($properties['f'] ?? 0.0); // @phpstan-ignore-next-line $this->weekday = (int) ($properties['weekday'] ?? 0); // @phpstan-ignore-next-line $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0); // @phpstan-ignore-next-line $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0); $this->invert = (int) ($properties['invert'] ?? 0); // @phpstan-ignore-next-line $this->special_type = (int) ($properties['special_type'] ?? 0); // @phpstan-ignore-next-line $this->special_amount = (int) ($properties['special_amount'] ?? 0); // @phpstan-ignore-next-line $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0); // @phpstan-ignore-next-line $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0); parent::__construct(self::getDateIntervalSpec($this)); foreach ($properties as $property => $value) { if ($property === 'localStrictModeEnabled') { continue; } $this->$property = $value; } $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode; // @codeCoverageIgnoreEnd } /** * @template T * * @param T $interval * @param mixed $original * * @return T */ private static function withOriginal(mixed $interval, mixed $original): mixed { if ($interval instanceof self) { $interval->originalInput = $original; } return $interval; } private static function standardizeUnit(string $unit): string { $unit = rtrim($unit, 'sz').'s'; return $unit === 'days' ? 'dayz' : $unit; } private static function getFlipCascadeFactors(): array { if (!self::$flipCascadeFactors) { self::$flipCascadeFactors = []; foreach (self::getCascadeFactors() as $to => [$factor, $from]) { self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; } } return self::$flipCascadeFactors; } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object { $mainClass = DateInterval::class; if (!is_a($className, $mainClass, true)) { throw new InvalidCastException("$className is not a sub-class of $mainClass."); } $microseconds = $interval->f; $instance = self::buildInstance($interval, $className, $skip); if ($instance instanceof self) { $instance->originalInput = $interval; } if ($microseconds) { $instance->f = $microseconds; } if ($interval instanceof self && is_a($className, self::class, true)) { self::copyStep($interval, $instance); } self::copyNegativeUnits($interval, $instance); return self::withOriginal($instance, $interval); } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function buildInstance( DateInterval $interval, string $className, array $skip = [], ): object { $serialization = self::buildSerializationString($interval, $className, $skip); return match ($serialization) { null => new $className(static::getDateIntervalSpec($interval, false, $skip)), default => unserialize($serialization), }; } /** * As demonstrated by rlanvin (https://github.com/rlanvin) in * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438 * * Modifying the output of serialize() to change the class name and unserializing * the tweaked string allows creating new interval instances where the ->days * property can be set. It's not possible neither with `new` nto with `__set_state`. * * It has a non-negligible performance cost, so we'll use this method only if * $interval->days !== false. */ private static function buildSerializationString( DateInterval $interval, string $className, array $skip = [], ): ?string { if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) { return null; } // De-enhance CarbonInterval objects to be serializable back to DateInterval if ($interval instanceof self && !is_a($className, self::class, true)) { $interval = clone $interval; unset($interval->timezoneSetting); unset($interval->originalInput); unset($interval->startDate); unset($interval->endDate); unset($interval->rawInterval); unset($interval->absolute); unset($interval->initialValues); unset($interval->clock); unset($interval->step); unset($interval->localMonthsOverflow); unset($interval->localYearsOverflow); unset($interval->localStrictModeEnabled); unset($interval->localHumanDiffOptions); unset($interval->localToStringFormat); unset($interval->localSerializer); unset($interval->localMacros); unset($interval->localGenericMacros); unset($interval->localFormatFunction); unset($interval->localTranslator); } $serialization = serialize($interval); $inputClass = $interval::class; $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":'; if (!str_starts_with($serialization, $expectedStart)) { return null; // @codeCoverageIgnore } return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart)); } private static function copyStep(self $from, self $to): void { $to->setStep($from->getStep()); } private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void { $to->invert = $from->invert; foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { if ($from->$unit < 0) { self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE); } } } private function invertCascade(array $values): static { return $this->set(array_map(function ($value) { return -$value; }, $values))->doCascade(true)->invert(); } private function doCascade(bool $deep): static { $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { if ($$key === 'dayz') { $$key = 'daysExcludeWeeks'; } } $value = $newData[$source]; $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; $decimalPart = fmod($newData[$source], 1); if ($decimalPart !== 0.0) { $unit = $source; foreach ($previous as [$subUnit, $subFactor]) { $newData[$unit] -= $decimalPart; $newData[$subUnit] += $decimalPart * $subFactor; $decimalPart = fmod($newData[$subUnit], 1); if ($decimalPart === 0.0) { break; } $unit = $subUnit; } } array_unshift($previous, [$source, $factor]); } $positive = null; if (!$deep) { foreach ($newData as $value) { if ($value) { if ($positive === null) { $positive = ($value > 0); continue; } if (($value > 0) !== $positive) { return $this->invertCascade($originalData) ->solveNegativeInterval(); } } } } return $this->set($newData) ->solveNegativeInterval(); } private function needsDeclension(string $mode, int $index, int $parts): bool { return match ($mode) { 'last' => $index === $parts - 1, default => true, }; } private function checkIntegerValue(string $name, mixed $value): void { if (\is_int($value)) { return; } $this->assertSafeForInteger($name, $value); if (\is_float($value) && (((float) (int) $value) === $value)) { return; } if (!self::$floatSettersEnabled) { $type = \gettype($value); @trigger_error( "Since 2.70.0, it's deprecated to pass $type value for $name.\n". "It's truncated when stored as an integer interval unit.\n". "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", \E_USER_DEPRECATED, ); } } /** * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. */ private function assertSafeForInteger(string $name, mixed $value): void { if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); } } private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void { if (self::$floatSettersEnabled) { $floatValue = (float) $value; $base = (float) $integerValue; if ($floatValue === $base) { return; } $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; $upper = true; foreach ($units as $property => $name) { if ($name === $unit) { $upper = false; continue; } if (!$upper && $this->$property !== 0) { throw new RuntimeException( "You cannot set $unit to a float value as $name would be overridden, ". 'set it first to 0 explicitly if you really want to erase its value' ); } } $this->add($unit, $floatValue - $base); } } private function getInnerValues(): array { return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days]; } private function checkStartAndEnd(): void { if ( $this->initialValues !== null && ($this->startDate !== null || $this->endDate !== null) && $this->initialValues !== $this->getInnerValues() ) { $this->absolute = false; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; } } /** @return $this */ private function setSetting(string $setting, mixed $value): self { switch ($setting) { case 'timezoneSetting': return $value === null ? $this : $this->setTimezone($value); case 'step': $this->setStep($value); return $this; case 'localMonthsOverflow': return $value === null ? $this : $this->settings(['monthOverflow' => $value]); case 'localYearsOverflow': return $value === null ? $this : $this->settings(['yearOverflow' => $value]); case 'localStrictModeEnabled': case 'localHumanDiffOptions': case 'localToStringFormat': case 'localSerializer': case 'localMacros': case 'localGenericMacros': case 'localFormatFunction': case 'localTranslator': $this->$setting = $value; return $this; default: // Drop unknown settings return $this; } } private static function incrementUnit(DateInterval $instance, string $unit, int $value): void { if ($value === 0) { return; } // @codeCoverageIgnoreStart if (PHP_VERSION_ID !== 8_03_20) { $instance->$unit += $value; return; } // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value); // @codeCoverageIgnoreEnd } /** @codeCoverageIgnore */ private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void { switch ($unit) { case 'y': $instance->y = $value; break; case 'm': $instance->m = $value; break; case 'd': $instance->d = $value; break; case 'h': $instance->h = $value; break; case 'i': $instance->i = $value; break; case 's': $instance->s = $value; break; default: $instance->$unit = $value; } } }
PHP
{ "end_line": 2389, "name": "times", "signature": "public function times($factor): static", "start_line": 2373 }
{ "class_name": "CarbonInterval", "class_signature": "class CarbonInterval implements CarbonConverterInterface, UnitValue", "namespace": "Carbon" }
multiply
Carbon/src/Carbon/CarbonInterval.php
public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH], 'day' => ['week' => Carbon::DAYS_PER_WEEK], 'hour' => ['day' => Carbon::HOURS_PER_DAY], 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], ]; return $defaults[$source][$target] ?? null; } /** * Returns current config for days per week. * * @return int|float */ public static function getDaysPerWeek() { return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; } /** * Returns current config for hours per day. * * @return int|float */ public static function getHoursPerDay() { return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; } /** * Returns current config for minutes per hour. * * @return int|float */ public static function getMinutesPerHour() { return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; } /** * Returns current config for seconds per minute. * * @return int|float */ public static function getSecondsPerMinute() { return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMillisecondsPerSecond() { return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMicrosecondsPerMillisecond() { return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; } /** * Create a new CarbonInterval instance from specific values. * This is an alias for the constructor that allows better fluent * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than * (new CarbonInterval(1))->fn(). * * @param int $years * @param int $months * @param int $weeks * @param int $days * @param int $hours * @param int $minutes * @param int $seconds * @param int $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. * * @return static */ public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); } /** * Parse a string into a new CarbonInterval object according to the specified format. * * @example * ``` * echo Carboninterval::createFromFormat('H:i', '1:30'); * ``` * * @param string $format Format of the $interval input string * @param string|null $interval Input string to convert into an interval * * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. * * @return static */ public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; } /** * Return the original source used to create the current interval. * * @return array|int|string|DateInterval|mixed|null */ public function original() { return $this->originalInput; } /** * Return the start date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function start(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->startDate; } /** * Return the end date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function end(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->endDate; } /** * Get rid of the original input, start date and end date that may be kept in memory. * * @return $this */ public function optimize(): static { $this->originalInput = null; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; $this->absolute = false; return $this; } /** * Get a copy of the instance. * * @return static */ public function copy(): static { $date = new static(0); $date->copyProperties($this); $date->step = $this->step; return $date; } /** * Get a copy of the instance. * * @return static */ public function clone(): static { return $this->copy(); } /** * Provide static helpers to create instances. Allows CarbonInterval::years(3). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @return static|mixed|null */ public static function __callStatic(string $method, array $parameters) { try { $interval = new static(0); $localStrictModeEnabled = $interval->localStrictModeEnabled; $interval->localStrictModeEnabled = true; $result = static::hasMacro($method) ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { return $interval->callMacro($method, $parameters); }) : $interval->$method(...$parameters); $interval->localStrictModeEnabled = $localStrictModeEnabled; return $result; } catch (BadFluentSetterException $exception) { if (Carbon::isStrictModeEnabled()) { throw new BadFluentConstructorException($method, 0, $exception); } return null; } } /** * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. * * @param array $dump data as exported by var_export() * * @return static */ #[ReturnTypeWillChange] public static function __set_state($dump) { /** @noinspection PhpVoidFunctionResultUsedInspection */ /** @var DateInterval $dateInterval */ $dateInterval = parent::__set_state($dump); return static::instance($dateInterval); } /** * Return the current context from inside a macro callee or a new one if static. * * @return static */ protected static function this(): static { return end(static::$macroContextStack) ?: new static(0); } /** * Creates a CarbonInterval from string. * * Format: * * Suffix | Unit | Example | DateInterval expression * -------|---------|---------|------------------------ * y | years | 1y | P1Y * mo | months | 3mo | P3M * w | weeks | 2w | P2W * d | days | 28d | P28D * h | hours | 4h | PT4H * m | minutes | 12m | PT12M * s | seconds | 59s | PT59S * * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. * * Special cases: * - An empty string will return a zero interval * - Fractions are allowed for weeks, days, hours and minutes and will be converted * and rounded to the next smaller value (caution: 0.5w = 4d) * * @param string $intervalDefinition * * @throws InvalidIntervalException * * @return static */ public static function fromString(string $intervalDefinition): static { if (empty($intervalDefinition)) { return self::withOriginal(new static(0), $intervalDefinition); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $milliseconds = 0; $microseconds = 0; $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ([$part, $value, $unit] = array_shift($parts)) { $intValue = (int) $value; $fraction = (float) $value - $intValue; // Fix calculation precision switch (round($fraction, 6)) { case 1: $fraction = 0; $intValue++; break; case 0: $fraction = 0; break; } switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { case 'millennia': case 'millennium': $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; break; case 'century': case 'centuries': $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; break; case 'decade': case 'decades': $years += $intValue * CarbonInterface::YEARS_PER_DECADE; break; case 'year': case 'years': case 'y': case 'yr': case 'yrs': $years += $intValue; break; case 'quarter': case 'quarters': $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; break; case 'month': case 'months': case 'mo': case 'mos': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; } break; case 'second': case 'seconds': case 's': $seconds += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; } break; case 'millisecond': case 'milliseconds': case 'milli': case 'ms': $milliseconds += $intValue; if ($fraction) { $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); } break; case 'microsecond': case 'microseconds': case 'micro': case 'µs': $microseconds += $intValue; break; default: throw new InvalidIntervalException( "Invalid part $part in definition $intervalDefinition", ); } } return self::withOriginal( new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds), $intervalDefinition, ); } /** * Creates a CarbonInterval from string using a different locale. * * @param string $interval interval string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be used instead. * * @return static */ public static function parseFromLocale(string $interval, ?string $locale = null): static { return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE)); } /** * Create an interval from the difference between 2 dates. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $start * @param \Carbon\Carbon|\DateTimeInterface|mixed $end * * @return static */ public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; } /** * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function abs(bool $absolute = false): static { if ($absolute && $this->invert) { $this->invert(); } return $this; } /** * @alias abs * * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function absolute(bool $absolute = true): static { return $this->abs($absolute); } /** * Cast the current instance into the given class. * * @template T of DateInterval * * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { return self::castIntervalToClass($this, $className); } /** * Create a CarbonInterval instance from a DateInterval one. Can not instance * DateInterval objects created from DateTime::diff() as you can't externally * set the $days field. * * @param DateInterval $interval * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static */ public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static { if ($skipCopy && $interval instanceof static) { return $interval; } return self::castIntervalToClass($interval, static::class, $skip); } /** * Make a CarbonInterval instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static|null */ public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); } protected static function makeFromString(string $interval): ?self { $interval = preg_replace('/\s+/', ' ', trim($interval)); if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { return static::fromString($interval); } $intervalInstance = static::createFromDateString($interval); return $intervalInstance->isEmpty() ? null : $intervalInstance; } protected function resolveInterval($interval): ?self { if (!($interval instanceof self)) { return self::make($interval); } return $interval; } /** * Sets up a DateInterval from the relative parts of the string. * * @param string $datetime * * @return static * * @link https://php.net/manual/en/dateinterval.createfromdatestring.php */ public static function createFromDateString(string $datetime): static { $string = strtr($datetime, [ ',' => ' ', ' and ' => ' ', ]); $previousException = null; try { $interval = parent::createFromDateString($string); } catch (Throwable $exception) { $interval = null; $previousException = $exception; } $interval ?: throw new InvalidFormatException( 'Could not create interval from: '.var_export($datetime, true), previous: $previousException, ); if (!($interval instanceof static)) { $interval = static::instance($interval); } return self::withOriginal($interval, $datetime); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the CarbonInterval object. */ public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; } /** * Get a part of the CarbonInterval object. */ public function __get(string $name): int|float|string|null { return $this->get($name); } /** * Set a part of the CarbonInterval object. * * @param Unit|string|array $name * @param int $value * * @throws UnknownSetterException * * @return $this */ public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; } /** * Set a part of the CarbonInterval object. * * @param string $name * @param int $value * * @throws UnknownSetterException */ public function __set(string $name, $value) { $this->set($name, $value); } /** * Allow setting of weeks and days to be cumulative. * * @param int $weeks Number of weeks to set * @param int $days Number of days to set * * @return static */ public function weeksAndDays(int $weeks, int $days): static { $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; return $this; } /** * Returns true if the interval is empty for each unit. * * @return bool */ public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonInterval::macro('twice', function () { * return $this->times(2); * }); * echo CarbonInterval::hours(2)->twice(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonInterval::mixin(new class { * public function daysToHours() { * return function () { * $this->hours += $this->days; * $this->days = 0; * * return $this; * }; * } * public function hoursToDays() { * return function () { * $this->days += $this->hours; * $this->hours = 0; * * return $this; * }; * } * }); * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; * echo CarbonInterval::days(5)->daysToHours() . "\n"; * ``` * * @param object|string $mixin * * @throws ReflectionException * * @return void */ public static function mixin($mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Call given macro. * * @param string $name * @param array $parameters * * @return mixed */ protected function callMacro(string $name, array $parameters) { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadFluentSetterException|Throwable * * @return static|int|float|string */ public function __call(string $method, array $parameters) { if (static::hasMacro($method)) { return static::bindMacroContext($this, function () use (&$method, &$parameters) { return $this->callMacro($method, $parameters); }); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); return $this->{$match['method']}($value, $match['unit']); } $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); try { $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); } } return $this; } protected function getForHumansInitialVariables($syntax, $short): array { if (\is_array($syntax)) { return $syntax; } if (\is_int($short)) { return [ 'parts' => $short, 'short' => false, ]; } if (\is_bool($syntax)) { return [ 'short' => $syntax, 'syntax' => CarbonInterface::DIFF_ABSOLUTE, ]; } return []; } /** * @param mixed $syntax * @param mixed $short * @param mixed $parts * @param mixed $options * * @return array */ protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array { $optionalSpace = ' '; $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; /** @var bool|string $join */ $join = $default === '' ? '' : ' '; /** @var bool|array|string $altNumbers */ $altNumbers = false; $aUnit = false; $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); $skip = array_map( static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit, (array) $skip, ); $skip = array_map( 'strtolower', array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''), ); $syntax ??= CarbonInterface::DIFF_ABSOLUTE; if ($parts === self::NO_LIMIT) { $parts = INF; } $options ??= static::getHumanDiffOptions(); if ($join === false) { $join = ' '; } elseif ($join === true) { $join = [ $default, $this->getTranslationMessage('list.1') ?? $default, ]; } if ($altNumbers && $altNumbers !== true) { $language = new Language($this->locale); $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { [$default, $last] = $join; if ($default !== ' ') { $optionalSpace = ''; } $join = function ($list) use ($default, $last) { if (\count($list) < 2) { return implode('', $list); } $end = array_pop($list); return implode($default, $list).$last.$end; }; } if (\is_string($join)) { if ($join !== ' ') { $optionalSpace = ''; } $glue = $join; $join = static fn ($list) => implode($glue, $list); } $interpolations = [ ':optional-space' => $optionalSpace, ]; $translator ??= isset($locale) ? Translator::get($locale) : null; return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator]; } protected static function getRoundingMethodFromOptions(int $options): ?string { if ($options & CarbonInterface::ROUND) { return 'round'; } if ($options & CarbonInterface::CEIL) { return 'ceil'; } if ($options & CarbonInterface::FLOOR) { return 'floor'; } return null; } /** * Returns interval values as an array where key are the unit names and values the counts. * * @return int[] */ public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; } /** * Returns interval non-zero values as an array where key are the unit names and values the counts. * * @return int[] */ public function getNonZeroValues(): array { return array_filter($this->toArray(), 'intval'); } /** * Returns interval values as an array where key are the unit names and values the counts * from the biggest non-zero one the the smallest non-zero one. * * @return int[] */ public function getValuesSequence(): array { $nonZeroValues = $this->getNonZeroValues(); if ($nonZeroValues === []) { return []; } $keys = array_keys($nonZeroValues); $firstKey = $keys[0]; $lastKey = $keys[\count($keys) - 1]; $values = []; $record = false; foreach ($this->toArray() as $unit => $count) { if ($unit === $firstKey) { $record = true; } if ($record) { $values[$unit] = $count; } if ($unit === $lastKey) { $record = false; } } return $values; } /** * Get the current interval in a human readable format in the current locale. * * @example * ``` * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; * ``` * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: -1: no limits) * @param int $options human diff options * * @throws Exception * * @return string */ public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string { /* @var TranslatorInterface|null $translator */ [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this ->getForHumansParameters($syntax, $short, $parts, $options); $interval = []; $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; $count = 1; $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); $declensionMode = null; $translator ??= $this->getLocalTranslator(); $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); if ($this->needsDeclension($declensionMode, $index, $parts)) { // Some languages have special pluralization for past and future tense. $key = $unit.'_'.$transId; $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); if ($result !== $key) { return $result; } } } $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); if ($result !== $unit) { return $result; } return null; }; $intervalValues = $this; $method = static::getRoundingMethodFromOptions($options); if ($method) { $previousCount = INF; while ( \count($intervalValues->getNonZeroValues()) > $parts && ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 ) { $index = min($count, $previousCount - 1) - 2; if ($index < 0) { break; } $intervalValues = $this->copy()->roundUnit( $keys[$index], 1, $method, ); $previousCount = $count; } } $diffIntervalArray = [ ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], ]; if (!empty($skip)) { foreach ($diffIntervalArray as $index => &$unitData) { $nextIndex = $index + 1; if ($unitData['value'] && isset($diffIntervalArray[$nextIndex]) && \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) ) { $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); $unitData['value'] = 0; } } } $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; } } if (!$absolute) { return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); }; $fallbackUnit = ['second', 's']; foreach ($diffIntervalArray as $diffIntervalData) { if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } // break the loop after we get the required number of parts in array if (\count($interval) >= $parts) { break; } // break the loop after we have reached the minimum unit if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } $actualParts = \count($interval); foreach ($interval as $index => &$item) { $item = $transChoice($item[0], $item[1], $index, $actualParts); } if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; $unit = $fallbackUnit[$short ? 1 : 0]; $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); } // join the interval parts by a space $time = $join($interval); unset($diffIntervalArray, $interval); if ($absolute) { return $time; } $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); if ($parts === 1) { if ($relativeToNow && $unit === 'day') { $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null; if ($specialTranslations && $options & $specialTranslations['option']) { $key = $specialTranslations[$isFuture ? 'future' : 'past']; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } } $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; } $time = [':time' => $time]; return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); } public function format(string $format): string { $output = parent::format($format); if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) { return $output; } $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate); return str_replace('(unknown)', $this->rawInterval->format('%a'), $output); } /** * Format the instance as a string using the forHumans() function. * * @throws Exception * * @return string */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if (!$format) { return $this->forHumans(); } if ($format instanceof Closure) { return $format($this); } return $this->format($format); } /** * Return native DateInterval PHP object matching the current instance. * * @example * ``` * var_dump(CarbonInterval::hours(2)->toDateInterval()); * ``` * * @return DateInterval */ public function toDateInterval(): DateInterval { return self::castIntervalToClass($this, DateInterval::class); } /** * Convert the interval to a CarbonPeriod. * * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. * * @return CarbonPeriod */ public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); } /** * Decompose the current interval into * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); } /** * Invert the interval. * * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this */ public function invert($inverted = null): static { $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; return $this; } protected function solveNegativeInterval(): static { if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { $this->years *= self::NEGATIVE; $this->months *= self::NEGATIVE; $this->dayz *= self::NEGATIVE; $this->hours *= self::NEGATIVE; $this->minutes *= self::NEGATIVE; $this->seconds *= self::NEGATIVE; $this->microseconds *= self::NEGATIVE; $this->invert(); } return $this; } /** * Add the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function sub($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } return $this->add($unit, -(float) $value); } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function subtract($unit, $value = 1): static { return $this->sub($unit, $value); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Multiply current instance given number of times. times() is naive, it multiplies each unit * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded * separately for each unit. * * Use times() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see multiply() * * @param float|int $factor * * @return $this */ public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; } /** * Divide current instance by a given divider. shares() is naive, it divides each unit separately * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours * and 7 minutes. * * Use shares() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see divide() * * @param float|int $divider * * @return $this */ public function shares($divider): static { return $this->times(1 / $divider); } protected function copyProperties(self $interval, $ignoreSign = false): static { $this->years = $interval->years; $this->months = $interval->months; $this->dayz = $interval->dayz; $this->hours = $interval->hours; $this->minutes = $interval->minutes; $this->seconds = $interval->seconds; $this->microseconds = $interval->microseconds; if (!$ignoreSign) { $this->invert = $interval->invert; } return $this; } /** * Multiply and cascade current instance by a given factor. * * @param float|int $factor * * @return $this */ public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); } /** * Divide and cascade current instance by a given divider. * * @param float|int $divider * * @return $this */ public function divide($divider): static { return $this->multiply(1 / $divider); } /** * Get the interval_spec string of a date interval. * * @param DateInterval $interval * * @return string */ public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), static::PERIOD_MONTHS => abs($interval->m), static::PERIOD_DAYS => abs($interval->d), ]); $skip = array_map([Unit::class, 'toNameIfUnit'], $skip); if ( $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) ) { $date = [ static::PERIOD_DAYS => abs($interval->days), ]; } $seconds = abs($interval->s); if ($microseconds && $interval->f > 0) { $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); } $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; foreach ($date as $key => $value) { $specString .= $value.$key; } if (\count($time) > 0) { $specString .= static::PERIOD_TIME_PREFIX; foreach ($time as $key => $value) { $specString .= $value.$key; } } return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; } /** * Get the interval_spec string. * * @return string */ public function spec(bool $microseconds = false): string { return static::getDateIntervalSpec($this, $microseconds); } /** * Comparing 2 date intervals. * * @param DateInterval $first * @param DateInterval $second * * @return int 0, 1 or -1 */ public static function compareDateIntervals(DateInterval $first, DateInterval $second): int { $current = Carbon::now(); $passed = $current->avoidMutation()->add($second); $current->add($first); return $current <=> $passed; } /** * Comparing with passed interval. * * @param DateInterval $interval * * @return int 0, 1 or -1 */ public function compare(DateInterval $interval): int { return static::compareDateIntervals($this, $interval); } /** * Convert overflowed values into bigger units. * * @return $this */ public function cascade(): static { return $this->doCascade(false); } public function hasNegativeValues(): bool { foreach ($this->toArray() as $value) { if ($value < 0) { return true; } } return false; } public function hasPositiveValues(): bool { foreach ($this->toArray() as $value) { if ($value > 0) { return true; } } return false; } /** * Get amount of given unit equivalent to the interval. * * @param string $unit * * @throws UnknownUnitException|UnitNotConfiguredException * * @return float */ public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see equalTo() * * @return bool */ public function eq($interval): bool { return $this->equalTo($interval); } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see notEqualTo() * * @return bool */ public function ne($interval): bool { return $this->notEqualTo($interval); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function notEqualTo($interval): bool { return !$this->eq($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThan() * * @return bool */ public function gt($interval): bool { return $this->greaterThan($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThanOrEqualTo() * * @return bool */ public function gte($interval): bool { return $this->greaterThanOrEqualTo($interval); } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThanOrEqualTo($interval): bool { return $this->greaterThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThan() * * @return bool */ public function lt($interval): bool { return $this->lessThan($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThanOrEqualTo() * * @return bool */ public function lte($interval): bool { return $this->lessThanOrEqualTo($interval); } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThanOrEqualTo($interval): bool { return $this->lessThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function between($interval1, $interval2, bool $equal = true): bool { return $equal ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) : $this->greaterThan($interval1) && $this->lessThan($interval2); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenIncluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenExcluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, false); } /** * Determines if the instance is between two others * * @example * ``` * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function isBetween($interval1, $interval2, bool $equal = true): bool { return $this->between($interval1, $interval2, $equal); } /** * Round the current instance at the given unit with given precision if specified and the given function. * * @throws Exception */ public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); } /** * Truncate the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function floorUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function ceilUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified. * * @param float|int|string|DateInterval|null $precision * @param string $function * * @throws Exception * * @return $this */ public function round($precision = 1, string $function = 'round'): static { return $this->roundWith($precision, $function); } /** * Round the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function floor(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function ceil(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'ceil'); } public function __unserialize(array $data): void { $properties = array_combine( array_map( static fn (mixed $key) => \is_string($key) ? str_replace('tzName', 'timezoneSetting', $key) : $key, array_keys($data), ), $data, ); if (method_exists(parent::class, '__unserialize')) { // PHP >= 8.2 parent::__unserialize($properties); return; } // PHP <= 8.1 // @codeCoverageIgnoreStart $properties = array_combine( array_map( static fn (string $property) => preg_replace('/^\0.+\0/', '', $property), array_keys($data), ), $data, ); $localStrictMode = $this->localStrictModeEnabled; $this->localStrictModeEnabled = false; $days = $properties['days'] ?? false; $this->days = $days === false ? false : (int) $days; $this->y = (int) ($properties['y'] ?? 0); $this->m = (int) ($properties['m'] ?? 0); $this->d = (int) ($properties['d'] ?? 0); $this->h = (int) ($properties['h'] ?? 0); $this->i = (int) ($properties['i'] ?? 0); $this->s = (int) ($properties['s'] ?? 0); $this->f = (float) ($properties['f'] ?? 0.0); // @phpstan-ignore-next-line $this->weekday = (int) ($properties['weekday'] ?? 0); // @phpstan-ignore-next-line $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0); // @phpstan-ignore-next-line $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0); $this->invert = (int) ($properties['invert'] ?? 0); // @phpstan-ignore-next-line $this->special_type = (int) ($properties['special_type'] ?? 0); // @phpstan-ignore-next-line $this->special_amount = (int) ($properties['special_amount'] ?? 0); // @phpstan-ignore-next-line $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0); // @phpstan-ignore-next-line $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0); parent::__construct(self::getDateIntervalSpec($this)); foreach ($properties as $property => $value) { if ($property === 'localStrictModeEnabled') { continue; } $this->$property = $value; } $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode; // @codeCoverageIgnoreEnd } /** * @template T * * @param T $interval * @param mixed $original * * @return T */ private static function withOriginal(mixed $interval, mixed $original): mixed { if ($interval instanceof self) { $interval->originalInput = $original; } return $interval; } private static function standardizeUnit(string $unit): string { $unit = rtrim($unit, 'sz').'s'; return $unit === 'days' ? 'dayz' : $unit; } private static function getFlipCascadeFactors(): array { if (!self::$flipCascadeFactors) { self::$flipCascadeFactors = []; foreach (self::getCascadeFactors() as $to => [$factor, $from]) { self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; } } return self::$flipCascadeFactors; } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object { $mainClass = DateInterval::class; if (!is_a($className, $mainClass, true)) { throw new InvalidCastException("$className is not a sub-class of $mainClass."); } $microseconds = $interval->f; $instance = self::buildInstance($interval, $className, $skip); if ($instance instanceof self) { $instance->originalInput = $interval; } if ($microseconds) { $instance->f = $microseconds; } if ($interval instanceof self && is_a($className, self::class, true)) { self::copyStep($interval, $instance); } self::copyNegativeUnits($interval, $instance); return self::withOriginal($instance, $interval); } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function buildInstance( DateInterval $interval, string $className, array $skip = [], ): object { $serialization = self::buildSerializationString($interval, $className, $skip); return match ($serialization) { null => new $className(static::getDateIntervalSpec($interval, false, $skip)), default => unserialize($serialization), }; } /** * As demonstrated by rlanvin (https://github.com/rlanvin) in * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438 * * Modifying the output of serialize() to change the class name and unserializing * the tweaked string allows creating new interval instances where the ->days * property can be set. It's not possible neither with `new` nto with `__set_state`. * * It has a non-negligible performance cost, so we'll use this method only if * $interval->days !== false. */ private static function buildSerializationString( DateInterval $interval, string $className, array $skip = [], ): ?string { if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) { return null; } // De-enhance CarbonInterval objects to be serializable back to DateInterval if ($interval instanceof self && !is_a($className, self::class, true)) { $interval = clone $interval; unset($interval->timezoneSetting); unset($interval->originalInput); unset($interval->startDate); unset($interval->endDate); unset($interval->rawInterval); unset($interval->absolute); unset($interval->initialValues); unset($interval->clock); unset($interval->step); unset($interval->localMonthsOverflow); unset($interval->localYearsOverflow); unset($interval->localStrictModeEnabled); unset($interval->localHumanDiffOptions); unset($interval->localToStringFormat); unset($interval->localSerializer); unset($interval->localMacros); unset($interval->localGenericMacros); unset($interval->localFormatFunction); unset($interval->localTranslator); } $serialization = serialize($interval); $inputClass = $interval::class; $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":'; if (!str_starts_with($serialization, $expectedStart)) { return null; // @codeCoverageIgnore } return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart)); } private static function copyStep(self $from, self $to): void { $to->setStep($from->getStep()); } private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void { $to->invert = $from->invert; foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { if ($from->$unit < 0) { self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE); } } } private function invertCascade(array $values): static { return $this->set(array_map(function ($value) { return -$value; }, $values))->doCascade(true)->invert(); } private function doCascade(bool $deep): static { $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { if ($$key === 'dayz') { $$key = 'daysExcludeWeeks'; } } $value = $newData[$source]; $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; $decimalPart = fmod($newData[$source], 1); if ($decimalPart !== 0.0) { $unit = $source; foreach ($previous as [$subUnit, $subFactor]) { $newData[$unit] -= $decimalPart; $newData[$subUnit] += $decimalPart * $subFactor; $decimalPart = fmod($newData[$subUnit], 1); if ($decimalPart === 0.0) { break; } $unit = $subUnit; } } array_unshift($previous, [$source, $factor]); } $positive = null; if (!$deep) { foreach ($newData as $value) { if ($value) { if ($positive === null) { $positive = ($value > 0); continue; } if (($value > 0) !== $positive) { return $this->invertCascade($originalData) ->solveNegativeInterval(); } } } } return $this->set($newData) ->solveNegativeInterval(); } private function needsDeclension(string $mode, int $index, int $parts): bool { return match ($mode) { 'last' => $index === $parts - 1, default => true, }; } private function checkIntegerValue(string $name, mixed $value): void { if (\is_int($value)) { return; } $this->assertSafeForInteger($name, $value); if (\is_float($value) && (((float) (int) $value) === $value)) { return; } if (!self::$floatSettersEnabled) { $type = \gettype($value); @trigger_error( "Since 2.70.0, it's deprecated to pass $type value for $name.\n". "It's truncated when stored as an integer interval unit.\n". "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", \E_USER_DEPRECATED, ); } } /** * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. */ private function assertSafeForInteger(string $name, mixed $value): void { if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); } } private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void { if (self::$floatSettersEnabled) { $floatValue = (float) $value; $base = (float) $integerValue; if ($floatValue === $base) { return; } $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; $upper = true; foreach ($units as $property => $name) { if ($name === $unit) { $upper = false; continue; } if (!$upper && $this->$property !== 0) { throw new RuntimeException( "You cannot set $unit to a float value as $name would be overridden, ". 'set it first to 0 explicitly if you really want to erase its value' ); } } $this->add($unit, $floatValue - $base); } } private function getInnerValues(): array { return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days]; } private function checkStartAndEnd(): void { if ( $this->initialValues !== null && ($this->startDate !== null || $this->endDate !== null) && $this->initialValues !== $this->getInnerValues() ) { $this->absolute = false; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; } } /** @return $this */ private function setSetting(string $setting, mixed $value): self { switch ($setting) { case 'timezoneSetting': return $value === null ? $this : $this->setTimezone($value); case 'step': $this->setStep($value); return $this; case 'localMonthsOverflow': return $value === null ? $this : $this->settings(['monthOverflow' => $value]); case 'localYearsOverflow': return $value === null ? $this : $this->settings(['yearOverflow' => $value]); case 'localStrictModeEnabled': case 'localHumanDiffOptions': case 'localToStringFormat': case 'localSerializer': case 'localMacros': case 'localGenericMacros': case 'localFormatFunction': case 'localTranslator': $this->$setting = $value; return $this; default: // Drop unknown settings return $this; } } private static function incrementUnit(DateInterval $instance, string $unit, int $value): void { if ($value === 0) { return; } // @codeCoverageIgnoreStart if (PHP_VERSION_ID !== 8_03_20) { $instance->$unit += $value; return; } // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value); // @codeCoverageIgnoreEnd } /** @codeCoverageIgnore */ private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void { switch ($unit) { case 'y': $instance->y = $value; break; case 'm': $instance->m = $value; break; case 'd': $instance->d = $value; break; case 'h': $instance->h = $value; break; case 'i': $instance->i = $value; break; case 's': $instance->s = $value; break; default: $instance->$unit = $value; } } }
PHP
{ "end_line": 2454, "name": "multiply", "signature": "public function multiply($factor): static", "start_line": 2435 }
{ "class_name": "CarbonInterval", "class_signature": "class CarbonInterval implements CarbonConverterInterface, UnitValue", "namespace": "Carbon" }
total
Carbon/src/Carbon/CarbonInterval.php
public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH], 'day' => ['week' => Carbon::DAYS_PER_WEEK], 'hour' => ['day' => Carbon::HOURS_PER_DAY], 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], ]; return $defaults[$source][$target] ?? null; } /** * Returns current config for days per week. * * @return int|float */ public static function getDaysPerWeek() { return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; } /** * Returns current config for hours per day. * * @return int|float */ public static function getHoursPerDay() { return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; } /** * Returns current config for minutes per hour. * * @return int|float */ public static function getMinutesPerHour() { return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; } /** * Returns current config for seconds per minute. * * @return int|float */ public static function getSecondsPerMinute() { return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMillisecondsPerSecond() { return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMicrosecondsPerMillisecond() { return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; } /** * Create a new CarbonInterval instance from specific values. * This is an alias for the constructor that allows better fluent * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than * (new CarbonInterval(1))->fn(). * * @param int $years * @param int $months * @param int $weeks * @param int $days * @param int $hours * @param int $minutes * @param int $seconds * @param int $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. * * @return static */ public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); } /** * Parse a string into a new CarbonInterval object according to the specified format. * * @example * ``` * echo Carboninterval::createFromFormat('H:i', '1:30'); * ``` * * @param string $format Format of the $interval input string * @param string|null $interval Input string to convert into an interval * * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. * * @return static */ public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; } /** * Return the original source used to create the current interval. * * @return array|int|string|DateInterval|mixed|null */ public function original() { return $this->originalInput; } /** * Return the start date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function start(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->startDate; } /** * Return the end date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function end(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->endDate; } /** * Get rid of the original input, start date and end date that may be kept in memory. * * @return $this */ public function optimize(): static { $this->originalInput = null; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; $this->absolute = false; return $this; } /** * Get a copy of the instance. * * @return static */ public function copy(): static { $date = new static(0); $date->copyProperties($this); $date->step = $this->step; return $date; } /** * Get a copy of the instance. * * @return static */ public function clone(): static { return $this->copy(); } /** * Provide static helpers to create instances. Allows CarbonInterval::years(3). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @return static|mixed|null */ public static function __callStatic(string $method, array $parameters) { try { $interval = new static(0); $localStrictModeEnabled = $interval->localStrictModeEnabled; $interval->localStrictModeEnabled = true; $result = static::hasMacro($method) ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { return $interval->callMacro($method, $parameters); }) : $interval->$method(...$parameters); $interval->localStrictModeEnabled = $localStrictModeEnabled; return $result; } catch (BadFluentSetterException $exception) { if (Carbon::isStrictModeEnabled()) { throw new BadFluentConstructorException($method, 0, $exception); } return null; } } /** * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. * * @param array $dump data as exported by var_export() * * @return static */ #[ReturnTypeWillChange] public static function __set_state($dump) { /** @noinspection PhpVoidFunctionResultUsedInspection */ /** @var DateInterval $dateInterval */ $dateInterval = parent::__set_state($dump); return static::instance($dateInterval); } /** * Return the current context from inside a macro callee or a new one if static. * * @return static */ protected static function this(): static { return end(static::$macroContextStack) ?: new static(0); } /** * Creates a CarbonInterval from string. * * Format: * * Suffix | Unit | Example | DateInterval expression * -------|---------|---------|------------------------ * y | years | 1y | P1Y * mo | months | 3mo | P3M * w | weeks | 2w | P2W * d | days | 28d | P28D * h | hours | 4h | PT4H * m | minutes | 12m | PT12M * s | seconds | 59s | PT59S * * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. * * Special cases: * - An empty string will return a zero interval * - Fractions are allowed for weeks, days, hours and minutes and will be converted * and rounded to the next smaller value (caution: 0.5w = 4d) * * @param string $intervalDefinition * * @throws InvalidIntervalException * * @return static */ public static function fromString(string $intervalDefinition): static { if (empty($intervalDefinition)) { return self::withOriginal(new static(0), $intervalDefinition); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $milliseconds = 0; $microseconds = 0; $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ([$part, $value, $unit] = array_shift($parts)) { $intValue = (int) $value; $fraction = (float) $value - $intValue; // Fix calculation precision switch (round($fraction, 6)) { case 1: $fraction = 0; $intValue++; break; case 0: $fraction = 0; break; } switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { case 'millennia': case 'millennium': $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; break; case 'century': case 'centuries': $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; break; case 'decade': case 'decades': $years += $intValue * CarbonInterface::YEARS_PER_DECADE; break; case 'year': case 'years': case 'y': case 'yr': case 'yrs': $years += $intValue; break; case 'quarter': case 'quarters': $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; break; case 'month': case 'months': case 'mo': case 'mos': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; } break; case 'second': case 'seconds': case 's': $seconds += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; } break; case 'millisecond': case 'milliseconds': case 'milli': case 'ms': $milliseconds += $intValue; if ($fraction) { $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); } break; case 'microsecond': case 'microseconds': case 'micro': case 'µs': $microseconds += $intValue; break; default: throw new InvalidIntervalException( "Invalid part $part in definition $intervalDefinition", ); } } return self::withOriginal( new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds), $intervalDefinition, ); } /** * Creates a CarbonInterval from string using a different locale. * * @param string $interval interval string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be used instead. * * @return static */ public static function parseFromLocale(string $interval, ?string $locale = null): static { return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE)); } /** * Create an interval from the difference between 2 dates. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $start * @param \Carbon\Carbon|\DateTimeInterface|mixed $end * * @return static */ public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; } /** * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function abs(bool $absolute = false): static { if ($absolute && $this->invert) { $this->invert(); } return $this; } /** * @alias abs * * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function absolute(bool $absolute = true): static { return $this->abs($absolute); } /** * Cast the current instance into the given class. * * @template T of DateInterval * * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { return self::castIntervalToClass($this, $className); } /** * Create a CarbonInterval instance from a DateInterval one. Can not instance * DateInterval objects created from DateTime::diff() as you can't externally * set the $days field. * * @param DateInterval $interval * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static */ public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static { if ($skipCopy && $interval instanceof static) { return $interval; } return self::castIntervalToClass($interval, static::class, $skip); } /** * Make a CarbonInterval instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static|null */ public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); } protected static function makeFromString(string $interval): ?self { $interval = preg_replace('/\s+/', ' ', trim($interval)); if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { return static::fromString($interval); } $intervalInstance = static::createFromDateString($interval); return $intervalInstance->isEmpty() ? null : $intervalInstance; } protected function resolveInterval($interval): ?self { if (!($interval instanceof self)) { return self::make($interval); } return $interval; } /** * Sets up a DateInterval from the relative parts of the string. * * @param string $datetime * * @return static * * @link https://php.net/manual/en/dateinterval.createfromdatestring.php */ public static function createFromDateString(string $datetime): static { $string = strtr($datetime, [ ',' => ' ', ' and ' => ' ', ]); $previousException = null; try { $interval = parent::createFromDateString($string); } catch (Throwable $exception) { $interval = null; $previousException = $exception; } $interval ?: throw new InvalidFormatException( 'Could not create interval from: '.var_export($datetime, true), previous: $previousException, ); if (!($interval instanceof static)) { $interval = static::instance($interval); } return self::withOriginal($interval, $datetime); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the CarbonInterval object. */ public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; } /** * Get a part of the CarbonInterval object. */ public function __get(string $name): int|float|string|null { return $this->get($name); } /** * Set a part of the CarbonInterval object. * * @param Unit|string|array $name * @param int $value * * @throws UnknownSetterException * * @return $this */ public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; } /** * Set a part of the CarbonInterval object. * * @param string $name * @param int $value * * @throws UnknownSetterException */ public function __set(string $name, $value) { $this->set($name, $value); } /** * Allow setting of weeks and days to be cumulative. * * @param int $weeks Number of weeks to set * @param int $days Number of days to set * * @return static */ public function weeksAndDays(int $weeks, int $days): static { $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; return $this; } /** * Returns true if the interval is empty for each unit. * * @return bool */ public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonInterval::macro('twice', function () { * return $this->times(2); * }); * echo CarbonInterval::hours(2)->twice(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonInterval::mixin(new class { * public function daysToHours() { * return function () { * $this->hours += $this->days; * $this->days = 0; * * return $this; * }; * } * public function hoursToDays() { * return function () { * $this->days += $this->hours; * $this->hours = 0; * * return $this; * }; * } * }); * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; * echo CarbonInterval::days(5)->daysToHours() . "\n"; * ``` * * @param object|string $mixin * * @throws ReflectionException * * @return void */ public static function mixin($mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Call given macro. * * @param string $name * @param array $parameters * * @return mixed */ protected function callMacro(string $name, array $parameters) { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadFluentSetterException|Throwable * * @return static|int|float|string */ public function __call(string $method, array $parameters) { if (static::hasMacro($method)) { return static::bindMacroContext($this, function () use (&$method, &$parameters) { return $this->callMacro($method, $parameters); }); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); return $this->{$match['method']}($value, $match['unit']); } $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); try { $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); } } return $this; } protected function getForHumansInitialVariables($syntax, $short): array { if (\is_array($syntax)) { return $syntax; } if (\is_int($short)) { return [ 'parts' => $short, 'short' => false, ]; } if (\is_bool($syntax)) { return [ 'short' => $syntax, 'syntax' => CarbonInterface::DIFF_ABSOLUTE, ]; } return []; } /** * @param mixed $syntax * @param mixed $short * @param mixed $parts * @param mixed $options * * @return array */ protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array { $optionalSpace = ' '; $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; /** @var bool|string $join */ $join = $default === '' ? '' : ' '; /** @var bool|array|string $altNumbers */ $altNumbers = false; $aUnit = false; $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); $skip = array_map( static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit, (array) $skip, ); $skip = array_map( 'strtolower', array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''), ); $syntax ??= CarbonInterface::DIFF_ABSOLUTE; if ($parts === self::NO_LIMIT) { $parts = INF; } $options ??= static::getHumanDiffOptions(); if ($join === false) { $join = ' '; } elseif ($join === true) { $join = [ $default, $this->getTranslationMessage('list.1') ?? $default, ]; } if ($altNumbers && $altNumbers !== true) { $language = new Language($this->locale); $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { [$default, $last] = $join; if ($default !== ' ') { $optionalSpace = ''; } $join = function ($list) use ($default, $last) { if (\count($list) < 2) { return implode('', $list); } $end = array_pop($list); return implode($default, $list).$last.$end; }; } if (\is_string($join)) { if ($join !== ' ') { $optionalSpace = ''; } $glue = $join; $join = static fn ($list) => implode($glue, $list); } $interpolations = [ ':optional-space' => $optionalSpace, ]; $translator ??= isset($locale) ? Translator::get($locale) : null; return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator]; } protected static function getRoundingMethodFromOptions(int $options): ?string { if ($options & CarbonInterface::ROUND) { return 'round'; } if ($options & CarbonInterface::CEIL) { return 'ceil'; } if ($options & CarbonInterface::FLOOR) { return 'floor'; } return null; } /** * Returns interval values as an array where key are the unit names and values the counts. * * @return int[] */ public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; } /** * Returns interval non-zero values as an array where key are the unit names and values the counts. * * @return int[] */ public function getNonZeroValues(): array { return array_filter($this->toArray(), 'intval'); } /** * Returns interval values as an array where key are the unit names and values the counts * from the biggest non-zero one the the smallest non-zero one. * * @return int[] */ public function getValuesSequence(): array { $nonZeroValues = $this->getNonZeroValues(); if ($nonZeroValues === []) { return []; } $keys = array_keys($nonZeroValues); $firstKey = $keys[0]; $lastKey = $keys[\count($keys) - 1]; $values = []; $record = false; foreach ($this->toArray() as $unit => $count) { if ($unit === $firstKey) { $record = true; } if ($record) { $values[$unit] = $count; } if ($unit === $lastKey) { $record = false; } } return $values; } /** * Get the current interval in a human readable format in the current locale. * * @example * ``` * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; * ``` * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: -1: no limits) * @param int $options human diff options * * @throws Exception * * @return string */ public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string { /* @var TranslatorInterface|null $translator */ [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this ->getForHumansParameters($syntax, $short, $parts, $options); $interval = []; $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; $count = 1; $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); $declensionMode = null; $translator ??= $this->getLocalTranslator(); $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); if ($this->needsDeclension($declensionMode, $index, $parts)) { // Some languages have special pluralization for past and future tense. $key = $unit.'_'.$transId; $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); if ($result !== $key) { return $result; } } } $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); if ($result !== $unit) { return $result; } return null; }; $intervalValues = $this; $method = static::getRoundingMethodFromOptions($options); if ($method) { $previousCount = INF; while ( \count($intervalValues->getNonZeroValues()) > $parts && ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 ) { $index = min($count, $previousCount - 1) - 2; if ($index < 0) { break; } $intervalValues = $this->copy()->roundUnit( $keys[$index], 1, $method, ); $previousCount = $count; } } $diffIntervalArray = [ ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], ]; if (!empty($skip)) { foreach ($diffIntervalArray as $index => &$unitData) { $nextIndex = $index + 1; if ($unitData['value'] && isset($diffIntervalArray[$nextIndex]) && \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) ) { $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); $unitData['value'] = 0; } } } $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; } } if (!$absolute) { return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); }; $fallbackUnit = ['second', 's']; foreach ($diffIntervalArray as $diffIntervalData) { if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } // break the loop after we get the required number of parts in array if (\count($interval) >= $parts) { break; } // break the loop after we have reached the minimum unit if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } $actualParts = \count($interval); foreach ($interval as $index => &$item) { $item = $transChoice($item[0], $item[1], $index, $actualParts); } if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; $unit = $fallbackUnit[$short ? 1 : 0]; $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); } // join the interval parts by a space $time = $join($interval); unset($diffIntervalArray, $interval); if ($absolute) { return $time; } $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); if ($parts === 1) { if ($relativeToNow && $unit === 'day') { $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null; if ($specialTranslations && $options & $specialTranslations['option']) { $key = $specialTranslations[$isFuture ? 'future' : 'past']; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } } $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; } $time = [':time' => $time]; return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); } public function format(string $format): string { $output = parent::format($format); if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) { return $output; } $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate); return str_replace('(unknown)', $this->rawInterval->format('%a'), $output); } /** * Format the instance as a string using the forHumans() function. * * @throws Exception * * @return string */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if (!$format) { return $this->forHumans(); } if ($format instanceof Closure) { return $format($this); } return $this->format($format); } /** * Return native DateInterval PHP object matching the current instance. * * @example * ``` * var_dump(CarbonInterval::hours(2)->toDateInterval()); * ``` * * @return DateInterval */ public function toDateInterval(): DateInterval { return self::castIntervalToClass($this, DateInterval::class); } /** * Convert the interval to a CarbonPeriod. * * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. * * @return CarbonPeriod */ public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); } /** * Decompose the current interval into * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); } /** * Invert the interval. * * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this */ public function invert($inverted = null): static { $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; return $this; } protected function solveNegativeInterval(): static { if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { $this->years *= self::NEGATIVE; $this->months *= self::NEGATIVE; $this->dayz *= self::NEGATIVE; $this->hours *= self::NEGATIVE; $this->minutes *= self::NEGATIVE; $this->seconds *= self::NEGATIVE; $this->microseconds *= self::NEGATIVE; $this->invert(); } return $this; } /** * Add the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function sub($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } return $this->add($unit, -(float) $value); } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function subtract($unit, $value = 1): static { return $this->sub($unit, $value); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Multiply current instance given number of times. times() is naive, it multiplies each unit * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded * separately for each unit. * * Use times() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see multiply() * * @param float|int $factor * * @return $this */ public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; } /** * Divide current instance by a given divider. shares() is naive, it divides each unit separately * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours * and 7 minutes. * * Use shares() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see divide() * * @param float|int $divider * * @return $this */ public function shares($divider): static { return $this->times(1 / $divider); } protected function copyProperties(self $interval, $ignoreSign = false): static { $this->years = $interval->years; $this->months = $interval->months; $this->dayz = $interval->dayz; $this->hours = $interval->hours; $this->minutes = $interval->minutes; $this->seconds = $interval->seconds; $this->microseconds = $interval->microseconds; if (!$ignoreSign) { $this->invert = $interval->invert; } return $this; } /** * Multiply and cascade current instance by a given factor. * * @param float|int $factor * * @return $this */ public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); } /** * Divide and cascade current instance by a given divider. * * @param float|int $divider * * @return $this */ public function divide($divider): static { return $this->multiply(1 / $divider); } /** * Get the interval_spec string of a date interval. * * @param DateInterval $interval * * @return string */ public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), static::PERIOD_MONTHS => abs($interval->m), static::PERIOD_DAYS => abs($interval->d), ]); $skip = array_map([Unit::class, 'toNameIfUnit'], $skip); if ( $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) ) { $date = [ static::PERIOD_DAYS => abs($interval->days), ]; } $seconds = abs($interval->s); if ($microseconds && $interval->f > 0) { $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); } $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; foreach ($date as $key => $value) { $specString .= $value.$key; } if (\count($time) > 0) { $specString .= static::PERIOD_TIME_PREFIX; foreach ($time as $key => $value) { $specString .= $value.$key; } } return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; } /** * Get the interval_spec string. * * @return string */ public function spec(bool $microseconds = false): string { return static::getDateIntervalSpec($this, $microseconds); } /** * Comparing 2 date intervals. * * @param DateInterval $first * @param DateInterval $second * * @return int 0, 1 or -1 */ public static function compareDateIntervals(DateInterval $first, DateInterval $second): int { $current = Carbon::now(); $passed = $current->avoidMutation()->add($second); $current->add($first); return $current <=> $passed; } /** * Comparing with passed interval. * * @param DateInterval $interval * * @return int 0, 1 or -1 */ public function compare(DateInterval $interval): int { return static::compareDateIntervals($this, $interval); } /** * Convert overflowed values into bigger units. * * @return $this */ public function cascade(): static { return $this->doCascade(false); } public function hasNegativeValues(): bool { foreach ($this->toArray() as $value) { if ($value < 0) { return true; } } return false; } public function hasPositiveValues(): bool { foreach ($this->toArray() as $value) { if ($value > 0) { return true; } } return false; } /** * Get amount of given unit equivalent to the interval. * * @param string $unit * * @throws UnknownUnitException|UnitNotConfiguredException * * @return float */ public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see equalTo() * * @return bool */ public function eq($interval): bool { return $this->equalTo($interval); } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see notEqualTo() * * @return bool */ public function ne($interval): bool { return $this->notEqualTo($interval); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function notEqualTo($interval): bool { return !$this->eq($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThan() * * @return bool */ public function gt($interval): bool { return $this->greaterThan($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThanOrEqualTo() * * @return bool */ public function gte($interval): bool { return $this->greaterThanOrEqualTo($interval); } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThanOrEqualTo($interval): bool { return $this->greaterThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThan() * * @return bool */ public function lt($interval): bool { return $this->lessThan($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThanOrEqualTo() * * @return bool */ public function lte($interval): bool { return $this->lessThanOrEqualTo($interval); } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThanOrEqualTo($interval): bool { return $this->lessThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function between($interval1, $interval2, bool $equal = true): bool { return $equal ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) : $this->greaterThan($interval1) && $this->lessThan($interval2); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenIncluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenExcluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, false); } /** * Determines if the instance is between two others * * @example * ``` * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function isBetween($interval1, $interval2, bool $equal = true): bool { return $this->between($interval1, $interval2, $equal); } /** * Round the current instance at the given unit with given precision if specified and the given function. * * @throws Exception */ public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); } /** * Truncate the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function floorUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function ceilUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified. * * @param float|int|string|DateInterval|null $precision * @param string $function * * @throws Exception * * @return $this */ public function round($precision = 1, string $function = 'round'): static { return $this->roundWith($precision, $function); } /** * Round the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function floor(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function ceil(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'ceil'); } public function __unserialize(array $data): void { $properties = array_combine( array_map( static fn (mixed $key) => \is_string($key) ? str_replace('tzName', 'timezoneSetting', $key) : $key, array_keys($data), ), $data, ); if (method_exists(parent::class, '__unserialize')) { // PHP >= 8.2 parent::__unserialize($properties); return; } // PHP <= 8.1 // @codeCoverageIgnoreStart $properties = array_combine( array_map( static fn (string $property) => preg_replace('/^\0.+\0/', '', $property), array_keys($data), ), $data, ); $localStrictMode = $this->localStrictModeEnabled; $this->localStrictModeEnabled = false; $days = $properties['days'] ?? false; $this->days = $days === false ? false : (int) $days; $this->y = (int) ($properties['y'] ?? 0); $this->m = (int) ($properties['m'] ?? 0); $this->d = (int) ($properties['d'] ?? 0); $this->h = (int) ($properties['h'] ?? 0); $this->i = (int) ($properties['i'] ?? 0); $this->s = (int) ($properties['s'] ?? 0); $this->f = (float) ($properties['f'] ?? 0.0); // @phpstan-ignore-next-line $this->weekday = (int) ($properties['weekday'] ?? 0); // @phpstan-ignore-next-line $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0); // @phpstan-ignore-next-line $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0); $this->invert = (int) ($properties['invert'] ?? 0); // @phpstan-ignore-next-line $this->special_type = (int) ($properties['special_type'] ?? 0); // @phpstan-ignore-next-line $this->special_amount = (int) ($properties['special_amount'] ?? 0); // @phpstan-ignore-next-line $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0); // @phpstan-ignore-next-line $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0); parent::__construct(self::getDateIntervalSpec($this)); foreach ($properties as $property => $value) { if ($property === 'localStrictModeEnabled') { continue; } $this->$property = $value; } $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode; // @codeCoverageIgnoreEnd } /** * @template T * * @param T $interval * @param mixed $original * * @return T */ private static function withOriginal(mixed $interval, mixed $original): mixed { if ($interval instanceof self) { $interval->originalInput = $original; } return $interval; } private static function standardizeUnit(string $unit): string { $unit = rtrim($unit, 'sz').'s'; return $unit === 'days' ? 'dayz' : $unit; } private static function getFlipCascadeFactors(): array { if (!self::$flipCascadeFactors) { self::$flipCascadeFactors = []; foreach (self::getCascadeFactors() as $to => [$factor, $from]) { self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; } } return self::$flipCascadeFactors; } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object { $mainClass = DateInterval::class; if (!is_a($className, $mainClass, true)) { throw new InvalidCastException("$className is not a sub-class of $mainClass."); } $microseconds = $interval->f; $instance = self::buildInstance($interval, $className, $skip); if ($instance instanceof self) { $instance->originalInput = $interval; } if ($microseconds) { $instance->f = $microseconds; } if ($interval instanceof self && is_a($className, self::class, true)) { self::copyStep($interval, $instance); } self::copyNegativeUnits($interval, $instance); return self::withOriginal($instance, $interval); } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function buildInstance( DateInterval $interval, string $className, array $skip = [], ): object { $serialization = self::buildSerializationString($interval, $className, $skip); return match ($serialization) { null => new $className(static::getDateIntervalSpec($interval, false, $skip)), default => unserialize($serialization), }; } /** * As demonstrated by rlanvin (https://github.com/rlanvin) in * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438 * * Modifying the output of serialize() to change the class name and unserializing * the tweaked string allows creating new interval instances where the ->days * property can be set. It's not possible neither with `new` nto with `__set_state`. * * It has a non-negligible performance cost, so we'll use this method only if * $interval->days !== false. */ private static function buildSerializationString( DateInterval $interval, string $className, array $skip = [], ): ?string { if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) { return null; } // De-enhance CarbonInterval objects to be serializable back to DateInterval if ($interval instanceof self && !is_a($className, self::class, true)) { $interval = clone $interval; unset($interval->timezoneSetting); unset($interval->originalInput); unset($interval->startDate); unset($interval->endDate); unset($interval->rawInterval); unset($interval->absolute); unset($interval->initialValues); unset($interval->clock); unset($interval->step); unset($interval->localMonthsOverflow); unset($interval->localYearsOverflow); unset($interval->localStrictModeEnabled); unset($interval->localHumanDiffOptions); unset($interval->localToStringFormat); unset($interval->localSerializer); unset($interval->localMacros); unset($interval->localGenericMacros); unset($interval->localFormatFunction); unset($interval->localTranslator); } $serialization = serialize($interval); $inputClass = $interval::class; $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":'; if (!str_starts_with($serialization, $expectedStart)) { return null; // @codeCoverageIgnore } return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart)); } private static function copyStep(self $from, self $to): void { $to->setStep($from->getStep()); } private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void { $to->invert = $from->invert; foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { if ($from->$unit < 0) { self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE); } } } private function invertCascade(array $values): static { return $this->set(array_map(function ($value) { return -$value; }, $values))->doCascade(true)->invert(); } private function doCascade(bool $deep): static { $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { if ($$key === 'dayz') { $$key = 'daysExcludeWeeks'; } } $value = $newData[$source]; $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; $decimalPart = fmod($newData[$source], 1); if ($decimalPart !== 0.0) { $unit = $source; foreach ($previous as [$subUnit, $subFactor]) { $newData[$unit] -= $decimalPart; $newData[$subUnit] += $decimalPart * $subFactor; $decimalPart = fmod($newData[$subUnit], 1); if ($decimalPart === 0.0) { break; } $unit = $subUnit; } } array_unshift($previous, [$source, $factor]); } $positive = null; if (!$deep) { foreach ($newData as $value) { if ($value) { if ($positive === null) { $positive = ($value > 0); continue; } if (($value > 0) !== $positive) { return $this->invertCascade($originalData) ->solveNegativeInterval(); } } } } return $this->set($newData) ->solveNegativeInterval(); } private function needsDeclension(string $mode, int $index, int $parts): bool { return match ($mode) { 'last' => $index === $parts - 1, default => true, }; } private function checkIntegerValue(string $name, mixed $value): void { if (\is_int($value)) { return; } $this->assertSafeForInteger($name, $value); if (\is_float($value) && (((float) (int) $value) === $value)) { return; } if (!self::$floatSettersEnabled) { $type = \gettype($value); @trigger_error( "Since 2.70.0, it's deprecated to pass $type value for $name.\n". "It's truncated when stored as an integer interval unit.\n". "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", \E_USER_DEPRECATED, ); } } /** * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. */ private function assertSafeForInteger(string $name, mixed $value): void { if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); } } private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void { if (self::$floatSettersEnabled) { $floatValue = (float) $value; $base = (float) $integerValue; if ($floatValue === $base) { return; } $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; $upper = true; foreach ($units as $property => $name) { if ($name === $unit) { $upper = false; continue; } if (!$upper && $this->$property !== 0) { throw new RuntimeException( "You cannot set $unit to a float value as $name would be overridden, ". 'set it first to 0 explicitly if you really want to erase its value' ); } } $this->add($unit, $floatValue - $base); } } private function getInnerValues(): array { return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days]; } private function checkStartAndEnd(): void { if ( $this->initialValues !== null && ($this->startDate !== null || $this->endDate !== null) && $this->initialValues !== $this->getInnerValues() ) { $this->absolute = false; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; } } /** @return $this */ private function setSetting(string $setting, mixed $value): self { switch ($setting) { case 'timezoneSetting': return $value === null ? $this : $this->setTimezone($value); case 'step': $this->setStep($value); return $this; case 'localMonthsOverflow': return $value === null ? $this : $this->settings(['monthOverflow' => $value]); case 'localYearsOverflow': return $value === null ? $this : $this->settings(['yearOverflow' => $value]); case 'localStrictModeEnabled': case 'localHumanDiffOptions': case 'localToStringFormat': case 'localSerializer': case 'localMacros': case 'localGenericMacros': case 'localFormatFunction': case 'localTranslator': $this->$setting = $value; return $this; default: // Drop unknown settings return $this; } } private static function incrementUnit(DateInterval $instance, string $unit, int $value): void { if ($value === 0) { return; } // @codeCoverageIgnoreStart if (PHP_VERSION_ID !== 8_03_20) { $instance->$unit += $value; return; } // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value); // @codeCoverageIgnoreEnd } /** @codeCoverageIgnore */ private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void { switch ($unit) { case 'y': $instance->y = $value; break; case 'm': $instance->m = $value; break; case 'd': $instance->d = $value; break; case 'h': $instance->h = $value; break; case 'i': $instance->i = $value; break; case 's': $instance->s = $value; break; default: $instance->$unit = $value; } } }
PHP
{ "end_line": 2696, "name": "total", "signature": "public function total(string $unit): float", "start_line": 2602 }
{ "class_name": "CarbonInterval", "class_signature": "class CarbonInterval implements CarbonConverterInterface, UnitValue", "namespace": "Carbon" }
equalTo
Carbon/src/Carbon/CarbonInterval.php
public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH], 'day' => ['week' => Carbon::DAYS_PER_WEEK], 'hour' => ['day' => Carbon::HOURS_PER_DAY], 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], ]; return $defaults[$source][$target] ?? null; } /** * Returns current config for days per week. * * @return int|float */ public static function getDaysPerWeek() { return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; } /** * Returns current config for hours per day. * * @return int|float */ public static function getHoursPerDay() { return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; } /** * Returns current config for minutes per hour. * * @return int|float */ public static function getMinutesPerHour() { return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; } /** * Returns current config for seconds per minute. * * @return int|float */ public static function getSecondsPerMinute() { return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMillisecondsPerSecond() { return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMicrosecondsPerMillisecond() { return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; } /** * Create a new CarbonInterval instance from specific values. * This is an alias for the constructor that allows better fluent * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than * (new CarbonInterval(1))->fn(). * * @param int $years * @param int $months * @param int $weeks * @param int $days * @param int $hours * @param int $minutes * @param int $seconds * @param int $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. * * @return static */ public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); } /** * Parse a string into a new CarbonInterval object according to the specified format. * * @example * ``` * echo Carboninterval::createFromFormat('H:i', '1:30'); * ``` * * @param string $format Format of the $interval input string * @param string|null $interval Input string to convert into an interval * * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. * * @return static */ public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; } /** * Return the original source used to create the current interval. * * @return array|int|string|DateInterval|mixed|null */ public function original() { return $this->originalInput; } /** * Return the start date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function start(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->startDate; } /** * Return the end date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function end(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->endDate; } /** * Get rid of the original input, start date and end date that may be kept in memory. * * @return $this */ public function optimize(): static { $this->originalInput = null; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; $this->absolute = false; return $this; } /** * Get a copy of the instance. * * @return static */ public function copy(): static { $date = new static(0); $date->copyProperties($this); $date->step = $this->step; return $date; } /** * Get a copy of the instance. * * @return static */ public function clone(): static { return $this->copy(); } /** * Provide static helpers to create instances. Allows CarbonInterval::years(3). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @return static|mixed|null */ public static function __callStatic(string $method, array $parameters) { try { $interval = new static(0); $localStrictModeEnabled = $interval->localStrictModeEnabled; $interval->localStrictModeEnabled = true; $result = static::hasMacro($method) ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { return $interval->callMacro($method, $parameters); }) : $interval->$method(...$parameters); $interval->localStrictModeEnabled = $localStrictModeEnabled; return $result; } catch (BadFluentSetterException $exception) { if (Carbon::isStrictModeEnabled()) { throw new BadFluentConstructorException($method, 0, $exception); } return null; } } /** * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. * * @param array $dump data as exported by var_export() * * @return static */ #[ReturnTypeWillChange] public static function __set_state($dump) { /** @noinspection PhpVoidFunctionResultUsedInspection */ /** @var DateInterval $dateInterval */ $dateInterval = parent::__set_state($dump); return static::instance($dateInterval); } /** * Return the current context from inside a macro callee or a new one if static. * * @return static */ protected static function this(): static { return end(static::$macroContextStack) ?: new static(0); } /** * Creates a CarbonInterval from string. * * Format: * * Suffix | Unit | Example | DateInterval expression * -------|---------|---------|------------------------ * y | years | 1y | P1Y * mo | months | 3mo | P3M * w | weeks | 2w | P2W * d | days | 28d | P28D * h | hours | 4h | PT4H * m | minutes | 12m | PT12M * s | seconds | 59s | PT59S * * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. * * Special cases: * - An empty string will return a zero interval * - Fractions are allowed for weeks, days, hours and minutes and will be converted * and rounded to the next smaller value (caution: 0.5w = 4d) * * @param string $intervalDefinition * * @throws InvalidIntervalException * * @return static */ public static function fromString(string $intervalDefinition): static { if (empty($intervalDefinition)) { return self::withOriginal(new static(0), $intervalDefinition); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $milliseconds = 0; $microseconds = 0; $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ([$part, $value, $unit] = array_shift($parts)) { $intValue = (int) $value; $fraction = (float) $value - $intValue; // Fix calculation precision switch (round($fraction, 6)) { case 1: $fraction = 0; $intValue++; break; case 0: $fraction = 0; break; } switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { case 'millennia': case 'millennium': $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; break; case 'century': case 'centuries': $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; break; case 'decade': case 'decades': $years += $intValue * CarbonInterface::YEARS_PER_DECADE; break; case 'year': case 'years': case 'y': case 'yr': case 'yrs': $years += $intValue; break; case 'quarter': case 'quarters': $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; break; case 'month': case 'months': case 'mo': case 'mos': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; } break; case 'second': case 'seconds': case 's': $seconds += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; } break; case 'millisecond': case 'milliseconds': case 'milli': case 'ms': $milliseconds += $intValue; if ($fraction) { $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); } break; case 'microsecond': case 'microseconds': case 'micro': case 'µs': $microseconds += $intValue; break; default: throw new InvalidIntervalException( "Invalid part $part in definition $intervalDefinition", ); } } return self::withOriginal( new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds), $intervalDefinition, ); } /** * Creates a CarbonInterval from string using a different locale. * * @param string $interval interval string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be used instead. * * @return static */ public static function parseFromLocale(string $interval, ?string $locale = null): static { return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE)); } /** * Create an interval from the difference between 2 dates. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $start * @param \Carbon\Carbon|\DateTimeInterface|mixed $end * * @return static */ public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; } /** * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function abs(bool $absolute = false): static { if ($absolute && $this->invert) { $this->invert(); } return $this; } /** * @alias abs * * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function absolute(bool $absolute = true): static { return $this->abs($absolute); } /** * Cast the current instance into the given class. * * @template T of DateInterval * * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { return self::castIntervalToClass($this, $className); } /** * Create a CarbonInterval instance from a DateInterval one. Can not instance * DateInterval objects created from DateTime::diff() as you can't externally * set the $days field. * * @param DateInterval $interval * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static */ public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static { if ($skipCopy && $interval instanceof static) { return $interval; } return self::castIntervalToClass($interval, static::class, $skip); } /** * Make a CarbonInterval instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static|null */ public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); } protected static function makeFromString(string $interval): ?self { $interval = preg_replace('/\s+/', ' ', trim($interval)); if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { return static::fromString($interval); } $intervalInstance = static::createFromDateString($interval); return $intervalInstance->isEmpty() ? null : $intervalInstance; } protected function resolveInterval($interval): ?self { if (!($interval instanceof self)) { return self::make($interval); } return $interval; } /** * Sets up a DateInterval from the relative parts of the string. * * @param string $datetime * * @return static * * @link https://php.net/manual/en/dateinterval.createfromdatestring.php */ public static function createFromDateString(string $datetime): static { $string = strtr($datetime, [ ',' => ' ', ' and ' => ' ', ]); $previousException = null; try { $interval = parent::createFromDateString($string); } catch (Throwable $exception) { $interval = null; $previousException = $exception; } $interval ?: throw new InvalidFormatException( 'Could not create interval from: '.var_export($datetime, true), previous: $previousException, ); if (!($interval instanceof static)) { $interval = static::instance($interval); } return self::withOriginal($interval, $datetime); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the CarbonInterval object. */ public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; } /** * Get a part of the CarbonInterval object. */ public function __get(string $name): int|float|string|null { return $this->get($name); } /** * Set a part of the CarbonInterval object. * * @param Unit|string|array $name * @param int $value * * @throws UnknownSetterException * * @return $this */ public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; } /** * Set a part of the CarbonInterval object. * * @param string $name * @param int $value * * @throws UnknownSetterException */ public function __set(string $name, $value) { $this->set($name, $value); } /** * Allow setting of weeks and days to be cumulative. * * @param int $weeks Number of weeks to set * @param int $days Number of days to set * * @return static */ public function weeksAndDays(int $weeks, int $days): static { $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; return $this; } /** * Returns true if the interval is empty for each unit. * * @return bool */ public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonInterval::macro('twice', function () { * return $this->times(2); * }); * echo CarbonInterval::hours(2)->twice(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonInterval::mixin(new class { * public function daysToHours() { * return function () { * $this->hours += $this->days; * $this->days = 0; * * return $this; * }; * } * public function hoursToDays() { * return function () { * $this->days += $this->hours; * $this->hours = 0; * * return $this; * }; * } * }); * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; * echo CarbonInterval::days(5)->daysToHours() . "\n"; * ``` * * @param object|string $mixin * * @throws ReflectionException * * @return void */ public static function mixin($mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Call given macro. * * @param string $name * @param array $parameters * * @return mixed */ protected function callMacro(string $name, array $parameters) { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadFluentSetterException|Throwable * * @return static|int|float|string */ public function __call(string $method, array $parameters) { if (static::hasMacro($method)) { return static::bindMacroContext($this, function () use (&$method, &$parameters) { return $this->callMacro($method, $parameters); }); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); return $this->{$match['method']}($value, $match['unit']); } $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); try { $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); } } return $this; } protected function getForHumansInitialVariables($syntax, $short): array { if (\is_array($syntax)) { return $syntax; } if (\is_int($short)) { return [ 'parts' => $short, 'short' => false, ]; } if (\is_bool($syntax)) { return [ 'short' => $syntax, 'syntax' => CarbonInterface::DIFF_ABSOLUTE, ]; } return []; } /** * @param mixed $syntax * @param mixed $short * @param mixed $parts * @param mixed $options * * @return array */ protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array { $optionalSpace = ' '; $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; /** @var bool|string $join */ $join = $default === '' ? '' : ' '; /** @var bool|array|string $altNumbers */ $altNumbers = false; $aUnit = false; $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); $skip = array_map( static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit, (array) $skip, ); $skip = array_map( 'strtolower', array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''), ); $syntax ??= CarbonInterface::DIFF_ABSOLUTE; if ($parts === self::NO_LIMIT) { $parts = INF; } $options ??= static::getHumanDiffOptions(); if ($join === false) { $join = ' '; } elseif ($join === true) { $join = [ $default, $this->getTranslationMessage('list.1') ?? $default, ]; } if ($altNumbers && $altNumbers !== true) { $language = new Language($this->locale); $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { [$default, $last] = $join; if ($default !== ' ') { $optionalSpace = ''; } $join = function ($list) use ($default, $last) { if (\count($list) < 2) { return implode('', $list); } $end = array_pop($list); return implode($default, $list).$last.$end; }; } if (\is_string($join)) { if ($join !== ' ') { $optionalSpace = ''; } $glue = $join; $join = static fn ($list) => implode($glue, $list); } $interpolations = [ ':optional-space' => $optionalSpace, ]; $translator ??= isset($locale) ? Translator::get($locale) : null; return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator]; } protected static function getRoundingMethodFromOptions(int $options): ?string { if ($options & CarbonInterface::ROUND) { return 'round'; } if ($options & CarbonInterface::CEIL) { return 'ceil'; } if ($options & CarbonInterface::FLOOR) { return 'floor'; } return null; } /** * Returns interval values as an array where key are the unit names and values the counts. * * @return int[] */ public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; } /** * Returns interval non-zero values as an array where key are the unit names and values the counts. * * @return int[] */ public function getNonZeroValues(): array { return array_filter($this->toArray(), 'intval'); } /** * Returns interval values as an array where key are the unit names and values the counts * from the biggest non-zero one the the smallest non-zero one. * * @return int[] */ public function getValuesSequence(): array { $nonZeroValues = $this->getNonZeroValues(); if ($nonZeroValues === []) { return []; } $keys = array_keys($nonZeroValues); $firstKey = $keys[0]; $lastKey = $keys[\count($keys) - 1]; $values = []; $record = false; foreach ($this->toArray() as $unit => $count) { if ($unit === $firstKey) { $record = true; } if ($record) { $values[$unit] = $count; } if ($unit === $lastKey) { $record = false; } } return $values; } /** * Get the current interval in a human readable format in the current locale. * * @example * ``` * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; * ``` * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: -1: no limits) * @param int $options human diff options * * @throws Exception * * @return string */ public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string { /* @var TranslatorInterface|null $translator */ [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this ->getForHumansParameters($syntax, $short, $parts, $options); $interval = []; $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; $count = 1; $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); $declensionMode = null; $translator ??= $this->getLocalTranslator(); $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); if ($this->needsDeclension($declensionMode, $index, $parts)) { // Some languages have special pluralization for past and future tense. $key = $unit.'_'.$transId; $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); if ($result !== $key) { return $result; } } } $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); if ($result !== $unit) { return $result; } return null; }; $intervalValues = $this; $method = static::getRoundingMethodFromOptions($options); if ($method) { $previousCount = INF; while ( \count($intervalValues->getNonZeroValues()) > $parts && ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 ) { $index = min($count, $previousCount - 1) - 2; if ($index < 0) { break; } $intervalValues = $this->copy()->roundUnit( $keys[$index], 1, $method, ); $previousCount = $count; } } $diffIntervalArray = [ ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], ]; if (!empty($skip)) { foreach ($diffIntervalArray as $index => &$unitData) { $nextIndex = $index + 1; if ($unitData['value'] && isset($diffIntervalArray[$nextIndex]) && \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) ) { $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); $unitData['value'] = 0; } } } $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; } } if (!$absolute) { return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); }; $fallbackUnit = ['second', 's']; foreach ($diffIntervalArray as $diffIntervalData) { if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } // break the loop after we get the required number of parts in array if (\count($interval) >= $parts) { break; } // break the loop after we have reached the minimum unit if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } $actualParts = \count($interval); foreach ($interval as $index => &$item) { $item = $transChoice($item[0], $item[1], $index, $actualParts); } if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; $unit = $fallbackUnit[$short ? 1 : 0]; $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); } // join the interval parts by a space $time = $join($interval); unset($diffIntervalArray, $interval); if ($absolute) { return $time; } $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); if ($parts === 1) { if ($relativeToNow && $unit === 'day') { $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null; if ($specialTranslations && $options & $specialTranslations['option']) { $key = $specialTranslations[$isFuture ? 'future' : 'past']; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } } $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; } $time = [':time' => $time]; return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); } public function format(string $format): string { $output = parent::format($format); if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) { return $output; } $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate); return str_replace('(unknown)', $this->rawInterval->format('%a'), $output); } /** * Format the instance as a string using the forHumans() function. * * @throws Exception * * @return string */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if (!$format) { return $this->forHumans(); } if ($format instanceof Closure) { return $format($this); } return $this->format($format); } /** * Return native DateInterval PHP object matching the current instance. * * @example * ``` * var_dump(CarbonInterval::hours(2)->toDateInterval()); * ``` * * @return DateInterval */ public function toDateInterval(): DateInterval { return self::castIntervalToClass($this, DateInterval::class); } /** * Convert the interval to a CarbonPeriod. * * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. * * @return CarbonPeriod */ public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); } /** * Decompose the current interval into * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); } /** * Invert the interval. * * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this */ public function invert($inverted = null): static { $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; return $this; } protected function solveNegativeInterval(): static { if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { $this->years *= self::NEGATIVE; $this->months *= self::NEGATIVE; $this->dayz *= self::NEGATIVE; $this->hours *= self::NEGATIVE; $this->minutes *= self::NEGATIVE; $this->seconds *= self::NEGATIVE; $this->microseconds *= self::NEGATIVE; $this->invert(); } return $this; } /** * Add the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function sub($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } return $this->add($unit, -(float) $value); } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function subtract($unit, $value = 1): static { return $this->sub($unit, $value); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Multiply current instance given number of times. times() is naive, it multiplies each unit * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded * separately for each unit. * * Use times() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see multiply() * * @param float|int $factor * * @return $this */ public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; } /** * Divide current instance by a given divider. shares() is naive, it divides each unit separately * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours * and 7 minutes. * * Use shares() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see divide() * * @param float|int $divider * * @return $this */ public function shares($divider): static { return $this->times(1 / $divider); } protected function copyProperties(self $interval, $ignoreSign = false): static { $this->years = $interval->years; $this->months = $interval->months; $this->dayz = $interval->dayz; $this->hours = $interval->hours; $this->minutes = $interval->minutes; $this->seconds = $interval->seconds; $this->microseconds = $interval->microseconds; if (!$ignoreSign) { $this->invert = $interval->invert; } return $this; } /** * Multiply and cascade current instance by a given factor. * * @param float|int $factor * * @return $this */ public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); } /** * Divide and cascade current instance by a given divider. * * @param float|int $divider * * @return $this */ public function divide($divider): static { return $this->multiply(1 / $divider); } /** * Get the interval_spec string of a date interval. * * @param DateInterval $interval * * @return string */ public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), static::PERIOD_MONTHS => abs($interval->m), static::PERIOD_DAYS => abs($interval->d), ]); $skip = array_map([Unit::class, 'toNameIfUnit'], $skip); if ( $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) ) { $date = [ static::PERIOD_DAYS => abs($interval->days), ]; } $seconds = abs($interval->s); if ($microseconds && $interval->f > 0) { $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); } $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; foreach ($date as $key => $value) { $specString .= $value.$key; } if (\count($time) > 0) { $specString .= static::PERIOD_TIME_PREFIX; foreach ($time as $key => $value) { $specString .= $value.$key; } } return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; } /** * Get the interval_spec string. * * @return string */ public function spec(bool $microseconds = false): string { return static::getDateIntervalSpec($this, $microseconds); } /** * Comparing 2 date intervals. * * @param DateInterval $first * @param DateInterval $second * * @return int 0, 1 or -1 */ public static function compareDateIntervals(DateInterval $first, DateInterval $second): int { $current = Carbon::now(); $passed = $current->avoidMutation()->add($second); $current->add($first); return $current <=> $passed; } /** * Comparing with passed interval. * * @param DateInterval $interval * * @return int 0, 1 or -1 */ public function compare(DateInterval $interval): int { return static::compareDateIntervals($this, $interval); } /** * Convert overflowed values into bigger units. * * @return $this */ public function cascade(): static { return $this->doCascade(false); } public function hasNegativeValues(): bool { foreach ($this->toArray() as $value) { if ($value < 0) { return true; } } return false; } public function hasPositiveValues(): bool { foreach ($this->toArray() as $value) { if ($value > 0) { return true; } } return false; } /** * Get amount of given unit equivalent to the interval. * * @param string $unit * * @throws UnknownUnitException|UnitNotConfiguredException * * @return float */ public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see equalTo() * * @return bool */ public function eq($interval): bool { return $this->equalTo($interval); } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see notEqualTo() * * @return bool */ public function ne($interval): bool { return $this->notEqualTo($interval); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function notEqualTo($interval): bool { return !$this->eq($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThan() * * @return bool */ public function gt($interval): bool { return $this->greaterThan($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThanOrEqualTo() * * @return bool */ public function gte($interval): bool { return $this->greaterThanOrEqualTo($interval); } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThanOrEqualTo($interval): bool { return $this->greaterThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThan() * * @return bool */ public function lt($interval): bool { return $this->lessThan($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThanOrEqualTo() * * @return bool */ public function lte($interval): bool { return $this->lessThanOrEqualTo($interval); } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThanOrEqualTo($interval): bool { return $this->lessThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function between($interval1, $interval2, bool $equal = true): bool { return $equal ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) : $this->greaterThan($interval1) && $this->lessThan($interval2); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenIncluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenExcluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, false); } /** * Determines if the instance is between two others * * @example * ``` * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function isBetween($interval1, $interval2, bool $equal = true): bool { return $this->between($interval1, $interval2, $equal); } /** * Round the current instance at the given unit with given precision if specified and the given function. * * @throws Exception */ public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); } /** * Truncate the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function floorUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function ceilUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified. * * @param float|int|string|DateInterval|null $precision * @param string $function * * @throws Exception * * @return $this */ public function round($precision = 1, string $function = 'round'): static { return $this->roundWith($precision, $function); } /** * Round the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function floor(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function ceil(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'ceil'); } public function __unserialize(array $data): void { $properties = array_combine( array_map( static fn (mixed $key) => \is_string($key) ? str_replace('tzName', 'timezoneSetting', $key) : $key, array_keys($data), ), $data, ); if (method_exists(parent::class, '__unserialize')) { // PHP >= 8.2 parent::__unserialize($properties); return; } // PHP <= 8.1 // @codeCoverageIgnoreStart $properties = array_combine( array_map( static fn (string $property) => preg_replace('/^\0.+\0/', '', $property), array_keys($data), ), $data, ); $localStrictMode = $this->localStrictModeEnabled; $this->localStrictModeEnabled = false; $days = $properties['days'] ?? false; $this->days = $days === false ? false : (int) $days; $this->y = (int) ($properties['y'] ?? 0); $this->m = (int) ($properties['m'] ?? 0); $this->d = (int) ($properties['d'] ?? 0); $this->h = (int) ($properties['h'] ?? 0); $this->i = (int) ($properties['i'] ?? 0); $this->s = (int) ($properties['s'] ?? 0); $this->f = (float) ($properties['f'] ?? 0.0); // @phpstan-ignore-next-line $this->weekday = (int) ($properties['weekday'] ?? 0); // @phpstan-ignore-next-line $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0); // @phpstan-ignore-next-line $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0); $this->invert = (int) ($properties['invert'] ?? 0); // @phpstan-ignore-next-line $this->special_type = (int) ($properties['special_type'] ?? 0); // @phpstan-ignore-next-line $this->special_amount = (int) ($properties['special_amount'] ?? 0); // @phpstan-ignore-next-line $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0); // @phpstan-ignore-next-line $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0); parent::__construct(self::getDateIntervalSpec($this)); foreach ($properties as $property => $value) { if ($property === 'localStrictModeEnabled') { continue; } $this->$property = $value; } $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode; // @codeCoverageIgnoreEnd } /** * @template T * * @param T $interval * @param mixed $original * * @return T */ private static function withOriginal(mixed $interval, mixed $original): mixed { if ($interval instanceof self) { $interval->originalInput = $original; } return $interval; } private static function standardizeUnit(string $unit): string { $unit = rtrim($unit, 'sz').'s'; return $unit === 'days' ? 'dayz' : $unit; } private static function getFlipCascadeFactors(): array { if (!self::$flipCascadeFactors) { self::$flipCascadeFactors = []; foreach (self::getCascadeFactors() as $to => [$factor, $from]) { self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; } } return self::$flipCascadeFactors; } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object { $mainClass = DateInterval::class; if (!is_a($className, $mainClass, true)) { throw new InvalidCastException("$className is not a sub-class of $mainClass."); } $microseconds = $interval->f; $instance = self::buildInstance($interval, $className, $skip); if ($instance instanceof self) { $instance->originalInput = $interval; } if ($microseconds) { $instance->f = $microseconds; } if ($interval instanceof self && is_a($className, self::class, true)) { self::copyStep($interval, $instance); } self::copyNegativeUnits($interval, $instance); return self::withOriginal($instance, $interval); } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function buildInstance( DateInterval $interval, string $className, array $skip = [], ): object { $serialization = self::buildSerializationString($interval, $className, $skip); return match ($serialization) { null => new $className(static::getDateIntervalSpec($interval, false, $skip)), default => unserialize($serialization), }; } /** * As demonstrated by rlanvin (https://github.com/rlanvin) in * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438 * * Modifying the output of serialize() to change the class name and unserializing * the tweaked string allows creating new interval instances where the ->days * property can be set. It's not possible neither with `new` nto with `__set_state`. * * It has a non-negligible performance cost, so we'll use this method only if * $interval->days !== false. */ private static function buildSerializationString( DateInterval $interval, string $className, array $skip = [], ): ?string { if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) { return null; } // De-enhance CarbonInterval objects to be serializable back to DateInterval if ($interval instanceof self && !is_a($className, self::class, true)) { $interval = clone $interval; unset($interval->timezoneSetting); unset($interval->originalInput); unset($interval->startDate); unset($interval->endDate); unset($interval->rawInterval); unset($interval->absolute); unset($interval->initialValues); unset($interval->clock); unset($interval->step); unset($interval->localMonthsOverflow); unset($interval->localYearsOverflow); unset($interval->localStrictModeEnabled); unset($interval->localHumanDiffOptions); unset($interval->localToStringFormat); unset($interval->localSerializer); unset($interval->localMacros); unset($interval->localGenericMacros); unset($interval->localFormatFunction); unset($interval->localTranslator); } $serialization = serialize($interval); $inputClass = $interval::class; $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":'; if (!str_starts_with($serialization, $expectedStart)) { return null; // @codeCoverageIgnore } return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart)); } private static function copyStep(self $from, self $to): void { $to->setStep($from->getStep()); } private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void { $to->invert = $from->invert; foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { if ($from->$unit < 0) { self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE); } } } private function invertCascade(array $values): static { return $this->set(array_map(function ($value) { return -$value; }, $values))->doCascade(true)->invert(); } private function doCascade(bool $deep): static { $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { if ($$key === 'dayz') { $$key = 'daysExcludeWeeks'; } } $value = $newData[$source]; $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; $decimalPart = fmod($newData[$source], 1); if ($decimalPart !== 0.0) { $unit = $source; foreach ($previous as [$subUnit, $subFactor]) { $newData[$unit] -= $decimalPart; $newData[$subUnit] += $decimalPart * $subFactor; $decimalPart = fmod($newData[$subUnit], 1); if ($decimalPart === 0.0) { break; } $unit = $subUnit; } } array_unshift($previous, [$source, $factor]); } $positive = null; if (!$deep) { foreach ($newData as $value) { if ($value) { if ($positive === null) { $positive = ($value > 0); continue; } if (($value > 0) !== $positive) { return $this->invertCascade($originalData) ->solveNegativeInterval(); } } } } return $this->set($newData) ->solveNegativeInterval(); } private function needsDeclension(string $mode, int $index, int $parts): bool { return match ($mode) { 'last' => $index === $parts - 1, default => true, }; } private function checkIntegerValue(string $name, mixed $value): void { if (\is_int($value)) { return; } $this->assertSafeForInteger($name, $value); if (\is_float($value) && (((float) (int) $value) === $value)) { return; } if (!self::$floatSettersEnabled) { $type = \gettype($value); @trigger_error( "Since 2.70.0, it's deprecated to pass $type value for $name.\n". "It's truncated when stored as an integer interval unit.\n". "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", \E_USER_DEPRECATED, ); } } /** * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. */ private function assertSafeForInteger(string $name, mixed $value): void { if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); } } private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void { if (self::$floatSettersEnabled) { $floatValue = (float) $value; $base = (float) $integerValue; if ($floatValue === $base) { return; } $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; $upper = true; foreach ($units as $property => $name) { if ($name === $unit) { $upper = false; continue; } if (!$upper && $this->$property !== 0) { throw new RuntimeException( "You cannot set $unit to a float value as $name would be overridden, ". 'set it first to 0 explicitly if you really want to erase its value' ); } } $this->add($unit, $floatValue - $base); } } private function getInnerValues(): array { return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days]; } private function checkStartAndEnd(): void { if ( $this->initialValues !== null && ($this->startDate !== null || $this->endDate !== null) && $this->initialValues !== $this->getInnerValues() ) { $this->absolute = false; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; } } /** @return $this */ private function setSetting(string $setting, mixed $value): self { switch ($setting) { case 'timezoneSetting': return $value === null ? $this : $this->setTimezone($value); case 'step': $this->setStep($value); return $this; case 'localMonthsOverflow': return $value === null ? $this : $this->settings(['monthOverflow' => $value]); case 'localYearsOverflow': return $value === null ? $this : $this->settings(['yearOverflow' => $value]); case 'localStrictModeEnabled': case 'localHumanDiffOptions': case 'localToStringFormat': case 'localSerializer': case 'localMacros': case 'localGenericMacros': case 'localFormatFunction': case 'localTranslator': $this->$setting = $value; return $this; default: // Drop unknown settings return $this; } } private static function incrementUnit(DateInterval $instance, string $unit, int $value): void { if ($value === 0) { return; } // @codeCoverageIgnoreStart if (PHP_VERSION_ID !== 8_03_20) { $instance->$unit += $value; return; } // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value); // @codeCoverageIgnoreEnd } /** @codeCoverageIgnore */ private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void { switch ($unit) { case 'y': $instance->y = $value; break; case 'm': $instance->m = $value; break; case 'd': $instance->d = $value; break; case 'h': $instance->h = $value; break; case 'i': $instance->i = $value; break; case 's': $instance->s = $value; break; default: $instance->$unit = $value; } } }
PHP
{ "end_line": 2742, "name": "equalTo", "signature": "public function equalTo($interval): bool", "start_line": 2719 }
{ "class_name": "CarbonInterval", "class_signature": "class CarbonInterval implements CarbonConverterInterface, UnitValue", "namespace": "Carbon" }
roundUnit
Carbon/src/Carbon/CarbonInterval.php
public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\BadFluentConstructorException; use Carbon\Exceptions\BadFluentSetterException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\ParseErrorException; use Carbon\Exceptions\UnitNotConfiguredException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\Traits\IntervalRounding; use Carbon\Traits\IntervalStep; use Carbon\Traits\LocalFactory; use Carbon\Traits\MagicParameter; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use DateInterval; use DateTime; use DateTimeInterface; use DateTimeZone; use Exception; use InvalidArgumentException; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A simple API extension for DateInterval. * The implementation provides helpers to handle weeks but only days are saved. * Weeks are calculated based on the total days of the current instance. * * @property int $years Year component of the current interval. (For P2Y6M, the value will be 2) * @property int $months Month component of the current interval. (For P1Y6M10D, the value will be 6) * @property int $weeks Week component of the current interval calculated from the days. (For P1Y6M17D, the value will be 2) * @property int $dayz Day component of the current interval (weeks * 7 + days). (For P6M17DT20H, the value will be 17) * @property int $hours Hour component of the current interval. (For P7DT20H5M, the value will be 20) * @property int $minutes Minute component of the current interval. (For PT20H5M30S, the value will be 5) * @property int $seconds Second component of the current interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->seconds = 34) * @property int $milliseconds Milliseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->milliseconds = 567) * @property int $microseconds Microseconds component of the current interval. (CarbonInterval::seconds(34)->microseconds(567_890)->microseconds = 567_890) * @property int $microExcludeMilli Remaining microseconds without the milliseconds. * @property int $dayzExcludeWeeks Total days remaining in the final week of the current instance (days % 7). * @property int $daysExcludeWeeks alias of dayzExcludeWeeks * @property-read float $totalYears Number of years equivalent to the interval. (For P1Y6M, the value will be 1.5) * @property-read float $totalMonths Number of months equivalent to the interval. (For P1Y6M10D, the value will be ~12.357) * @property-read float $totalWeeks Number of weeks equivalent to the interval. (For P6M17DT20H, the value will be ~26.548) * @property-read float $totalDays Number of days equivalent to the interval. (For P17DT20H, the value will be ~17.833) * @property-read float $totalDayz Alias for totalDays. * @property-read float $totalHours Number of hours equivalent to the interval. (For P1DT20H5M, the value will be ~44.083) * @property-read float $totalMinutes Number of minutes equivalent to the interval. (For PT20H5M30S, the value will be 1205.5) * @property-read float $totalSeconds Number of seconds equivalent to the interval. (CarbonInterval::minutes(2)->seconds(34)->microseconds(567_890)->totalSeconds = 154.567_890) * @property-read float $totalMilliseconds Number of milliseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMilliseconds = 34567.890) * @property-read float $totalMicroseconds Number of microseconds equivalent to the interval. (CarbonInterval::seconds(34)->microseconds(567_890)->totalMicroseconds = 34567890) * @property-read string $locale locale of the current instance * * @method static CarbonInterval years($years = 1) Create instance specifying a number of years or modify the number of years if called on an instance. * @method static CarbonInterval year($years = 1) Alias for years() * @method static CarbonInterval months($months = 1) Create instance specifying a number of months or modify the number of months if called on an instance. * @method static CarbonInterval month($months = 1) Alias for months() * @method static CarbonInterval weeks($weeks = 1) Create instance specifying a number of weeks or modify the number of weeks if called on an instance. * @method static CarbonInterval week($weeks = 1) Alias for weeks() * @method static CarbonInterval days($days = 1) Create instance specifying a number of days or modify the number of days if called on an instance. * @method static CarbonInterval dayz($days = 1) Alias for days() * @method static CarbonInterval daysExcludeWeeks($days = 1) Create instance specifying a number of days or modify the number of days (keeping the current number of weeks) if called on an instance. * @method static CarbonInterval dayzExcludeWeeks($days = 1) Alias for daysExcludeWeeks() * @method static CarbonInterval day($days = 1) Alias for days() * @method static CarbonInterval hours($hours = 1) Create instance specifying a number of hours or modify the number of hours if called on an instance. * @method static CarbonInterval hour($hours = 1) Alias for hours() * @method static CarbonInterval minutes($minutes = 1) Create instance specifying a number of minutes or modify the number of minutes if called on an instance. * @method static CarbonInterval minute($minutes = 1) Alias for minutes() * @method static CarbonInterval seconds($seconds = 1) Create instance specifying a number of seconds or modify the number of seconds if called on an instance. * @method static CarbonInterval second($seconds = 1) Alias for seconds() * @method static CarbonInterval milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds or modify the number of milliseconds if called on an instance. * @method static CarbonInterval millisecond($milliseconds = 1) Alias for milliseconds() * @method static CarbonInterval microseconds($microseconds = 1) Create instance specifying a number of microseconds or modify the number of microseconds if called on an instance. * @method static CarbonInterval microsecond($microseconds = 1) Alias for microseconds() * @method $this addYears(int $years) Add given number of years to the current interval * @method $this subYears(int $years) Subtract given number of years to the current interval * @method $this addMonths(int $months) Add given number of months to the current interval * @method $this subMonths(int $months) Subtract given number of months to the current interval * @method $this addWeeks(int|float $weeks) Add given number of weeks to the current interval * @method $this subWeeks(int|float $weeks) Subtract given number of weeks to the current interval * @method $this addDays(int|float $days) Add given number of days to the current interval * @method $this subDays(int|float $days) Subtract given number of days to the current interval * @method $this addHours(int|float $hours) Add given number of hours to the current interval * @method $this subHours(int|float $hours) Subtract given number of hours to the current interval * @method $this addMinutes(int|float $minutes) Add given number of minutes to the current interval * @method $this subMinutes(int|float $minutes) Subtract given number of minutes to the current interval * @method $this addSeconds(int|float $seconds) Add given number of seconds to the current interval * @method $this subSeconds(int|float $seconds) Subtract given number of seconds to the current interval * @method $this addMilliseconds(int|float $milliseconds) Add given number of milliseconds to the current interval * @method $this subMilliseconds(int|float $milliseconds) Subtract given number of milliseconds to the current interval * @method $this addMicroseconds(int|float $microseconds) Add given number of microseconds to the current interval * @method $this subMicroseconds(int|float $microseconds) Subtract given number of microseconds to the current interval * @method $this roundYear(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(int|float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(int|float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(int|float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(int|float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(int|float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(int|float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(int|float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(int|float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(int|float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(int|float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(int|float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(int|float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(int|float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(int|float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(int|float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(int|float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(int|float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(int|float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(int|float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(int|float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(int|float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(int|float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(int|float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(int|float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(int|float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(int|float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(int|float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(int|float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(int|float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(int|float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(int|float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(int|float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(int|float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(int|float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(int|float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(int|float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(int|float $precision = 1) Ceil the current instance microsecond with given precision. */ class CarbonInterval extends DateInterval implements CarbonConverterInterface, UnitValue { use LocalFactory; use IntervalRounding; use IntervalStep; use MagicParameter; use Mixin { Mixin::mixin as baseMixin; } use Options; use ToStringFormat; /** * Unlimited parts for forHumans() method. * * INF constant can be used instead. */ public const NO_LIMIT = -1; public const POSITIVE = 1; public const NEGATIVE = -1; /** * Interval spec period designators */ public const PERIOD_PREFIX = 'P'; public const PERIOD_YEARS = 'Y'; public const PERIOD_MONTHS = 'M'; public const PERIOD_DAYS = 'D'; public const PERIOD_TIME_PREFIX = 'T'; public const PERIOD_HOURS = 'H'; public const PERIOD_MINUTES = 'M'; public const PERIOD_SECONDS = 'S'; public const SPECIAL_TRANSLATIONS = [ 1 => [ 'option' => CarbonInterface::ONE_DAY_WORDS, 'future' => 'diff_tomorrow', 'past' => 'diff_yesterday', ], 2 => [ 'option' => CarbonInterface::TWO_DAY_WORDS, 'future' => 'diff_after_tomorrow', 'past' => 'diff_before_yesterday', ], ]; protected static ?array $cascadeFactors = null; protected static array $formats = [ 'y' => 'y', 'Y' => 'y', 'o' => 'y', 'm' => 'm', 'n' => 'm', 'W' => 'weeks', 'd' => 'd', 'j' => 'd', 'z' => 'd', 'h' => 'h', 'g' => 'h', 'H' => 'h', 'G' => 'h', 'i' => 'i', 's' => 's', 'u' => 'micro', 'v' => 'milli', ]; private static ?array $flipCascadeFactors = null; private static bool $floatSettersEnabled = false; /** * The registered macros. */ protected static array $macros = []; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; /** * The input used to create the interval. */ protected mixed $originalInput = null; /** * Start date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $startDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?CarbonInterface $endDate = null; /** * End date if interval was created from a difference between 2 dates. */ protected ?DateInterval $rawInterval = null; /** * Flag if the interval was made from a diff with absolute flag on. */ protected bool $absolute = false; protected ?array $initialValues = null; /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->setTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $this->timezoneSetting = $timezone; $this->checkStartAndEnd(); if ($this->startDate) { $this->startDate = $this->startDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } if ($this->endDate) { $this->endDate = $this->endDate ->avoidMutation() ->shiftTimezone($timezone); $this->rawInterval = null; } return $this; } /** * Mapping of units and factors for cascading. * * Should only be modified by changing the factors or referenced constants. */ public static function getCascadeFactors(): array { return static::$cascadeFactors ?: static::getDefaultCascadeFactors(); } protected static function getDefaultCascadeFactors(): array { return [ 'milliseconds' => [CarbonInterface::MICROSECONDS_PER_MILLISECOND, 'microseconds'], 'seconds' => [CarbonInterface::MILLISECONDS_PER_SECOND, 'milliseconds'], 'minutes' => [CarbonInterface::SECONDS_PER_MINUTE, 'seconds'], 'hours' => [CarbonInterface::MINUTES_PER_HOUR, 'minutes'], 'dayz' => [CarbonInterface::HOURS_PER_DAY, 'hours'], 'weeks' => [CarbonInterface::DAYS_PER_WEEK, 'dayz'], 'months' => [CarbonInterface::WEEKS_PER_MONTH, 'weeks'], 'years' => [CarbonInterface::MONTHS_PER_YEAR, 'months'], ]; } /** * Set default cascading factors for ->cascade() method. * * @param array $cascadeFactors */ public static function setCascadeFactors(array $cascadeFactors) { self::$flipCascadeFactors = null; static::$cascadeFactors = $cascadeFactors; } /** * This option allow you to opt-in for the Carbon 3 behavior where float * values will no longer be cast to integer (so truncated). * * ⚠️ This settings will be applied globally, which mean your whole application * code including the third-party dependencies that also may use Carbon will * adopt the new behavior. */ public static function enableFloatSetters(bool $floatSettersEnabled = true): void { self::$floatSettersEnabled = $floatSettersEnabled; } /////////////////////////////////////////////////////////////////// //////////////////////////// CONSTRUCTORS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Create a new CarbonInterval instance. * * @param Closure|DateInterval|string|int|null $years * @param int|float|null $months * @param int|float|null $weeks * @param int|float|null $days * @param int|float|null $hours * @param int|float|null $minutes * @param int|float|null $seconds * @param int|float|null $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. */ public function __construct($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { $this->originalInput = \func_num_args() === 1 ? $years : \func_get_args(); if ($years instanceof Closure) { $this->step = $years; $years = null; } if ($years instanceof DateInterval) { parent::__construct(static::getDateIntervalSpec($years)); $this->f = $years->f; self::copyNegativeUnits($years, $this); return; } $spec = $years; $isStringSpec = (\is_string($spec) && !preg_match('/^[\d.]/', $spec)); if (!$isStringSpec || (float) $years) { $spec = static::PERIOD_PREFIX; $spec .= $years > 0 ? $years.static::PERIOD_YEARS : ''; $spec .= $months > 0 ? $months.static::PERIOD_MONTHS : ''; $specDays = 0; $specDays += $weeks > 0 ? $weeks * static::getDaysPerWeek() : 0; $specDays += $days > 0 ? $days : 0; $spec .= $specDays > 0 ? $specDays.static::PERIOD_DAYS : ''; if ($hours > 0 || $minutes > 0 || $seconds > 0) { $spec .= static::PERIOD_TIME_PREFIX; $spec .= $hours > 0 ? $hours.static::PERIOD_HOURS : ''; $spec .= $minutes > 0 ? $minutes.static::PERIOD_MINUTES : ''; $spec .= $seconds > 0 ? $seconds.static::PERIOD_SECONDS : ''; } if ($spec === static::PERIOD_PREFIX) { // Allow the zero interval. $spec .= '0'.static::PERIOD_YEARS; } } try { parent::__construct($spec); } catch (Throwable $exception) { try { parent::__construct('PT0S'); if ($isStringSpec) { if (!preg_match('/^P (?:(?<year>[+-]?\d*(?:\.\d+)?)Y)? (?:(?<month>[+-]?\d*(?:\.\d+)?)M)? (?:(?<week>[+-]?\d*(?:\.\d+)?)W)? (?:(?<day>[+-]?\d*(?:\.\d+)?)D)? (?:T (?:(?<hour>[+-]?\d*(?:\.\d+)?)H)? (?:(?<minute>[+-]?\d*(?:\.\d+)?)M)? (?:(?<second>[+-]?\d*(?:\.\d+)?)S)? )? $/x', $spec, $match)) { throw new InvalidArgumentException("Invalid duration: $spec"); } $years = (float) ($match['year'] ?? 0); $this->assertSafeForInteger('year', $years); $months = (float) ($match['month'] ?? 0); $this->assertSafeForInteger('month', $months); $weeks = (float) ($match['week'] ?? 0); $this->assertSafeForInteger('week', $weeks); $days = (float) ($match['day'] ?? 0); $this->assertSafeForInteger('day', $days); $hours = (float) ($match['hour'] ?? 0); $this->assertSafeForInteger('hour', $hours); $minutes = (float) ($match['minute'] ?? 0); $this->assertSafeForInteger('minute', $minutes); $seconds = (float) ($match['second'] ?? 0); $this->assertSafeForInteger('second', $seconds); $microseconds = (int) str_pad( substr(explode('.', $match['second'] ?? '0.0')[1] ?? '0', 0, 6), 6, '0', ); } $totalDays = (($weeks * static::getDaysPerWeek()) + $days); $this->assertSafeForInteger('days total (including weeks)', $totalDays); $this->y = (int) $years; $this->m = (int) $months; $this->d = (int) $totalDays; $this->h = (int) $hours; $this->i = (int) $minutes; $this->s = (int) $seconds; $secondFloatPart = (float) ($microseconds / CarbonInterface::MICROSECONDS_PER_SECOND); $this->f = $secondFloatPart; $intervalMicroseconds = (int) ($this->f * CarbonInterface::MICROSECONDS_PER_SECOND); $intervalSeconds = $seconds - $secondFloatPart; if ( ((float) $this->y) !== $years || ((float) $this->m) !== $months || ((float) $this->d) !== $totalDays || ((float) $this->h) !== $hours || ((float) $this->i) !== $minutes || ((float) $this->s) !== $intervalSeconds || $intervalMicroseconds !== ((int) $microseconds) ) { $this->add(static::fromString( ($years - $this->y).' years '. ($months - $this->m).' months '. ($totalDays - $this->d).' days '. ($hours - $this->h).' hours '. ($minutes - $this->i).' minutes '. number_format($intervalSeconds - $this->s, 6, '.', '').' seconds '. ($microseconds - $intervalMicroseconds).' microseconds ', )); } } catch (Throwable $secondException) { throw $secondException instanceof OutOfRangeException ? $secondException : $exception; } } if ($microseconds !== null) { $this->f = $microseconds / CarbonInterface::MICROSECONDS_PER_SECOND; } foreach (['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as $unit) { if ($$unit < 0) { $this->set($unit, $$unit); } } } /** * Returns the factor for a given source-to-target couple. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactor($source, $target) { $source = self::standardizeUnit($source); $target = self::standardizeUnit($target); $factors = self::getFlipCascadeFactors(); if (isset($factors[$source])) { [$to, $factor] = $factors[$source]; if ($to === $target) { return $factor; } return $factor * static::getFactor($to, $target); } return null; } /** * Returns the factor for a given source-to-target couple if set, * else try to find the appropriate constant as the factor, such as Carbon::DAYS_PER_WEEK. * * @param string $source * @param string $target * * @return int|float|null */ public static function getFactorWithDefault($source, $target) { $factor = self::getFactor($source, $target); if ($factor) { return $factor; } static $defaults = [ 'month' => ['year' => Carbon::MONTHS_PER_YEAR], 'week' => ['month' => Carbon::WEEKS_PER_MONTH], 'day' => ['week' => Carbon::DAYS_PER_WEEK], 'hour' => ['day' => Carbon::HOURS_PER_DAY], 'minute' => ['hour' => Carbon::MINUTES_PER_HOUR], 'second' => ['minute' => Carbon::SECONDS_PER_MINUTE], 'millisecond' => ['second' => Carbon::MILLISECONDS_PER_SECOND], 'microsecond' => ['millisecond' => Carbon::MICROSECONDS_PER_MILLISECOND], ]; return $defaults[$source][$target] ?? null; } /** * Returns current config for days per week. * * @return int|float */ public static function getDaysPerWeek() { return static::getFactor('dayz', 'weeks') ?: Carbon::DAYS_PER_WEEK; } /** * Returns current config for hours per day. * * @return int|float */ public static function getHoursPerDay() { return static::getFactor('hours', 'dayz') ?: Carbon::HOURS_PER_DAY; } /** * Returns current config for minutes per hour. * * @return int|float */ public static function getMinutesPerHour() { return static::getFactor('minutes', 'hours') ?: Carbon::MINUTES_PER_HOUR; } /** * Returns current config for seconds per minute. * * @return int|float */ public static function getSecondsPerMinute() { return static::getFactor('seconds', 'minutes') ?: Carbon::SECONDS_PER_MINUTE; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMillisecondsPerSecond() { return static::getFactor('milliseconds', 'seconds') ?: Carbon::MILLISECONDS_PER_SECOND; } /** * Returns current config for microseconds per second. * * @return int|float */ public static function getMicrosecondsPerMillisecond() { return static::getFactor('microseconds', 'milliseconds') ?: Carbon::MICROSECONDS_PER_MILLISECOND; } /** * Create a new CarbonInterval instance from specific values. * This is an alias for the constructor that allows better fluent * syntax as it allows you to do CarbonInterval::create(1)->fn() rather than * (new CarbonInterval(1))->fn(). * * @param int $years * @param int $months * @param int $weeks * @param int $days * @param int $hours * @param int $minutes * @param int $seconds * @param int $microseconds * * @throws Exception when the interval_spec (passed as $years) cannot be parsed as an interval. * * @return static */ public static function create($years = null, $months = null, $weeks = null, $days = null, $hours = null, $minutes = null, $seconds = null, $microseconds = null) { return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $microseconds); } /** * Parse a string into a new CarbonInterval object according to the specified format. * * @example * ``` * echo Carboninterval::createFromFormat('H:i', '1:30'); * ``` * * @param string $format Format of the $interval input string * @param string|null $interval Input string to convert into an interval * * @throws \Carbon\Exceptions\ParseErrorException when the $interval cannot be parsed as an interval. * * @return static */ public static function createFromFormat(string $format, ?string $interval): static { $instance = new static(0); $length = mb_strlen($format); if (preg_match('/s([,.])([uv])$/', $format, $match)) { $interval = explode($match[1], $interval); $index = \count($interval) - 1; $interval[$index] = str_pad($interval[$index], $match[2] === 'v' ? 3 : 6, '0'); $interval = implode($match[1], $interval); } $interval ??= ''; for ($index = 0; $index < $length; $index++) { $expected = mb_substr($format, $index, 1); $nextCharacter = mb_substr($interval, 0, 1); $unit = static::$formats[$expected] ?? null; if ($unit) { if (!preg_match('/^-?\d+/', $interval, $match)) { throw new ParseErrorException('number', $nextCharacter); } $interval = mb_substr($interval, mb_strlen($match[0])); self::incrementUnit($instance, $unit, (int) ($match[0])); continue; } if ($nextCharacter !== $expected) { throw new ParseErrorException( "'$expected'", $nextCharacter, 'Allowed substitutes for interval formats are '.implode(', ', array_keys(static::$formats))."\n". 'See https://php.net/manual/en/function.date.php for their meaning', ); } $interval = mb_substr($interval, 1); } if ($interval !== '') { throw new ParseErrorException( 'end of string', $interval, ); } return $instance; } /** * Return the original source used to create the current interval. * * @return array|int|string|DateInterval|mixed|null */ public function original() { return $this->originalInput; } /** * Return the start date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function start(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->startDate; } /** * Return the end date if interval was created from a difference between 2 dates. * * @return CarbonInterface|null */ public function end(): ?CarbonInterface { $this->checkStartAndEnd(); return $this->endDate; } /** * Get rid of the original input, start date and end date that may be kept in memory. * * @return $this */ public function optimize(): static { $this->originalInput = null; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; $this->absolute = false; return $this; } /** * Get a copy of the instance. * * @return static */ public function copy(): static { $date = new static(0); $date->copyProperties($this); $date->step = $this->step; return $date; } /** * Get a copy of the instance. * * @return static */ public function clone(): static { return $this->copy(); } /** * Provide static helpers to create instances. Allows CarbonInterval::years(3). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @return static|mixed|null */ public static function __callStatic(string $method, array $parameters) { try { $interval = new static(0); $localStrictModeEnabled = $interval->localStrictModeEnabled; $interval->localStrictModeEnabled = true; $result = static::hasMacro($method) ? static::bindMacroContext(null, function () use (&$method, &$parameters, &$interval) { return $interval->callMacro($method, $parameters); }) : $interval->$method(...$parameters); $interval->localStrictModeEnabled = $localStrictModeEnabled; return $result; } catch (BadFluentSetterException $exception) { if (Carbon::isStrictModeEnabled()) { throw new BadFluentConstructorException($method, 0, $exception); } return null; } } /** * Evaluate the PHP generated by var_export() and recreate the exported CarbonInterval instance. * * @param array $dump data as exported by var_export() * * @return static */ #[ReturnTypeWillChange] public static function __set_state($dump) { /** @noinspection PhpVoidFunctionResultUsedInspection */ /** @var DateInterval $dateInterval */ $dateInterval = parent::__set_state($dump); return static::instance($dateInterval); } /** * Return the current context from inside a macro callee or a new one if static. * * @return static */ protected static function this(): static { return end(static::$macroContextStack) ?: new static(0); } /** * Creates a CarbonInterval from string. * * Format: * * Suffix | Unit | Example | DateInterval expression * -------|---------|---------|------------------------ * y | years | 1y | P1Y * mo | months | 3mo | P3M * w | weeks | 2w | P2W * d | days | 28d | P28D * h | hours | 4h | PT4H * m | minutes | 12m | PT12M * s | seconds | 59s | PT59S * * e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. * * Special cases: * - An empty string will return a zero interval * - Fractions are allowed for weeks, days, hours and minutes and will be converted * and rounded to the next smaller value (caution: 0.5w = 4d) * * @param string $intervalDefinition * * @throws InvalidIntervalException * * @return static */ public static function fromString(string $intervalDefinition): static { if (empty($intervalDefinition)) { return self::withOriginal(new static(0), $intervalDefinition); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $milliseconds = 0; $microseconds = 0; $pattern = '/(-?\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ([$part, $value, $unit] = array_shift($parts)) { $intValue = (int) $value; $fraction = (float) $value - $intValue; // Fix calculation precision switch (round($fraction, 6)) { case 1: $fraction = 0; $intValue++; break; case 0: $fraction = 0; break; } switch ($unit === 'µs' ? 'µs' : strtolower($unit)) { case 'millennia': case 'millennium': $years += $intValue * CarbonInterface::YEARS_PER_MILLENNIUM; break; case 'century': case 'centuries': $years += $intValue * CarbonInterface::YEARS_PER_CENTURY; break; case 'decade': case 'decades': $years += $intValue * CarbonInterface::YEARS_PER_DECADE; break; case 'year': case 'years': case 'y': case 'yr': case 'yrs': $years += $intValue; break; case 'quarter': case 'quarters': $months += $intValue * CarbonInterface::MONTHS_PER_QUARTER; break; case 'month': case 'months': case 'mo': case 'mos': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getDaysPerWeek(), 'd']; } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getHoursPerDay(), 'h']; } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMinutesPerHour(), 'm']; } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getSecondsPerMinute(), 's']; } break; case 'second': case 'seconds': case 's': $seconds += $intValue; if ($fraction) { $parts[] = [null, $fraction * static::getMillisecondsPerSecond(), 'ms']; } break; case 'millisecond': case 'milliseconds': case 'milli': case 'ms': $milliseconds += $intValue; if ($fraction) { $microseconds += round($fraction * static::getMicrosecondsPerMillisecond()); } break; case 'microsecond': case 'microseconds': case 'micro': case 'µs': $microseconds += $intValue; break; default: throw new InvalidIntervalException( "Invalid part $part in definition $intervalDefinition", ); } } return self::withOriginal( new static($years, $months, $weeks, $days, $hours, $minutes, $seconds, $milliseconds * Carbon::MICROSECONDS_PER_MILLISECOND + $microseconds), $intervalDefinition, ); } /** * Creates a CarbonInterval from string using a different locale. * * @param string $interval interval string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be used instead. * * @return static */ public static function parseFromLocale(string $interval, ?string $locale = null): static { return static::fromString(Carbon::translateTimeString($interval, $locale ?: static::getLocale(), CarbonInterface::DEFAULT_LOCALE)); } /** * Create an interval from the difference between 2 dates. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $start * @param \Carbon\Carbon|\DateTimeInterface|mixed $end * * @return static */ public static function diff($start, $end = null, bool $absolute = false, array $skip = []): static { $start = $start instanceof CarbonInterface ? $start : Carbon::make($start); $end = $end instanceof CarbonInterface ? $end : Carbon::make($end); $rawInterval = $start->diffAsDateInterval($end, $absolute); $interval = static::instance($rawInterval, $skip); $interval->absolute = $absolute; $interval->rawInterval = $rawInterval; $interval->startDate = $start; $interval->endDate = $end; $interval->initialValues = $interval->getInnerValues(); return $interval; } /** * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function abs(bool $absolute = false): static { if ($absolute && $this->invert) { $this->invert(); } return $this; } /** * @alias abs * * Invert the interval if it's inverted. * * @param bool $absolute do nothing if set to false * * @return $this */ public function absolute(bool $absolute = true): static { return $this->abs($absolute); } /** * Cast the current instance into the given class. * * @template T of DateInterval * * @psalm-param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { return self::castIntervalToClass($this, $className); } /** * Create a CarbonInterval instance from a DateInterval one. Can not instance * DateInterval objects created from DateTime::diff() as you can't externally * set the $days field. * * @param DateInterval $interval * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static */ public static function instance(DateInterval $interval, array $skip = [], bool $skipCopy = false): static { if ($skipCopy && $interval instanceof static) { return $interval; } return self::castIntervalToClass($interval, static::class, $skip); } /** * Make a CarbonInterval instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be intervals (skip dates * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * @param bool $skipCopy set to true to return the passed object * (without copying it) if it's already of the * current class * * @return static|null */ public static function make($interval, $unit = null, bool $skipCopy = false): ?self { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->value; } if ($unit) { $interval = "$interval $unit"; } if ($interval instanceof DateInterval) { return static::instance($interval, [], $skipCopy); } if ($interval instanceof Closure) { return self::withOriginal(new static($interval), $interval); } if (!\is_string($interval)) { return null; } return static::makeFromString($interval); } protected static function makeFromString(string $interval): ?self { $interval = preg_replace('/\s+/', ' ', trim($interval)); if (preg_match('/^P[T\d]/', $interval)) { return new static($interval); } if (preg_match('/^(?:\h*-?\d+(?:\.\d+)?\h*[a-z]+)+$/i', $interval)) { return static::fromString($interval); } $intervalInstance = static::createFromDateString($interval); return $intervalInstance->isEmpty() ? null : $intervalInstance; } protected function resolveInterval($interval): ?self { if (!($interval instanceof self)) { return self::make($interval); } return $interval; } /** * Sets up a DateInterval from the relative parts of the string. * * @param string $datetime * * @return static * * @link https://php.net/manual/en/dateinterval.createfromdatestring.php */ public static function createFromDateString(string $datetime): static { $string = strtr($datetime, [ ',' => ' ', ' and ' => ' ', ]); $previousException = null; try { $interval = parent::createFromDateString($string); } catch (Throwable $exception) { $interval = null; $previousException = $exception; } $interval ?: throw new InvalidFormatException( 'Could not create interval from: '.var_export($datetime, true), previous: $previousException, ); if (!($interval instanceof static)) { $interval = static::instance($interval); } return self::withOriginal($interval, $datetime); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the CarbonInterval object. */ public function get(Unit|string $name): int|float|string|null { $name = Unit::toName($name); if (str_starts_with($name, 'total')) { return $this->total(substr($name, 5)); } $resolvedUnit = Carbon::singularUnit(rtrim($name, 'z')); return match ($resolvedUnit) { 'tzname', 'tz_name' => match (true) { ($this->timezoneSetting === null) => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, ($this->timezoneSetting instanceof DateTimeZone) => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, 'year' => $this->y, 'month' => $this->m, 'day' => $this->d, 'hour' => $this->h, 'minute' => $this->i, 'second' => $this->s, 'milli', 'millisecond' => (int) (round($this->f * Carbon::MICROSECONDS_PER_SECOND) / Carbon::MICROSECONDS_PER_MILLISECOND), 'micro', 'microsecond' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND), 'microexcludemilli' => (int) round($this->f * Carbon::MICROSECONDS_PER_SECOND) % Carbon::MICROSECONDS_PER_MILLISECOND, 'week' => (int) ($this->d / (int) static::getDaysPerWeek()), 'daysexcludeweek', 'dayzexcludeweek' => $this->d % (int) static::getDaysPerWeek(), 'locale' => $this->getTranslatorLocale(), default => throw new UnknownGetterException($name, previous: new UnknownGetterException($resolvedUnit)), }; } /** * Get a part of the CarbonInterval object. */ public function __get(string $name): int|float|string|null { return $this->get($name); } /** * Set a part of the CarbonInterval object. * * @param Unit|string|array $name * @param int $value * * @throws UnknownSetterException * * @return $this */ public function set($name, $value = null): static { $properties = \is_array($name) ? $name : [$name => $value]; foreach ($properties as $key => $value) { switch (Carbon::singularUnit($key instanceof Unit ? $key->value : rtrim((string) $key, 'z'))) { case 'year': $this->checkIntegerValue($key, $value); $this->y = $value; $this->handleDecimalPart('year', $value, $this->y); break; case 'month': $this->checkIntegerValue($key, $value); $this->m = $value; $this->handleDecimalPart('month', $value, $this->m); break; case 'week': $this->checkIntegerValue($key, $value); $days = $value * (int) static::getDaysPerWeek(); $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'day': if ($value === false) { break; } $this->checkIntegerValue($key, $value); $this->d = $value; $this->handleDecimalPart('day', $value, $this->d); break; case 'daysexcludeweek': case 'dayzexcludeweek': $this->checkIntegerValue($key, $value); $days = $this->weeks * (int) static::getDaysPerWeek() + $value; $this->assertSafeForInteger('days total (including weeks)', $days); $this->d = $days; $this->handleDecimalPart('day', $days, $this->d); break; case 'hour': $this->checkIntegerValue($key, $value); $this->h = $value; $this->handleDecimalPart('hour', $value, $this->h); break; case 'minute': $this->checkIntegerValue($key, $value); $this->i = $value; $this->handleDecimalPart('minute', $value, $this->i); break; case 'second': $this->checkIntegerValue($key, $value); $this->s = $value; $this->handleDecimalPart('second', $value, $this->s); break; case 'milli': case 'millisecond': $this->microseconds = $value * Carbon::MICROSECONDS_PER_MILLISECOND + $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND; break; case 'micro': case 'microsecond': $this->f = $value / Carbon::MICROSECONDS_PER_SECOND; break; default: if (str_starts_with($key, ' * ')) { return $this->setSetting(substr($key, 3), $value); } if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new UnknownSetterException($key); } $this->$key = $value; } } return $this; } /** * Set a part of the CarbonInterval object. * * @param string $name * @param int $value * * @throws UnknownSetterException */ public function __set(string $name, $value) { $this->set($name, $value); } /** * Allow setting of weeks and days to be cumulative. * * @param int $weeks Number of weeks to set * @param int $days Number of days to set * * @return static */ public function weeksAndDays(int $weeks, int $days): static { $this->dayz = ($weeks * static::getDaysPerWeek()) + $days; return $this; } /** * Returns true if the interval is empty for each unit. * * @return bool */ public function isEmpty(): bool { return $this->years === 0 && $this->months === 0 && $this->dayz === 0 && !$this->days && $this->hours === 0 && $this->minutes === 0 && $this->seconds === 0 && $this->microseconds === 0; } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonInterval::macro('twice', function () { * return $this->times(2); * }); * echo CarbonInterval::hours(2)->twice(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonInterval::mixin(new class { * public function daysToHours() { * return function () { * $this->hours += $this->days; * $this->days = 0; * * return $this; * }; * } * public function hoursToDays() { * return function () { * $this->days += $this->hours; * $this->hours = 0; * * return $this; * }; * } * }); * echo CarbonInterval::hours(5)->hoursToDays() . "\n"; * echo CarbonInterval::days(5)->daysToHours() . "\n"; * ``` * * @param object|string $mixin * * @throws ReflectionException * * @return void */ public static function mixin($mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. * * @param string $name * * @return bool */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Call given macro. * * @param string $name * @param array $parameters * * @return mixed */ protected function callMacro(string $name, array $parameters) { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Allow fluent calls on the setters... CarbonInterval::years(3)->months(5)->day(). * * Note: This is done using the magic method to allow static and instance methods to * have the same names. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadFluentSetterException|Throwable * * @return static|int|float|string */ public function __call(string $method, array $parameters) { if (static::hasMacro($method)) { return static::bindMacroContext($this, function () use (&$method, &$parameters) { return $this->callMacro($method, $parameters); }); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } if (preg_match('/^(?<method>add|sub)(?<unit>[A-Z].*)$/', $method, $match)) { $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($match['unit']), 0); return $this->{$match['method']}($value, $match['unit']); } $value = $this->getMagicParameter($parameters, 0, Carbon::pluralUnit($method), 1); try { $this->set($method, $value); } catch (UnknownSetterException $exception) { if ($this->localStrictModeEnabled ?? Carbon::isStrictModeEnabled()) { throw new BadFluentSetterException($method, 0, $exception); } } return $this; } protected function getForHumansInitialVariables($syntax, $short): array { if (\is_array($syntax)) { return $syntax; } if (\is_int($short)) { return [ 'parts' => $short, 'short' => false, ]; } if (\is_bool($syntax)) { return [ 'short' => $syntax, 'syntax' => CarbonInterface::DIFF_ABSOLUTE, ]; } return []; } /** * @param mixed $syntax * @param mixed $short * @param mixed $parts * @param mixed $options * * @return array */ protected function getForHumansParameters($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): array { $optionalSpace = ' '; $default = $this->getTranslationMessage('list.0') ?? $this->getTranslationMessage('list') ?? ' '; /** @var bool|string $join */ $join = $default === '' ? '' : ' '; /** @var bool|array|string $altNumbers */ $altNumbers = false; $aUnit = false; $minimumUnit = 's'; $skip = []; extract($this->getForHumansInitialVariables($syntax, $short)); $skip = array_map( static fn ($unit) => $unit instanceof Unit ? $unit->value : $unit, (array) $skip, ); $skip = array_map( 'strtolower', array_filter($skip, static fn ($unit) => \is_string($unit) && $unit !== ''), ); $syntax ??= CarbonInterface::DIFF_ABSOLUTE; if ($parts === self::NO_LIMIT) { $parts = INF; } $options ??= static::getHumanDiffOptions(); if ($join === false) { $join = ' '; } elseif ($join === true) { $join = [ $default, $this->getTranslationMessage('list.1') ?? $default, ]; } if ($altNumbers && $altNumbers !== true) { $language = new Language($this->locale); $altNumbers = \in_array($language->getCode(), (array) $altNumbers, true); } if (\is_array($join)) { [$default, $last] = $join; if ($default !== ' ') { $optionalSpace = ''; } $join = function ($list) use ($default, $last) { if (\count($list) < 2) { return implode('', $list); } $end = array_pop($list); return implode($default, $list).$last.$end; }; } if (\is_string($join)) { if ($join !== ' ') { $optionalSpace = ''; } $glue = $join; $join = static fn ($list) => implode($glue, $list); } $interpolations = [ ':optional-space' => $optionalSpace, ]; $translator ??= isset($locale) ? Translator::get($locale) : null; return [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator]; } protected static function getRoundingMethodFromOptions(int $options): ?string { if ($options & CarbonInterface::ROUND) { return 'round'; } if ($options & CarbonInterface::CEIL) { return 'ceil'; } if ($options & CarbonInterface::FLOOR) { return 'floor'; } return null; } /** * Returns interval values as an array where key are the unit names and values the counts. * * @return int[] */ public function toArray(): array { return [ 'years' => $this->years, 'months' => $this->months, 'weeks' => $this->weeks, 'days' => $this->daysExcludeWeeks, 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'microseconds' => $this->microseconds, ]; } /** * Returns interval non-zero values as an array where key are the unit names and values the counts. * * @return int[] */ public function getNonZeroValues(): array { return array_filter($this->toArray(), 'intval'); } /** * Returns interval values as an array where key are the unit names and values the counts * from the biggest non-zero one the the smallest non-zero one. * * @return int[] */ public function getValuesSequence(): array { $nonZeroValues = $this->getNonZeroValues(); if ($nonZeroValues === []) { return []; } $keys = array_keys($nonZeroValues); $firstKey = $keys[0]; $lastKey = $keys[\count($keys) - 1]; $values = []; $record = false; foreach ($this->toArray() as $unit => $count) { if ($unit === $firstKey) { $record = true; } if ($record) { $values[$unit] = $count; } if ($unit === $lastKey) { $record = false; } } return $values; } /** * Get the current interval in a human readable format in the current locale. * * @example * ``` * echo CarbonInterval::fromString('4d 3h 40m')->forHumans() . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 2]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['parts' => 3, 'join' => true]) . "\n"; * echo CarbonInterval::fromString('4d 3h 40m')->forHumans(['short' => true]) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['join' => ' or ']) . "\n"; * echo CarbonInterval::fromString('1d 24h')->forHumans(['minimumUnit' => 'hour']) . "\n"; * ``` * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contain: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: -1: no limits) * @param int $options human diff options * * @throws Exception * * @return string */ public function forHumans($syntax = null, $short = false, $parts = self::NO_LIMIT, $options = null): string { /* @var TranslatorInterface|null $translator */ [$syntax, $short, $parts, $options, $join, $aUnit, $altNumbers, $interpolations, $minimumUnit, $skip, $translator] = $this ->getForHumansParameters($syntax, $short, $parts, $options); $interval = []; $syntax = (int) ($syntax ?? CarbonInterface::DIFF_ABSOLUTE); $absolute = $syntax === CarbonInterface::DIFF_ABSOLUTE; $relativeToNow = $syntax === CarbonInterface::DIFF_RELATIVE_TO_NOW; $count = 1; $unit = $short ? 's' : 'second'; $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); $declensionMode = null; $translator ??= $this->getLocalTranslator(); $handleDeclensions = function ($unit, $count, $index = 0, $parts = 1) use ($interpolations, $transId, $translator, $altNumbers, $absolute, &$declensionMode) { if (!$absolute) { $declensionMode = $declensionMode ?? $this->translate($transId.'_mode'); if ($this->needsDeclension($declensionMode, $index, $parts)) { // Some languages have special pluralization for past and future tense. $key = $unit.'_'.$transId; $result = $this->translate($key, $interpolations, $count, $translator, $altNumbers); if ($result !== $key) { return $result; } } } $result = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); if ($result !== $unit) { return $result; } return null; }; $intervalValues = $this; $method = static::getRoundingMethodFromOptions($options); if ($method) { $previousCount = INF; while ( \count($intervalValues->getNonZeroValues()) > $parts && ($count = \count($keys = array_keys($intervalValues->getValuesSequence()))) > 1 ) { $index = min($count, $previousCount - 1) - 2; if ($index < 0) { break; } $intervalValues = $this->copy()->roundUnit( $keys[$index], 1, $method, ); $previousCount = $count; } } $diffIntervalArray = [ ['value' => $intervalValues->years, 'unit' => 'year', 'unitShort' => 'y'], ['value' => $intervalValues->months, 'unit' => 'month', 'unitShort' => 'm'], ['value' => $intervalValues->weeks, 'unit' => 'week', 'unitShort' => 'w'], ['value' => $intervalValues->daysExcludeWeeks, 'unit' => 'day', 'unitShort' => 'd'], ['value' => $intervalValues->hours, 'unit' => 'hour', 'unitShort' => 'h'], ['value' => $intervalValues->minutes, 'unit' => 'minute', 'unitShort' => 'min'], ['value' => $intervalValues->seconds, 'unit' => 'second', 'unitShort' => 's'], ['value' => $intervalValues->milliseconds, 'unit' => 'millisecond', 'unitShort' => 'ms'], ['value' => $intervalValues->microExcludeMilli, 'unit' => 'microsecond', 'unitShort' => 'µs'], ]; if (!empty($skip)) { foreach ($diffIntervalArray as $index => &$unitData) { $nextIndex = $index + 1; if ($unitData['value'] && isset($diffIntervalArray[$nextIndex]) && \count(array_intersect([$unitData['unit'], $unitData['unit'].'s', $unitData['unitShort']], $skip)) ) { $diffIntervalArray[$nextIndex]['value'] += $unitData['value'] * self::getFactorWithDefault($diffIntervalArray[$nextIndex]['unit'], $unitData['unit']); $unitData['value'] = 0; } } } $transChoice = function ($short, $unitData, $index, $parts) use ($absolute, $handleDeclensions, $translator, $aUnit, $altNumbers, $interpolations) { $count = $unitData['value']; if ($short) { $result = $handleDeclensions($unitData['unitShort'], $count, $index, $parts); if ($result !== null) { return $result; } } elseif ($aUnit) { $result = $handleDeclensions('a_'.$unitData['unit'], $count, $index, $parts); if ($result !== null) { return $result; } } if (!$absolute) { return $handleDeclensions($unitData['unit'], $count, $index, $parts); } return $this->translate($unitData['unit'], $interpolations, $count, $translator, $altNumbers); }; $fallbackUnit = ['second', 's']; foreach ($diffIntervalArray as $diffIntervalData) { if ($diffIntervalData['value'] > 0) { $unit = $short ? $diffIntervalData['unitShort'] : $diffIntervalData['unit']; $count = $diffIntervalData['value']; $interval[] = [$short, $diffIntervalData]; } elseif ($options & CarbonInterface::SEQUENTIAL_PARTS_ONLY && \count($interval) > 0) { break; } // break the loop after we get the required number of parts in array if (\count($interval) >= $parts) { break; } // break the loop after we have reached the minimum unit if (\in_array($minimumUnit, [$diffIntervalData['unit'], $diffIntervalData['unitShort']], true)) { $fallbackUnit = [$diffIntervalData['unit'], $diffIntervalData['unitShort']]; break; } } $actualParts = \count($interval); foreach ($interval as $index => &$item) { $item = $transChoice($item[0], $item[1], $index, $actualParts); } if (\count($interval) === 0) { if ($relativeToNow && $options & CarbonInterface::JUST_NOW) { $key = 'diff_now'; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } $count = $options & CarbonInterface::NO_ZERO_DIFF ? 1 : 0; $unit = $fallbackUnit[$short ? 1 : 0]; $interval[] = $this->translate($unit, $interpolations, $count, $translator, $altNumbers); } // join the interval parts by a space $time = $join($interval); unset($diffIntervalArray, $interval); if ($absolute) { return $time; } $isFuture = $this->invert === 1; $transId = $relativeToNow ? ($isFuture ? 'from_now' : 'ago') : ($isFuture ? 'after' : 'before'); if ($parts === 1) { if ($relativeToNow && $unit === 'day') { $specialTranslations = static::SPECIAL_TRANSLATIONS[$count] ?? null; if ($specialTranslations && $options & $specialTranslations['option']) { $key = $specialTranslations[$isFuture ? 'future' : 'past']; $translation = $this->translate($key, $interpolations, null, $translator); if ($translation !== $key) { return $translation; } } } $aTime = $aUnit ? $handleDeclensions('a_'.$unit, $count) : null; $time = $aTime ?: $handleDeclensions($unit, $count) ?: $time; } $time = [':time' => $time]; return $this->translate($transId, array_merge($time, $interpolations, $time), null, $translator); } public function format(string $format): string { $output = parent::format($format); if (!str_contains($format, '%a') || !isset($this->startDate, $this->endDate)) { return $output; } $this->rawInterval ??= $this->startDate->diffAsDateInterval($this->endDate); return str_replace('(unknown)', $this->rawInterval->format('%a'), $output); } /** * Format the instance as a string using the forHumans() function. * * @throws Exception * * @return string */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if (!$format) { return $this->forHumans(); } if ($format instanceof Closure) { return $format($this); } return $this->format($format); } /** * Return native DateInterval PHP object matching the current instance. * * @example * ``` * var_dump(CarbonInterval::hours(2)->toDateInterval()); * ``` * * @return DateInterval */ public function toDateInterval(): DateInterval { return self::castIntervalToClass($this, DateInterval::class); } /** * Convert the interval to a CarbonPeriod. * * @param DateTimeInterface|string|int ...$params Start date, [end date or recurrences] and optional settings. * * @return CarbonPeriod */ public function toPeriod(...$params): CarbonPeriod { if ($this->timezoneSetting) { $timeZone = \is_string($this->timezoneSetting) ? new DateTimeZone($this->timezoneSetting) : $this->timezoneSetting; if ($timeZone instanceof DateTimeZone) { array_unshift($params, $timeZone); } } $class = ($params[0] ?? null) instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($this, ...$params); } /** * Decompose the current interval into * * @param mixed|int|DateInterval|string|Closure|Unit|null $interval interval or number of the given $unit * @param Unit|string|null $unit if specified, $interval must be an integer * * @return CarbonPeriod */ public function stepBy($interval, Unit|string|null $unit = null): CarbonPeriod { $this->checkStartAndEnd(); $start = $this->startDate ?? CarbonImmutable::make('now'); $end = $this->endDate ?? $start->copy()->add($this); try { $step = static::make($interval, $unit); } catch (InvalidFormatException $exception) { if ($unit || (\is_string($interval) ? preg_match('/(\s|\d)/', $interval) : !($interval instanceof Unit))) { throw $exception; } $step = static::make(1, $interval); } $class = $start instanceof DateTime ? CarbonPeriod::class : CarbonPeriodImmutable::class; return $class::create($step, $start, $end); } /** * Invert the interval. * * @param bool|int $inverted if a parameter is passed, the passed value cast as 1 or 0 is used * as the new value of the ->invert property. * * @return $this */ public function invert($inverted = null): static { $this->invert = (\func_num_args() === 0 ? !$this->invert : $inverted) ? 1 : 0; return $this; } protected function solveNegativeInterval(): static { if (!$this->isEmpty() && $this->years <= 0 && $this->months <= 0 && $this->dayz <= 0 && $this->hours <= 0 && $this->minutes <= 0 && $this->seconds <= 0 && $this->microseconds <= 0) { $this->years *= self::NEGATIVE; $this->months *= self::NEGATIVE; $this->dayz *= self::NEGATIVE; $this->hours *= self::NEGATIVE; $this->minutes *= self::NEGATIVE; $this->seconds *= self::NEGATIVE; $this->microseconds *= self::NEGATIVE; $this->invert(); } return $this; } /** * Add the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function add($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } if (\is_string($unit) && !preg_match('/^\s*-?\d/', $unit)) { $unit = "$value $unit"; $value = 1; } $interval = static::make($unit); if (!$interval) { throw new InvalidIntervalException('This type of data cannot be added/subtracted.'); } if ($value !== 1) { $interval->times($value); } $sign = ($this->invert === 1) !== ($interval->invert === 1) ? self::NEGATIVE : self::POSITIVE; $this->years += $interval->y * $sign; $this->months += $interval->m * $sign; $this->dayz += ($interval->days === false ? $interval->d : $interval->days) * $sign; $this->hours += $interval->h * $sign; $this->minutes += $interval->i * $sign; $this->seconds += $interval->s * $sign; $this->microseconds += $interval->microseconds * $sign; $this->solveNegativeInterval(); return $this; } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function sub($unit, $value = 1): static { if (is_numeric($unit)) { [$value, $unit] = [$unit, $value]; } return $this->add($unit, -(float) $value); } /** * Subtract the passed interval to the current instance. * * @param string|DateInterval $unit * @param int|float $value * * @return $this */ public function subtract($unit, $value = 1): static { return $this->sub($unit, $value); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function plus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->add(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Add given parameters to the current interval. * * @param int $years * @param int $months * @param int|float $weeks * @param int|float $days * @param int|float $hours * @param int|float $minutes * @param int|float $seconds * @param int|float $microseconds * * @return $this */ public function minus( $years = 0, $months = 0, $weeks = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0, $microseconds = 0 ): static { return $this->sub(" $years years $months months $weeks weeks $days days $hours hours $minutes minutes $seconds seconds $microseconds microseconds "); } /** * Multiply current instance given number of times. times() is naive, it multiplies each unit * (so day can be greater than 31, hour can be greater than 23, etc.) and the result is rounded * separately for each unit. * * Use times() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see multiply() * * @param float|int $factor * * @return $this */ public function times($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $this->years = (int) round($this->years * $factor); $this->months = (int) round($this->months * $factor); $this->dayz = (int) round($this->dayz * $factor); $this->hours = (int) round($this->hours * $factor); $this->minutes = (int) round($this->minutes * $factor); $this->seconds = (int) round($this->seconds * $factor); $this->microseconds = (int) round($this->microseconds * $factor); return $this; } /** * Divide current instance by a given divider. shares() is naive, it divides each unit separately * and the result is rounded for each unit. So 5 hours and 20 minutes shared by 3 becomes 2 hours * and 7 minutes. * * Use shares() when you want a fast and approximated calculation that does not cascade units. * * For a precise and cascaded calculation, * * @see divide() * * @param float|int $divider * * @return $this */ public function shares($divider): static { return $this->times(1 / $divider); } protected function copyProperties(self $interval, $ignoreSign = false): static { $this->years = $interval->years; $this->months = $interval->months; $this->dayz = $interval->dayz; $this->hours = $interval->hours; $this->minutes = $interval->minutes; $this->seconds = $interval->seconds; $this->microseconds = $interval->microseconds; if (!$ignoreSign) { $this->invert = $interval->invert; } return $this; } /** * Multiply and cascade current instance by a given factor. * * @param float|int $factor * * @return $this */ public function multiply($factor): static { if ($factor < 0) { $this->invert = $this->invert ? 0 : 1; $factor = -$factor; } $yearPart = (int) floor($this->years * $factor); // Split calculation to prevent imprecision if ($yearPart) { $this->years -= $yearPart / $factor; } return $this->copyProperties( static::create($yearPart) ->microseconds(abs($this->totalMicroseconds) * $factor) ->cascade(), true, ); } /** * Divide and cascade current instance by a given divider. * * @param float|int $divider * * @return $this */ public function divide($divider): static { return $this->multiply(1 / $divider); } /** * Get the interval_spec string of a date interval. * * @param DateInterval $interval * * @return string */ public static function getDateIntervalSpec(DateInterval $interval, bool $microseconds = false, array $skip = []): string { $date = array_filter([ static::PERIOD_YEARS => abs($interval->y), static::PERIOD_MONTHS => abs($interval->m), static::PERIOD_DAYS => abs($interval->d), ]); $skip = array_map([Unit::class, 'toNameIfUnit'], $skip); if ( $interval->days >= CarbonInterface::DAYS_PER_WEEK * CarbonInterface::WEEKS_PER_MONTH && (!isset($date[static::PERIOD_YEARS]) || \count(array_intersect(['y', 'year', 'years'], $skip))) && (!isset($date[static::PERIOD_MONTHS]) || \count(array_intersect(['m', 'month', 'months'], $skip))) ) { $date = [ static::PERIOD_DAYS => abs($interval->days), ]; } $seconds = abs($interval->s); if ($microseconds && $interval->f > 0) { $seconds = \sprintf('%d.%06d', $seconds, abs($interval->f) * 1000000); } $time = array_filter([ static::PERIOD_HOURS => abs($interval->h), static::PERIOD_MINUTES => abs($interval->i), static::PERIOD_SECONDS => $seconds, ]); $specString = static::PERIOD_PREFIX; foreach ($date as $key => $value) { $specString .= $value.$key; } if (\count($time) > 0) { $specString .= static::PERIOD_TIME_PREFIX; foreach ($time as $key => $value) { $specString .= $value.$key; } } return $specString === static::PERIOD_PREFIX ? 'PT0S' : $specString; } /** * Get the interval_spec string. * * @return string */ public function spec(bool $microseconds = false): string { return static::getDateIntervalSpec($this, $microseconds); } /** * Comparing 2 date intervals. * * @param DateInterval $first * @param DateInterval $second * * @return int 0, 1 or -1 */ public static function compareDateIntervals(DateInterval $first, DateInterval $second): int { $current = Carbon::now(); $passed = $current->avoidMutation()->add($second); $current->add($first); return $current <=> $passed; } /** * Comparing with passed interval. * * @param DateInterval $interval * * @return int 0, 1 or -1 */ public function compare(DateInterval $interval): int { return static::compareDateIntervals($this, $interval); } /** * Convert overflowed values into bigger units. * * @return $this */ public function cascade(): static { return $this->doCascade(false); } public function hasNegativeValues(): bool { foreach ($this->toArray() as $value) { if ($value < 0) { return true; } } return false; } public function hasPositiveValues(): bool { foreach ($this->toArray() as $value) { if ($value > 0) { return true; } } return false; } /** * Get amount of given unit equivalent to the interval. * * @param string $unit * * @throws UnknownUnitException|UnitNotConfiguredException * * @return float */ public function total(string $unit): float { $realUnit = $unit = strtolower($unit); if (\in_array($unit, ['days', 'weeks'])) { $realUnit = 'dayz'; } elseif (!\in_array($unit, ['microseconds', 'milliseconds', 'seconds', 'minutes', 'hours', 'dayz', 'months', 'years'])) { throw new UnknownUnitException($unit); } $this->checkStartAndEnd(); if ($this->startDate && $this->endDate) { $diff = $this->startDate->diffInUnit($unit, $this->endDate); return $this->absolute ? abs($diff) : $diff; } $result = 0; $cumulativeFactor = 0; $unitFound = false; $factors = self::getFlipCascadeFactors(); $daysPerWeek = (int) static::getDaysPerWeek(); $values = [ 'years' => $this->years, 'months' => $this->months, 'weeks' => (int) ($this->d / $daysPerWeek), 'dayz' => fmod($this->d, $daysPerWeek), 'hours' => $this->hours, 'minutes' => $this->minutes, 'seconds' => $this->seconds, 'milliseconds' => (int) ($this->microseconds / Carbon::MICROSECONDS_PER_MILLISECOND), 'microseconds' => $this->microseconds % Carbon::MICROSECONDS_PER_MILLISECOND, ]; if (isset($factors['dayz']) && $factors['dayz'][0] !== 'weeks') { $values['dayz'] += $values['weeks'] * $daysPerWeek; $values['weeks'] = 0; } foreach ($factors as $source => [$target, $factor]) { if ($source === $realUnit) { $unitFound = true; $value = $values[$source]; $result += $value; $cumulativeFactor = 1; } if ($factor === false) { if ($unitFound) { break; } $result = 0; $cumulativeFactor = 0; continue; } if ($target === $realUnit) { $unitFound = true; } if ($cumulativeFactor) { $cumulativeFactor *= $factor; $result += $values[$target] * $cumulativeFactor; continue; } $value = $values[$source]; $result = ($result + $value) / $factor; } if (isset($target) && !$cumulativeFactor) { $result += $values[$target]; } if (!$unitFound) { throw new UnitNotConfiguredException($unit); } if ($this->invert) { $result *= self::NEGATIVE; } if ($unit === 'weeks') { $result /= $daysPerWeek; } // Cast as int numbers with no decimal part return fmod($result, 1) === 0.0 ? (int) $result : $result; } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see equalTo() * * @return bool */ public function eq($interval): bool { return $this->equalTo($interval); } /** * Determines if the instance is equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function equalTo($interval): bool { $interval = $this->resolveInterval($interval); if ($interval === null) { return false; } $step = $this->getStep(); if ($step) { return $step === $interval->getStep(); } if ($this->isEmpty()) { return $interval->isEmpty(); } $cascadedInterval = $this->copy()->cascade(); $comparedInterval = $interval->copy()->cascade(); return $cascadedInterval->invert === $comparedInterval->invert && $cascadedInterval->getNonZeroValues() === $comparedInterval->getNonZeroValues(); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see notEqualTo() * * @return bool */ public function ne($interval): bool { return $this->notEqualTo($interval); } /** * Determines if the instance is not equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function notEqualTo($interval): bool { return !$this->eq($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThan() * * @return bool */ public function gt($interval): bool { return $this->greaterThan($interval); } /** * Determines if the instance is greater (longer) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval === null || $this->totalMicroseconds > $interval->totalMicroseconds; } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see greaterThanOrEqualTo() * * @return bool */ public function gte($interval): bool { return $this->greaterThanOrEqualTo($interval); } /** * Determines if the instance is greater (longer) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function greaterThanOrEqualTo($interval): bool { return $this->greaterThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThan() * * @return bool */ public function lt($interval): bool { return $this->lessThan($interval); } /** * Determines if the instance is less (shorter) than another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThan($interval): bool { $interval = $this->resolveInterval($interval); return $interval !== null && $this->totalMicroseconds < $interval->totalMicroseconds; } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @see lessThanOrEqualTo() * * @return bool */ public function lte($interval): bool { return $this->lessThanOrEqualTo($interval); } /** * Determines if the instance is less (shorter) than or equal to another * * @param CarbonInterval|DateInterval|mixed $interval * * @return bool */ public function lessThanOrEqualTo($interval): bool { return $this->lessThan($interval) || $this->equalTo($interval); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->between(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function between($interval1, $interval2, bool $equal = true): bool { return $equal ? $this->greaterThanOrEqualTo($interval1) && $this->lessThanOrEqualTo($interval2) : $this->greaterThan($interval1) && $this->lessThan($interval2); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // true * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenIncluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->betweenExcluded(CarbonInterval::day(), CarbonInterval::days(2)); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * * @return bool */ public function betweenExcluded($interval1, $interval2): bool { return $this->between($interval1, $interval2, false); } /** * Determines if the instance is between two others * * @example * ``` * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(3)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::hours(36)); // false * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2)); // true * CarbonInterval::hours(48)->isBetween(CarbonInterval::day(), CarbonInterval::days(2), false); // false * ``` * * @param CarbonInterval|DateInterval|mixed $interval1 * @param CarbonInterval|DateInterval|mixed $interval2 * @param bool $equal Indicates if an equal to comparison should be done * * @return bool */ public function isBetween($interval1, $interval2, bool $equal = true): bool { return $this->between($interval1, $interval2, $equal); } /** * Round the current instance at the given unit with given precision if specified and the given function. * * @throws Exception */ public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static { if (static::getCascadeFactors() !== static::getDefaultCascadeFactors()) { $value = $function($this->total($unit) / $precision) * $precision; $inverted = $value < 0; return $this->copyProperties(self::fromString( number_format(abs($value), 12, '.', '').' '.$unit )->invert($inverted)->cascade()); } $base = CarbonImmutable::parse('2000-01-01 00:00:00', 'UTC') ->roundUnit($unit, $precision, $function); $next = $base->add($this); $inverted = $next < $base; if ($inverted) { $next = $base->sub($this); } $this->copyProperties( $next ->roundUnit($unit, $precision, $function) ->diff($base), ); return $this->invert($inverted); } /** * Truncate the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function floorUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. * * @param string $unit * @param float|int|string|DateInterval|null $precision * * @throws Exception * * @return $this */ public function ceilUnit(string $unit, $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified. * * @param float|int|string|DateInterval|null $precision * @param string $function * * @throws Exception * * @return $this */ public function round($precision = 1, string $function = 'round'): static { return $this->roundWith($precision, $function); } /** * Round the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function floor(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified. * * @throws Exception * * @return $this */ public function ceil(DateInterval|string|float|int $precision = 1): static { return $this->round($precision, 'ceil'); } public function __unserialize(array $data): void { $properties = array_combine( array_map( static fn (mixed $key) => \is_string($key) ? str_replace('tzName', 'timezoneSetting', $key) : $key, array_keys($data), ), $data, ); if (method_exists(parent::class, '__unserialize')) { // PHP >= 8.2 parent::__unserialize($properties); return; } // PHP <= 8.1 // @codeCoverageIgnoreStart $properties = array_combine( array_map( static fn (string $property) => preg_replace('/^\0.+\0/', '', $property), array_keys($data), ), $data, ); $localStrictMode = $this->localStrictModeEnabled; $this->localStrictModeEnabled = false; $days = $properties['days'] ?? false; $this->days = $days === false ? false : (int) $days; $this->y = (int) ($properties['y'] ?? 0); $this->m = (int) ($properties['m'] ?? 0); $this->d = (int) ($properties['d'] ?? 0); $this->h = (int) ($properties['h'] ?? 0); $this->i = (int) ($properties['i'] ?? 0); $this->s = (int) ($properties['s'] ?? 0); $this->f = (float) ($properties['f'] ?? 0.0); // @phpstan-ignore-next-line $this->weekday = (int) ($properties['weekday'] ?? 0); // @phpstan-ignore-next-line $this->weekday_behavior = (int) ($properties['weekday_behavior'] ?? 0); // @phpstan-ignore-next-line $this->first_last_day_of = (int) ($properties['first_last_day_of'] ?? 0); $this->invert = (int) ($properties['invert'] ?? 0); // @phpstan-ignore-next-line $this->special_type = (int) ($properties['special_type'] ?? 0); // @phpstan-ignore-next-line $this->special_amount = (int) ($properties['special_amount'] ?? 0); // @phpstan-ignore-next-line $this->have_weekday_relative = (int) ($properties['have_weekday_relative'] ?? 0); // @phpstan-ignore-next-line $this->have_special_relative = (int) ($properties['have_special_relative'] ?? 0); parent::__construct(self::getDateIntervalSpec($this)); foreach ($properties as $property => $value) { if ($property === 'localStrictModeEnabled') { continue; } $this->$property = $value; } $this->localStrictModeEnabled = $properties['localStrictModeEnabled'] ?? $localStrictMode; // @codeCoverageIgnoreEnd } /** * @template T * * @param T $interval * @param mixed $original * * @return T */ private static function withOriginal(mixed $interval, mixed $original): mixed { if ($interval instanceof self) { $interval->originalInput = $original; } return $interval; } private static function standardizeUnit(string $unit): string { $unit = rtrim($unit, 'sz').'s'; return $unit === 'days' ? 'dayz' : $unit; } private static function getFlipCascadeFactors(): array { if (!self::$flipCascadeFactors) { self::$flipCascadeFactors = []; foreach (self::getCascadeFactors() as $to => [$factor, $from]) { self::$flipCascadeFactors[self::standardizeUnit($from)] = [self::standardizeUnit($to), $factor]; } } return self::$flipCascadeFactors; } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function castIntervalToClass(DateInterval $interval, string $className, array $skip = []): object { $mainClass = DateInterval::class; if (!is_a($className, $mainClass, true)) { throw new InvalidCastException("$className is not a sub-class of $mainClass."); } $microseconds = $interval->f; $instance = self::buildInstance($interval, $className, $skip); if ($instance instanceof self) { $instance->originalInput = $interval; } if ($microseconds) { $instance->f = $microseconds; } if ($interval instanceof self && is_a($className, self::class, true)) { self::copyStep($interval, $instance); } self::copyNegativeUnits($interval, $instance); return self::withOriginal($instance, $interval); } /** * @template T of DateInterval * * @param DateInterval $interval * * @psalm-param class-string<T> $className * * @return T */ private static function buildInstance( DateInterval $interval, string $className, array $skip = [], ): object { $serialization = self::buildSerializationString($interval, $className, $skip); return match ($serialization) { null => new $className(static::getDateIntervalSpec($interval, false, $skip)), default => unserialize($serialization), }; } /** * As demonstrated by rlanvin (https://github.com/rlanvin) in * https://github.com/briannesbitt/Carbon/issues/3018#issuecomment-2888538438 * * Modifying the output of serialize() to change the class name and unserializing * the tweaked string allows creating new interval instances where the ->days * property can be set. It's not possible neither with `new` nto with `__set_state`. * * It has a non-negligible performance cost, so we'll use this method only if * $interval->days !== false. */ private static function buildSerializationString( DateInterval $interval, string $className, array $skip = [], ): ?string { if ($interval->days === false || PHP_VERSION_ID < 8_02_00 || $skip !== []) { return null; } // De-enhance CarbonInterval objects to be serializable back to DateInterval if ($interval instanceof self && !is_a($className, self::class, true)) { $interval = clone $interval; unset($interval->timezoneSetting); unset($interval->originalInput); unset($interval->startDate); unset($interval->endDate); unset($interval->rawInterval); unset($interval->absolute); unset($interval->initialValues); unset($interval->clock); unset($interval->step); unset($interval->localMonthsOverflow); unset($interval->localYearsOverflow); unset($interval->localStrictModeEnabled); unset($interval->localHumanDiffOptions); unset($interval->localToStringFormat); unset($interval->localSerializer); unset($interval->localMacros); unset($interval->localGenericMacros); unset($interval->localFormatFunction); unset($interval->localTranslator); } $serialization = serialize($interval); $inputClass = $interval::class; $expectedStart = 'O:'.\strlen($inputClass).':"'.$inputClass.'":'; if (!str_starts_with($serialization, $expectedStart)) { return null; // @codeCoverageIgnore } return 'O:'.\strlen($className).':"'.$className.'":'.substr($serialization, \strlen($expectedStart)); } private static function copyStep(self $from, self $to): void { $to->setStep($from->getStep()); } private static function copyNegativeUnits(DateInterval $from, DateInterval $to): void { $to->invert = $from->invert; foreach (['y', 'm', 'd', 'h', 'i', 's'] as $unit) { if ($from->$unit < 0) { self::setIntervalUnit($to, $unit, $to->$unit * self::NEGATIVE); } } } private function invertCascade(array $values): static { return $this->set(array_map(function ($value) { return -$value; }, $values))->doCascade(true)->invert(); } private function doCascade(bool $deep): static { $originalData = $this->toArray(); $originalData['milliseconds'] = (int) ($originalData['microseconds'] / static::getMicrosecondsPerMillisecond()); $originalData['microseconds'] = $originalData['microseconds'] % static::getMicrosecondsPerMillisecond(); $originalData['weeks'] = (int) ($this->d / static::getDaysPerWeek()); $originalData['daysExcludeWeeks'] = fmod($this->d, static::getDaysPerWeek()); unset($originalData['days']); $newData = $originalData; $previous = []; foreach (self::getFlipCascadeFactors() as $source => [$target, $factor]) { foreach (['source', 'target'] as $key) { if ($$key === 'dayz') { $$key = 'daysExcludeWeeks'; } } $value = $newData[$source]; $modulo = fmod($factor + fmod($value, $factor), $factor); $newData[$source] = $modulo; $newData[$target] += ($value - $modulo) / $factor; $decimalPart = fmod($newData[$source], 1); if ($decimalPart !== 0.0) { $unit = $source; foreach ($previous as [$subUnit, $subFactor]) { $newData[$unit] -= $decimalPart; $newData[$subUnit] += $decimalPart * $subFactor; $decimalPart = fmod($newData[$subUnit], 1); if ($decimalPart === 0.0) { break; } $unit = $subUnit; } } array_unshift($previous, [$source, $factor]); } $positive = null; if (!$deep) { foreach ($newData as $value) { if ($value) { if ($positive === null) { $positive = ($value > 0); continue; } if (($value > 0) !== $positive) { return $this->invertCascade($originalData) ->solveNegativeInterval(); } } } } return $this->set($newData) ->solveNegativeInterval(); } private function needsDeclension(string $mode, int $index, int $parts): bool { return match ($mode) { 'last' => $index === $parts - 1, default => true, }; } private function checkIntegerValue(string $name, mixed $value): void { if (\is_int($value)) { return; } $this->assertSafeForInteger($name, $value); if (\is_float($value) && (((float) (int) $value) === $value)) { return; } if (!self::$floatSettersEnabled) { $type = \gettype($value); @trigger_error( "Since 2.70.0, it's deprecated to pass $type value for $name.\n". "It's truncated when stored as an integer interval unit.\n". "From 3.0.0, decimal part will no longer be truncated and will be cascaded to smaller units.\n". "- To maintain the current behavior, use explicit cast: $name((int) \$value)\n". "- To adopt the new behavior globally, call CarbonInterval::enableFloatSetters()\n", \E_USER_DEPRECATED, ); } } /** * Throw an exception if precision loss when storing the given value as an integer would be >= 1.0. */ private function assertSafeForInteger(string $name, mixed $value): void { if ($value && !\is_int($value) && ($value >= 0x7fffffffffffffff || $value <= -0x7fffffffffffffff)) { throw new OutOfRangeException($name, -0x7fffffffffffffff, 0x7fffffffffffffff, $value); } } private function handleDecimalPart(string $unit, mixed $value, mixed $integerValue): void { if (self::$floatSettersEnabled) { $floatValue = (float) $value; $base = (float) $integerValue; if ($floatValue === $base) { return; } $units = [ 'y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second', ]; $upper = true; foreach ($units as $property => $name) { if ($name === $unit) { $upper = false; continue; } if (!$upper && $this->$property !== 0) { throw new RuntimeException( "You cannot set $unit to a float value as $name would be overridden, ". 'set it first to 0 explicitly if you really want to erase its value' ); } } $this->add($unit, $floatValue - $base); } } private function getInnerValues(): array { return [$this->y, $this->m, $this->d, $this->h, $this->i, $this->s, $this->f, $this->invert, $this->days]; } private function checkStartAndEnd(): void { if ( $this->initialValues !== null && ($this->startDate !== null || $this->endDate !== null) && $this->initialValues !== $this->getInnerValues() ) { $this->absolute = false; $this->startDate = null; $this->endDate = null; $this->rawInterval = null; } } /** @return $this */ private function setSetting(string $setting, mixed $value): self { switch ($setting) { case 'timezoneSetting': return $value === null ? $this : $this->setTimezone($value); case 'step': $this->setStep($value); return $this; case 'localMonthsOverflow': return $value === null ? $this : $this->settings(['monthOverflow' => $value]); case 'localYearsOverflow': return $value === null ? $this : $this->settings(['yearOverflow' => $value]); case 'localStrictModeEnabled': case 'localHumanDiffOptions': case 'localToStringFormat': case 'localSerializer': case 'localMacros': case 'localGenericMacros': case 'localFormatFunction': case 'localTranslator': $this->$setting = $value; return $this; default: // Drop unknown settings return $this; } } private static function incrementUnit(DateInterval $instance, string $unit, int $value): void { if ($value === 0) { return; } // @codeCoverageIgnoreStart if (PHP_VERSION_ID !== 8_03_20) { $instance->$unit += $value; return; } // Cannot use +=, nor set to a negative value directly as it segfaults in PHP 8.3.20 self::setIntervalUnit($instance, $unit, ($instance->$unit ?? 0) + $value); // @codeCoverageIgnoreEnd } /** @codeCoverageIgnore */ private static function setIntervalUnit(DateInterval $instance, string $unit, mixed $value): void { switch ($unit) { case 'y': $instance->y = $value; break; case 'm': $instance->m = $value; break; case 'd': $instance->d = $value; break; case 'h': $instance->h = $value; break; case 'i': $instance->i = $value; break; case 's': $instance->s = $value; break; default: $instance->$unit = $value; } } }
PHP
{ "end_line": 3000, "name": "roundUnit", "signature": "public function roundUnit(string $unit, DateInterval|string|int|float $precision = 1, string $function = 'round'): static", "start_line": 2973 }
{ "class_name": "CarbonInterval", "class_signature": "class CarbonInterval implements CarbonConverterInterface, UnitValue", "namespace": "Carbon" }
instance
Carbon/src/Carbon/CarbonPeriod.php
public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotACarbonClassException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnreachableException; use Carbon\Traits\DeprecatedPeriodProperties; use Carbon\Traits\IntervalRounding; use Carbon\Traits\LocalFactory; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Throwable; // @codeCoverageIgnoreStart require PHP_VERSION < 8.2 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php' : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php'; // @codeCoverageIgnoreEnd /** * Substitution of DatePeriod with some modifications and many more features. * * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. * @method static static since($date = null, $inclusive = null) Alias for start(). * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. * @method static static until($date = null, $inclusive = null) Alias for end(). * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. * @method static static times($recurrences = null) Alias for recurrences(). * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance. * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. * @method static static push($callback, $name = null) Alias for filter(). * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance. * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. * @method static static year($years = 1) Alias for years(). * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. * @method static static month($months = 1) Alias for months(). * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. * @method static static week($weeks = 1) Alias for weeks(). * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. * @method static static dayz($days = 1) Alias for days(). * @method static static day($days = 1) Alias for days(). * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. * @method static static hour($hours = 1) Alias for hours(). * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. * @method static static minute($minutes = 1) Alias for minutes(). * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. * @method static static second($seconds = 1) Alias for seconds(). * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * * @mixin DeprecatedPeriodProperties * * @SuppressWarnings(TooManyFields) * @SuppressWarnings(CamelCasePropertyName) * @SuppressWarnings(CouplingBetweenObjects) */ class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue { use LocalFactory; use IntervalRounding; use Mixin { Mixin::mixin as baseMixin; } use Options { Options::__debugInfo as baseDebugInfo; } use ToStringFormat; /** * Built-in filter for limit by recurrences. * * @var callable */ public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; /** * Built-in filter for limit to an end. * * @var callable */ public const END_DATE_FILTER = [self::class, 'filterEndDate']; /** * Special value which can be returned by filters to end iteration. Also a filter. * * @var callable */ public const END_ITERATION = [self::class, 'endIteration']; /** * Exclude end date from iteration. * * @var int */ public const EXCLUDE_END_DATE = 8; /** * Yield CarbonImmutable instances. * * @var int */ public const IMMUTABLE = 4; /** * Number of maximum attempts before giving up on finding next valid date. * * @var int */ public const NEXT_MAX_ATTEMPTS = 1000; /** * Number of maximum attempts before giving up on finding end date. * * @var int */ public const END_MAX_ATTEMPTS = 10000; /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = Carbon::class; /** * The registered macros. */ protected static array $macros = []; /** * Date class of iteration items. */ protected string $dateClass = Carbon::class; /** * Underlying date interval instance. Always present, one day by default. */ protected ?CarbonInterval $dateInterval = null; /** * True once __construct is finished. */ protected bool $constructed = false; /** * Whether current date interval was set by default. */ protected bool $isDefaultInterval = false; /** * The filters stack. */ protected array $filters = []; /** * Period start date. Applied on rewind. Always present, now by default. */ protected ?CarbonInterface $startDate = null; /** * Period end date. For inverted interval should be before the start date. Applied via a filter. */ protected ?CarbonInterface $endDate = null; /** * Limit for number of recurrences. Applied via a filter. */ protected int|float|null $carbonRecurrences = null; /** * Iteration options. */ protected ?int $options = null; /** * Index of current date. Always sequential, even if some dates are skipped by filters. * Equal to null only before the first iteration. */ protected int $key = 0; /** * Current date. May temporarily hold unaccepted value when looking for a next valid date. * Equal to null only before the first iteration. */ protected ?CarbonInterface $carbonCurrent = null; /** * Timezone of current date. Taken from the start date. */ protected ?DateTimeZone $timezone = null; /** * The cached validation result for current date. */ protected array|string|bool|null $validationResult = null; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; public function getIterator(): Generator { $this->rewind(); while ($this->valid()) { $key = $this->key(); $value = $this->current(); yield $key => $value; $this->next(); } } /** * Make a CarbonPeriod instance from given variable if possible. */ public static function make(mixed $var): ?static { try { return static::instance($var); } catch (NotAPeriodException) { return static::create($var); } } /** * Create a new instance from a DatePeriod or CarbonPeriod object. */ public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); } /** * Create a new instance. */ public static function create(...$params): static { return static::createFromArray($params); } /** * Create a new instance from an array of parameters. */ public static function createFromArray(array $params): static { return new static(...$params); } /** * Create CarbonPeriod from ISO 8601 string. */ public static function createFromIso(string $iso, ?int $options = null): static { $params = static::parseIso8601($iso); $instance = static::createFromArray($params); $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options; $instance->handleChangedParameters(); return $instance; } public static function createFromISO8601String(string $iso, ?int $options = null): static { return self::createFromIso($iso, $options); } /** * Return whether the given interval contains non-zero value of any time unit. */ protected static function intervalHasTime(DateInterval $interval): bool { return $interval->h || $interval->i || $interval->s || $interval->f; } /** * Return whether given variable is an ISO 8601 specification. * * Note: Check is very basic, as actual validation will be done later when parsing. * We just want to ensure that variable is not any other type of valid parameter. */ protected static function isIso8601(mixed $var): bool { if (!\is_string($var)) { return false; } // Match slash but not within a timezone name. $part = '[a-z]+(?:[_-][a-z]+)*'; preg_match("#\b$part/$part\b|(/)#i", $var, $match); return isset($match[1]); } /** * Parse given ISO 8601 string into an array of arguments. * * @SuppressWarnings(ElseExpression) */ protected static function parseIso8601(string $iso): array { $result = []; $interval = null; $start = null; $end = null; $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = self::makeInterval($part)) { $interval = $part; } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); } $result[] = $parsed; } return $result; } /** * Add missing parts of the target date from the source date. */ protected static function addMissingParts(string $source, string $target): string { $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); return $count ? $result : $target; } private static function makeInterval(mixed $input): ?CarbonInterval { try { return CarbonInterval::make($input); } catch (Throwable) { return null; } } private static function makeTimezone(mixed $input): ?CarbonTimeZone { if (!\is_string($input)) { return null; } try { return CarbonTimeZone::create($input); } catch (Throwable) { return null; } } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonPeriod::macro('middle', function () { * return $this->getStartDate()->average($this->getEndDate()); * }); * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonPeriod::mixin(new class { * public function addDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->addDays($count) * )->setEndDate( * $this->getEndDate()->addDays($count) * ); * }; * } * public function subDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->subDays($count) * )->setEndDate( * $this->getEndDate()->subDays($count) * ); * }; * } * }); * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); * ``` * * @throws ReflectionException */ public static function mixin(object|string $mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Provide static proxy for instance aliases. */ public static function __callStatic(string $method, array $parameters): mixed { $date = new static(); if (static::hasMacro($method)) { return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters)); } return $date->$method(...$parameters); } /** * CarbonPeriod constructor. * * @SuppressWarnings(ElseExpression) * * @throws InvalidArgumentException */ public function __construct(...$arguments) { $raw = null; if (isset($arguments['raw'])) { $raw = $arguments['raw']; $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false; if (isset($arguments['dateClass'])) { $this->dateClass = $arguments['dateClass']; } $arguments = $raw; } // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. $argumentsCount = \count($arguments); if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { array_splice($arguments, 0, 1, static::parseIso8601($iso)); } if ($argumentsCount === 1) { if ($arguments[0] instanceof self) { $arguments = [ $arguments[0]->getStartDate(), $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(), $arguments[0]->getDateInterval(), $arguments[0]->getOptions(), ]; } elseif ($arguments[0] instanceof DatePeriod) { $arguments = [ $arguments[0]->start, $arguments[0]->end ?: ($arguments[0]->recurrences - 1), $arguments[0]->interval, $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, ]; } } if (is_a($this->dateClass, DateTimeImmutable::class, true)) { $this->options = static::IMMUTABLE; } $optionsSet = false; $originalArguments = []; $sortedArguments = []; foreach ($arguments as $argument) { $parsedDate = null; if ($argument instanceof DateTimeZone) { $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments); } elseif (!isset($sortedArguments['interval']) && ( (\is_string($argument) && preg_match( '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument, )) || $argument instanceof DateInterval || $argument instanceof Closure || $argument instanceof Unit ) && $parsedInterval = self::makeInterval($argument) ) { $sortedArguments['interval'] = $parsedInterval; } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) { $sortedArguments['start'] = $parsedDate; $originalArguments['start'] = $argument; } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { $sortedArguments['end'] = $parsedDate; $originalArguments['end'] = $argument; } elseif (!isset($sortedArguments['recurrences']) && !isset($sortedArguments['end']) && (\is_int($argument) || \is_float($argument)) && $argument >= 0 ) { $sortedArguments['recurrences'] = $argument; } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { $optionsSet = true; $sortedArguments['options'] = (((int) $this->options) | ((int) $argument)); } elseif ($parsedTimezone = self::makeTimezone($argument)) { $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($raw === null && isset($sortedArguments['start'])) { $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1); if (\is_float($end)) { $end = $end === INF ? PHP_INT_MAX : (int) round($end); } $raw = [ $sortedArguments['start'], $sortedArguments['interval'] ?? CarbonInterval::day(), $end, ]; } $this->setFromAssociativeArray($sortedArguments); if ($this->startDate === null) { $dateClass = $this->dateClass; $this->setStartDate($dateClass::now()); } if ($this->dateInterval === null) { $this->setDateInterval(CarbonInterval::day()); $this->isDefaultInterval = true; } if ($this->options === null) { $this->setOptions(0); } parent::__construct( $this->startDate, $this->dateInterval, $this->endDate ?? max(1, min(2147483639, $this->recurrences ?? 1)), $this->options, ); $this->constructed = true; } /** * Get a copy of the instance. */ public function copy(): static { return clone $this; } /** * Prepare the instance to be set (self if mutable to be mutated, * copy if immutable to generate a new instance). */ protected function copyIfImmutable(): static { return $this; } /** * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. */ protected function getGetter(string $name): ?callable { return match (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) { 'start', 'start_date' => [$this, 'getStartDate'], 'end', 'end_date' => [$this, 'getEndDate'], 'interval', 'date_interval' => [$this, 'getDateInterval'], 'recurrences' => [$this, 'getRecurrences'], 'include_start_date' => [$this, 'isStartIncluded'], 'include_end_date' => [$this, 'isEndIncluded'], 'current' => [$this, 'current'], 'locale' => [$this, 'locale'], 'tzname', 'tz_name' => fn () => match (true) { $this->timezoneSetting === null => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, $this->timezoneSetting instanceof DateTimeZone => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, default => null, }; } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function get(string $name) { $getter = $this->getGetter($name); if ($getter) { return $getter(); } throw new UnknownGetterException($name); } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function __get(string $name) { return $this->get($name); } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset(string $name): bool { return $this->getGetter($name) !== null; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Set the iteration item class. * * @param string $dateClass * * @return static */ public function setDateClass(string $dateClass) { if (!is_a($dateClass, CarbonInterface::class, true)) { throw new NotACarbonClassException($dateClass); } $self = $this->copyIfImmutable(); $self->dateClass = $dateClass; if (is_a($dateClass, Carbon::class, true)) { $self->options = $self->options & ~static::IMMUTABLE; } elseif (is_a($dateClass, CarbonImmutable::class, true)) { $self->options = $self->options | static::IMMUTABLE; } return $self; } /** * Returns iteration item date class. * * @return string */ public function getDateClass(): string { return $this->dateClass; } /** * Change the period date interval. * * @param DateInterval|Unit|string|int $interval * @param Unit|string $unit the unit of $interval if it's a number * * @throws InvalidIntervalException * * @return static */ public function setDateInterval(mixed $interval, Unit|string|null $unit = null): static { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->name; } if (!$interval = CarbonInterval::make($interval, $unit)) { throw new InvalidIntervalException('Invalid interval.'); } if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) { throw new InvalidIntervalException('Empty interval is not accepted.'); } $self = $this->copyIfImmutable(); $self->dateInterval = $interval; $self->isDefaultInterval = false; $self->handleChangedParameters(); return $self; } /** * Reset the date interval to the default value. * * Difference with simply setting interval to 1-day is that P1D will not appear when calling toIso8601String() * and also next adding to the interval won't include the default 1-day. */ public function resetDateInterval(): static { $self = $this->copyIfImmutable(); $self->setDateInterval(CarbonInterval::day()); $self->isDefaultInterval = true; return $self; } /** * Invert the period date interval. */ public function invertDateInterval(): static { return $this->setDateInterval($this->dateInterval->invert()); } /** * Set start and end date. * * @param DateTime|DateTimeInterface|string $start * @param DateTime|DateTimeInterface|string|null $end * * @return static */ public function setDates(mixed $start, mixed $end): static { return $this->setStartDate($start)->setEndDate($end); } /** * Change the period options. * * @param int|null $options * * @return static */ public function setOptions(?int $options): static { $self = $this->copyIfImmutable(); $self->options = $options ?? 0; $self->handleChangedParameters(); return $self; } /** * Get the period options. */ public function getOptions(): int { return $this->options ?? 0; } /** * Toggle given options on or off. * * @param int $options * @param bool|null $state * * @throws InvalidArgumentException * * @return static */ public function toggleOptions(int $options, ?bool $state = null): static { $self = $this->copyIfImmutable(); if ($state === null) { $state = ($this->options & $options) !== $options; } return $self->setOptions( $state ? $this->options | $options : $this->options & ~$options, ); } /** * Toggle EXCLUDE_START_DATE option. */ public function excludeStartDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_START_DATE, $state); } /** * Toggle EXCLUDE_END_DATE option. */ public function excludeEndDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_END_DATE, $state); } /** * Get the underlying date interval. */ public function getDateInterval(): CarbonInterval { return $this->dateInterval->copy(); } /** * Get start date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getStartDate(?string $rounding = null): CarbonInterface { $date = $this->startDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get end date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getEndDate(?string $rounding = null): ?CarbonInterface { if (!$this->endDate) { return null; } $date = $this->endDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get number of recurrences. */ #[ReturnTypeWillChange] public function getRecurrences(): int|float|null { return $this->carbonRecurrences; } /** * Returns true if the start date should be excluded. */ public function isStartExcluded(): bool { return ($this->options & static::EXCLUDE_START_DATE) !== 0; } /** * Returns true if the end date should be excluded. */ public function isEndExcluded(): bool { return ($this->options & static::EXCLUDE_END_DATE) !== 0; } /** * Returns true if the start date should be included. */ public function isStartIncluded(): bool { return !$this->isStartExcluded(); } /** * Returns true if the end date should be included. */ public function isEndIncluded(): bool { return !$this->isEndExcluded(); } /** * Return the start if it's included by option, else return the start + 1 period interval. */ public function getIncludedStartDate(): CarbonInterface { $start = $this->getStartDate(); if ($this->isStartExcluded()) { return $start->add($this->getDateInterval()); } return $start; } /** * Return the end if it's included by option, else return the end - 1 period interval. * Warning: if the period has no fixed end, this method will iterate the period to calculate it. */ public function getIncludedEndDate(): CarbonInterface { $end = $this->getEndDate(); if (!$end) { return $this->calculateEnd(); } if ($this->isEndExcluded()) { return $end->sub($this->getDateInterval()); } return $end; } /** * Add a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function addFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); $self->filters[] = $tuple; $self->handleChangedParameters(); return $self; } /** * Prepend a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function prependFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); array_unshift($self->filters, $tuple); $self->handleChangedParameters(); return $self; } /** * Remove a filter by instance or name. */ public function removeFilter(callable|string $filter): static { $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; $self->filters = array_values(array_filter( $this->filters, static fn ($tuple) => $tuple[$key] !== $filter, )); $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Return whether given instance or name is in the filter stack. */ public function hasFilter(callable|string $filter): bool { $key = \is_callable($filter) ? 0 : 1; foreach ($this->filters as $tuple) { if ($tuple[$key] === $filter) { return true; } } return false; } /** * Get filters stack. */ public function getFilters(): array { return $this->filters; } /** * Set filters stack. */ public function setFilters(array $filters): static { $self = $this->copyIfImmutable(); $self->filters = $filters; $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Reset filters stack. */ public function resetFilters(): static { $self = $this->copyIfImmutable(); $self->filters = []; if ($self->endDate !== null) { $self->filters[] = [static::END_DATE_FILTER, null]; } if ($self->carbonRecurrences !== null) { $self->filters[] = [static::RECURRENCES_FILTER, null]; } $self->handleChangedParameters(); return $self; } /** * Add a recurrences filter (set maximum number of recurrences). * * @throws InvalidArgumentException */ public function setRecurrences(int|float|null $recurrences): static { if ($recurrences === null) { return $this->removeFilter(static::RECURRENCES_FILTER); } if ($recurrences < 0) { throw new InvalidPeriodParameterException('Invalid number of recurrences.'); } /** @var self $self */ $self = $this->copyIfImmutable(); $self->carbonRecurrences = $recurrences === INF ? INF : (int) $recurrences; if (!$self->hasFilter(static::RECURRENCES_FILTER)) { return $self->addFilter(static::RECURRENCES_FILTER); } $self->handleChangedParameters(); return $self; } /** * Change the period start date. * * @param DateTime|DateTimeInterface|string $date * @param bool|null $inclusive * * @throws InvalidPeriodDateException * * @return static */ public function setStartDate(mixed $date, ?bool $inclusive = null): static { if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date, $this->timezone))) { throw new InvalidPeriodDateException('Invalid start date.'); } $self = $this->copyIfImmutable(); $self->startDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); } return $self; } /** * Change the period end date. * * @param DateTime|DateTimeInterface|string|null $date * @param bool|null $inclusive * * @throws \InvalidArgumentException * * @return static */ public function setEndDate(mixed $date, ?bool $inclusive = null): static { if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date, $this->timezone)) { throw new InvalidPeriodDateException('Invalid end date.'); } if (!$date) { return $this->removeFilter(static::END_DATE_FILTER); } $self = $this->copyIfImmutable(); $self->endDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); } if (!$self->hasFilter(static::END_DATE_FILTER)) { return $self->addFilter(static::END_DATE_FILTER); } $self->handleChangedParameters(); return $self; } /** * Check if the current position is valid. */ public function valid(): bool { return $this->validateCurrentDate() === true; } /** * Return the current key. */ public function key(): ?int { return $this->valid() ? $this->key : null; } /** * Return the current date. */ public function current(): ?CarbonInterface { return $this->valid() ? $this->prepareForReturn($this->carbonCurrent) : null; } /** * Move forward to the next date. * * @throws RuntimeException */ public function next(): void { if ($this->carbonCurrent === null) { $this->rewind(); } if ($this->validationResult !== static::END_ITERATION) { $this->key++; $this->incrementCurrentDateUntilValid(); } } /** * Rewind to the start date. * * Iterating over a date in the UTC timezone avoids bug during backward DST change. * * @see https://bugs.php.net/bug.php?id=72255 * @see https://bugs.php.net/bug.php?id=74274 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time * * @throws RuntimeException */ public function rewind(): void { $this->key = 0; $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate); $settings = $this->getSettings(); if ($this->hasLocalTranslator()) { $settings['locale'] = $this->getTranslatorLocale(); } $this->carbonCurrent->settings($settings); $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null; if ($this->timezone) { $this->carbonCurrent = $this->carbonCurrent->utc(); } $this->validationResult = null; if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { $this->incrementCurrentDateUntilValid(); } } /** * Skip iterations and returns iteration state (false if ended, true if still valid). * * @param int $count steps number to skip (1 by default) * * @return bool */ public function skip(int $count = 1): bool { for ($i = $count; $this->valid() && $i > 0; $i--) { $this->next(); } return $this->valid(); } /** * Format the date period as ISO 8601. */ public function toIso8601String(): string { $parts = []; if ($this->carbonRecurrences !== null) { $parts[] = 'R'.$this->carbonRecurrences; } $parts[] = $this->startDate->toIso8601String(); if (!$this->isDefaultInterval) { $parts[] = $this->dateInterval->spec(); } if ($this->endDate !== null) { $parts[] = $this->endDate->toIso8601String(); } return implode('/', $parts); } /** * Convert the date period into a string. */ public function toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if ($format instanceof Closure) { return $format($this); } $translator = ([$this->dateClass, 'getTranslator'])(); $parts = []; $format = $format ?? ( !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) ? 'Y-m-d H:i:s' : 'Y-m-d' ); if ($this->carbonRecurrences !== null) { $parts[] = $this->translate('period_recurrences', [], $this->carbonRecurrences, $translator); } $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([ 'join' => true, ])], null, $translator); $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator); if ($this->endDate !== null) { $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator); } $result = implode(' ', $parts); return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1); } /** * Format the date period as ISO 8601. */ public function spec(): string { return $this->toIso8601String(); } /** * Cast the current instance into the given class. * * @param string $className The $className::instance() method will be called to cast the current object. * * @return DatePeriod|object */ public function cast(string $className): object { if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( $this->rawDate($this->getStartDate()), $this->getDateInterval(), $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0, ); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Return native DatePeriod PHP object matching the current instance. * * @example * ``` * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod()); * ``` */ public function toDatePeriod(): DatePeriod { return $this->cast(DatePeriod::class); } /** * Return `true` if the period has no custom filter and is guaranteed to be endless. * * Note that we can't check if a period is endless as soon as it has custom filters * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in * a way we can't predict without actually iterating the period. */ public function isUnfilteredAndEndLess(): bool { foreach ($this->filters as $filter) { switch ($filter) { case [static::RECURRENCES_FILTER, null]: if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) { return false; } break; case [static::END_DATE_FILTER, null]: if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { return false; } break; default: return false; } } return true; } /** * Convert the date period into an array without changing current iteration state. * * @return CarbonInterface[] */ public function toArray(): array { if ($this->isUnfilteredAndEndLess()) { throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); } $state = [ $this->key, $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null, $this->validationResult, ]; $result = iterator_to_array($this); [$this->key, $this->carbonCurrent, $this->validationResult] = $state; return $result; } /** * Count dates in the date period. */ public function count(): int { return \count($this->toArray()); } /** * Return the first date in the date period. */ public function first(): ?CarbonInterface { if ($this->isUnfilteredAndEndLess()) { foreach ($this as $date) { $this->rewind(); return $date; } return null; } return ($this->toArray() ?: [])[0] ?? null; } /** * Return the last date in the date period. */ public function last(): ?CarbonInterface { $array = $this->toArray(); return $array ? $array[\count($array) - 1] : null; } /** * Convert the date period into a string. */ public function __toString(): string { return $this->toString(); } /** * Add aliases for setters. * * CarbonPeriod::days(3)->hours(5)->invert() * ->sinceNow()->until('2010-01-10') * ->filter(...) * ->count() * * Note: We use magic method to let static and instance aliases with the same names. */ public function __call(string $method, array $parameters): mixed { if (static::hasMacro($method)) { return static::bindMacroContext($this, fn () => $this->callMacro($method, $parameters)); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } $count = \count($parameters); switch ($method) { case 'start': case 'since': if ($count === 0) { return $this->getStartDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setStartDate(...$parameters); case 'sinceNow': return $this->setStartDate(new Carbon(), ...$parameters); case 'end': case 'until': if ($count === 0) { return $this->getEndDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setEndDate(...$parameters); case 'untilNow': return $this->setEndDate(new Carbon(), ...$parameters); case 'dates': case 'between': self::setDefaultParameters($parameters, [ [0, 'start', null], [1, 'end', null], ]); return $this->setDates(...$parameters); case 'recurrences': case 'times': if ($count === 0) { return $this->getRecurrences(); } self::setDefaultParameters($parameters, [ [0, 'recurrences', null], ]); return $this->setRecurrences(...$parameters); case 'options': if ($count === 0) { return $this->getOptions(); } self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->setOptions(...$parameters); case 'toggle': self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->toggleOptions(...$parameters); case 'filter': case 'push': return $this->addFilter(...$parameters); case 'prepend': return $this->prependFilter(...$parameters); case 'filters': if ($count === 0) { return $this->getFilters(); } self::setDefaultParameters($parameters, [ [0, 'filters', []], ]); return $this->setFilters(...$parameters); case 'interval': case 'each': case 'every': case 'step': case 'stepBy': if ($count === 0) { return $this->getDateInterval(); } return $this->setDateInterval(...$parameters); case 'invert': return $this->invertDateInterval(); case 'years': case 'year': case 'months': case 'month': case 'weeks': case 'week': case 'days': case 'dayz': case 'day': case 'hours': case 'hour': case 'minutes': case 'minute': case 'seconds': case 'second': case 'milliseconds': case 'millisecond': case 'microseconds': case 'microsecond': return $this->setDateInterval(( // Override default P1D when instantiating via fluent setters. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] )(...$parameters)); } $dateClass = $this->dateClass; if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { throw new UnknownMethodException($method); } return $this; } /** * Set the instance's timezone from a string or object and apply it to start/end. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->setTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->setTimezone($timezone)); } return $self; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } return $self; } /** * Returns the end is set, else calculated from start and recurrences. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. * * @return CarbonInterface */ public function calculateEnd(?string $rounding = null): CarbonInterface { if ($end = $this->getEndDate($rounding)) { return $end; } if ($this->dateInterval->isEmpty()) { return $this->getStartDate($rounding); } $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); if ($date && $rounding) { $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); } return $date; } private function getEndFromRecurrences(): ?CarbonInterface { if ($this->carbonRecurrences === null) { throw new UnreachableException( "Could not calculate period end without either explicit end or recurrences.\n". "If you're looking for a forever-period, use ->setRecurrences(INF).", ); } if ($this->carbonRecurrences === INF) { $start = $this->getStartDate(); return $start < $start->avoidMutation()->add($this->getDateInterval()) ? CarbonImmutable::endOfTime() : CarbonImmutable::startOfTime(); } if ($this->filters === [[static::RECURRENCES_FILTER, null]]) { return $this->getStartDate()->avoidMutation()->add( $this->getDateInterval()->times( $this->carbonRecurrences - ($this->isStartExcluded() ? 0 : 1), ), ); } return null; } private function iterateUntilEnd(): ?CarbonInterface { $attempts = 0; $date = null; foreach ($this as $date) { if (++$attempts > static::END_MAX_ATTEMPTS) { throw new UnreachableException( 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.', ); } } return $date; } /** * Returns true if the current period overlaps the given one (if 1 parameter passed) * or the period between 2 dates (if 2 parameters passed). * * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd * * @return bool */ public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool { $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; if (!($range instanceof self)) { $range = static::create($range); } [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); return $end > $rangeStart && $rangeEnd > $start; } /** * Execute a given function on each date of the period. * * @example * ``` * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) { * echo $date->diffInDays('2020-12-25')." days before Christmas!\n"; * }); * ``` */ public function forEach(callable $callback): void { foreach ($this as $date) { $callback($date); } } /** * Execute a given function on each date of the period and yield the result of this function. * * @example * ``` * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24'); * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) { * return $date->diffInDays('2020-12-25').' days before Christmas!'; * }))); * ``` */ public function map(callable $callback): Generator { foreach ($this as $date) { yield $callback($date); } } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. * * @see equalTo() */ public function eq(mixed $period): bool { return $this->equalTo($period); } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. */ public function equalTo(mixed $period): bool { if (!($period instanceof self)) { $period = self::make($period); } $end = $this->getEndDate(); return $period !== null && $this->getDateInterval()->eq($period->getDateInterval()) && $this->getStartDate()->eq($period->getStartDate()) && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. * * @see notEqualTo() */ public function ne(mixed $period): bool { return $this->notEqualTo($period); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. */ public function notEqualTo(mixed $period): bool { return !$this->eq($period); } /** * Determines if the start date is before another given date. * (Rather start/end are included by options is ignored.) */ public function startsBefore(mixed $date = null): bool { return $this->getStartDate()->lessThan($this->resolveCarbon($date)); } /** * Determines if the start date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsBeforeOrAt(mixed $date = null): bool { return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is after another given date. * (Rather start/end are included by options is ignored.) */ public function startsAfter(mixed $date = null): bool { return $this->getStartDate()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the start date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAfterOrAt(mixed $date = null): bool { return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAt(mixed $date = null): bool { return $this->getStartDate()->equalTo($this->resolveCarbon($date)); } /** * Determines if the end date is before another given date. * (Rather start/end are included by options is ignored.) */ public function endsBefore(mixed $date = null): bool { return $this->calculateEnd()->lessThan($this->resolveCarbon($date)); } /** * Determines if the end date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsBeforeOrAt(mixed $date = null): bool { return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is after another given date. * (Rather start/end are included by options is ignored.) */ public function endsAfter(mixed $date = null): bool { return $this->calculateEnd()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the end date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAfterOrAt(mixed $date = null): bool { return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAt(mixed $date = null): bool { return $this->calculateEnd()->equalTo($this->resolveCarbon($date)); } /** * Return true if start date is now or later. * (Rather start/end are included by options is ignored.) */ public function isStarted(): bool { return $this->startsBeforeOrAt(); } /** * Return true if end date is now or later. * (Rather start/end are included by options is ignored.) */ public function isEnded(): bool { return $this->endsBeforeOrAt(); } /** * Return true if now is between start date (included) and end date (excluded). * (Rather start/end are included by options is ignored.) */ public function isInProgress(): bool { return $this->isStarted() && !$this->isEnded(); } /** * Round the current instance at the given unit with given precision if specified and the given function. */ public function roundUnit( string $unit, DateInterval|float|int|string|null $precision = 1, callable|string $function = 'round', ): static { $self = $this->copyIfImmutable(); $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); if ($self->endDate) { $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); } /** * Truncate the current instance at the given unit with given precision if specified. */ public function floorUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. */ public function ceilUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function round( DateInterval|float|int|string|null $precision = null, callable|string $function = 'round', ): static { return $this->roundWith( $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(), $function ); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function floor(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified (else period interval is used). */ public function ceil(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'ceil'); } /** * Specify data which should be serialized to JSON. * * @link https://php.net/manual/en/jsonserializable.jsonserialize.php * * @return CarbonInterface[] */ public function jsonSerialize(): array { return $this->toArray(); } /** * Return true if the given date is between start and end. */ public function contains(mixed $date = null): bool { $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : ''); $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : ''); return $this->$startMethod($date) && $this->$endMethod($date); } /** * Return true if the current period follows a given other period (with no overlap). * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31] * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function follows(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval())); } /** * Return true if the given other period follows the current one (with no overlap). * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12] * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function isFollowedBy(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $period->follows($this); } /** * Return true if the given period either follows or is followed by the current one. * * @see follows() * @see isFollowedBy() */ public function isConsecutiveWith(mixed $period, mixed ...$arguments): bool { return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments); } public function __debugInfo(): array { $info = $this->baseDebugInfo(); unset( $info['start'], $info['end'], $info['interval'], $info['include_start_date'], $info['include_end_date'], $info['constructed'], $info["\0*\0constructed"], ); return $info; } public function __unserialize(array $data): void { try { $values = array_combine( array_map( static fn (string $key): string => preg_replace('/^\0\*\0/', '', $key), array_keys($data), ), $data, ); $this->initializeSerialization($values); foreach ($values as $key => $value) { if ($value === null) { continue; } $property = match ($key) { 'tzName' => $this->setTimezone(...), 'options' => $this->setOptions(...), 'recurrences' => $this->setRecurrences(...), 'current' => function (mixed $current): void { if (!($current instanceof CarbonInterface)) { $current = $this->resolveCarbon($current); } $this->carbonCurrent = $current; }, 'start' => 'startDate', 'interval' => $this->setDateInterval(...), 'end' => 'endDate', 'key' => null, 'include_start_date' => function (bool $included): void { $this->excludeStartDate(!$included); }, 'include_end_date' => function (bool $included): void { $this->excludeEndDate(!$included); }, default => $key, }; if ($property === null) { continue; } if (\is_callable($property)) { $property($value); continue; } if ($value instanceof DateTimeInterface && !($value instanceof CarbonInterface)) { $value = ($value instanceof DateTime) ? Carbon::instance($value) : CarbonImmutable::instance($value); } try { $this->$property = $value; } catch (Throwable) { // Must be ignored for backward-compatibility } } if (\array_key_exists('carbonRecurrences', $values)) { $this->carbonRecurrences = $values['carbonRecurrences']; } elseif (((int) ($values['recurrences'] ?? 0)) <= 1 && $this->endDate !== null) { $this->carbonRecurrences = null; } } catch (Throwable $e) { // @codeCoverageIgnoreStart if (!method_exists(parent::class, '__unserialize')) { throw $e; } parent::__unserialize($data); // @codeCoverageIgnoreEnd } } /** * Update properties after removing built-in filters. */ protected function updateInternalState(): void { if (!$this->hasFilter(static::END_DATE_FILTER)) { $this->endDate = null; } if (!$this->hasFilter(static::RECURRENCES_FILTER)) { $this->carbonRecurrences = null; } } /** * Create a filter tuple from raw parameters. * * Will create an automatic filter callback for one of Carbon's is* methods. */ protected function createFilterTuple(array $parameters): array { $method = array_shift($parameters); if (!$this->isCarbonPredicateMethod($method)) { return [$method, array_shift($parameters)]; } return [static fn ($date) => ([$date, $method])(...$parameters), $method]; } /** * Return whether given callable is a string pointing to one of Carbon's is* methods * and should be automatically converted to a filter callback. */ protected function isCarbonPredicateMethod(callable|string $callable): bool { return \is_string($callable) && str_starts_with($callable, 'is') && (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable)); } /** * Recurrences filter callback (limits number of recurrences). * * @SuppressWarnings(UnusedFormalParameter) */ protected function filterRecurrences(CarbonInterface $current, int $key): bool|callable { if ($key < $this->carbonRecurrences) { return true; } return static::END_ITERATION; } /** * End date filter callback. * * @return bool|static::END_ITERATION */ protected function filterEndDate(CarbonInterface $current): bool|callable { if (!$this->isEndExcluded() && $current == $this->endDate) { return true; } if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) { return true; } return static::END_ITERATION; } /** * End iteration filter callback. * * @return static::END_ITERATION */ protected function endIteration(): callable { return static::END_ITERATION; } /** * Handle change of the parameters. */ protected function handleChangedParameters(): void { if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { $this->dateClass = CarbonImmutable::class; } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { $this->dateClass = Carbon::class; } $this->validationResult = null; } /** * Validate current date and stop iteration when necessary. * * Returns true when current date is valid, false if it is not, or static::END_ITERATION * when iteration should be stopped. * * @return bool|static::END_ITERATION */ protected function validateCurrentDate(): bool|callable { if ($this->carbonCurrent === null) { $this->rewind(); } // Check after the first rewind to avoid repeating the initial validation. return $this->validationResult ?? ($this->validationResult = $this->checkFilters()); } /** * Check whether current value and key pass all the filters. * * @return bool|static::END_ITERATION */ protected function checkFilters(): bool|callable { $current = $this->prepareForReturn($this->carbonCurrent); foreach ($this->filters as $tuple) { $result = \call_user_func($tuple[0], $current->avoidMutation(), $this->key, $this); if ($result === static::END_ITERATION) { return static::END_ITERATION; } if (!$result) { return false; } } return true; } /** * Prepare given date to be returned to the external logic. * * @param CarbonInterface $date * * @return CarbonInterface */ protected function prepareForReturn(CarbonInterface $date) { $date = ([$this->dateClass, 'make'])($date); if ($this->timezone) { return $date->setTimezone($this->timezone); } return $date; } /** * Keep incrementing the current date until a valid date is found or the iteration is ended. * * @throws RuntimeException */ protected function incrementCurrentDateUntilValid(): void { $attempts = 0; do { $this->carbonCurrent = $this->carbonCurrent->add($this->dateInterval); $this->validationResult = null; if (++$attempts > static::NEXT_MAX_ATTEMPTS) { throw new UnreachableException('Could not find next valid date.'); } } while ($this->validateCurrentDate() === false); } /** * Call given macro. */ protected function callMacro(string $name, array $parameters): mixed { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date * * @return \Carbon\CarbonInterface */ protected function resolveCarbon($date = null) { return $this->getStartDate()->nowWithSameTz()->carbonize($date); } /** * Resolve passed arguments or DatePeriod to a CarbonPeriod object. */ protected function resolveCarbonPeriod(mixed $period, mixed ...$arguments): self { if ($period instanceof self) { return $period; } return $period instanceof DatePeriod ? static::instance($period) : static::create($period, ...$arguments); } private function orderCouple($first, $second): array { return $first > $second ? [$second, $first] : [$first, $second]; } private function makeDateTime($value): ?DateTimeInterface { if ($value instanceof DateTimeInterface) { return $value; } if ($value instanceof WeekDay || $value instanceof Month) { $dateClass = $this->dateClass; return new $dateClass($value, $this->timezoneSetting); } if (\is_string($value)) { $value = trim($value); if (!preg_match('/^P[\dT]/', $value) && !preg_match('/^R\d/', $value) && preg_match('/[a-z\d]/i', $value) ) { $dateClass = $this->dateClass; return $dateClass::parse($value, $this->timezoneSetting); } } return null; } private function isInfiniteDate($date): bool { return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); } private function rawDate($date): ?DateTimeInterface { if ($date === false || $date === null) { return null; } if ($date instanceof CarbonInterface) { return $date->isMutable() ? $date->toDateTime() : $date->toDateTimeImmutable(); } if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { return $date; } $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); } private static function setDefaultParameters(array &$parameters, array $defaults): void { foreach ($defaults as [$index, $name, $value]) { if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { $parameters[$index] = $value; } } } private function setFromAssociativeArray(array $parameters): void { if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['end'])) { $this->setEndDate($parameters['end']); } if (isset($parameters['recurrences'])) { $this->setRecurrences($parameters['recurrences']); } if (isset($parameters['interval'])) { $this->setDateInterval($parameters['interval']); } if (isset($parameters['options'])) { $this->setOptions($parameters['options']); } } private function configureTimezone(DateTimeZone $timezone, array $sortedArguments, array $originalArguments): array { $this->setTimezone($timezone); if (\is_string($originalArguments['start'] ?? null)) { $sortedArguments['start'] = $this->makeDateTime($originalArguments['start']); } if (\is_string($originalArguments['end'] ?? null)) { $sortedArguments['end'] = $this->makeDateTime($originalArguments['end']); } return $sortedArguments; } private function initializeSerialization(array $values): void { $serializationBase = [ 'start' => $values['start'] ?? $values['startDate'] ?? null, 'current' => $values['current'] ?? $values['carbonCurrent'] ?? null, 'end' => $values['end'] ?? $values['endDate'] ?? null, 'interval' => $values['interval'] ?? $values['dateInterval'] ?? null, 'recurrences' => max(1, (int) ($values['recurrences'] ?? $values['carbonRecurrences'] ?? 1)), 'include_start_date' => $values['include_start_date'] ?? true, 'include_end_date' => $values['include_end_date'] ?? false, ]; foreach (['start', 'current', 'end'] as $dateProperty) { if ($serializationBase[$dateProperty] instanceof Carbon) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTime(); } elseif ($serializationBase[$dateProperty] instanceof CarbonInterface) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTimeImmutable(); } } if ($serializationBase['interval'] instanceof CarbonInterval) { $serializationBase['interval'] = $serializationBase['interval']->toDateInterval(); } // @codeCoverageIgnoreStart if (method_exists(parent::class, '__unserialize')) { parent::__unserialize($serializationBase); return; } $excludeStart = !($values['include_start_date'] ?? true); $includeEnd = $values['include_end_date'] ?? true; parent::__construct( $serializationBase['start'], $serializationBase['interval'], $serializationBase['end'] ?? $serializationBase['recurrences'], ($excludeStart ? self::EXCLUDE_START_DATE : 0) | ($includeEnd && \defined('DatePeriod::INCLUDE_END_DATE') ? self::INCLUDE_END_DATE : 0), ); // @codeCoverageIgnoreEnd } }
PHP
{ "end_line": 391, "name": "instance", "signature": "public static function instance(mixed $period): static", "start_line": 358 }
{ "class_name": "CarbonPeriod", "class_signature": "class CarbonPeriod implements Countable, JsonSerializable, UnitValue", "namespace": "Carbon" }
toggleOptions
Carbon/src/Carbon/CarbonPeriod.php
public function toggleOptions(int $options, ?bool $state = null): static { $self = $this->copyIfImmutable(); if ($state === null) { $state = ($this->options & $options) !== $options; } return $self->setOptions( $state ? $this->options | $options : $this->options & ~$options, ); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotACarbonClassException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnreachableException; use Carbon\Traits\DeprecatedPeriodProperties; use Carbon\Traits\IntervalRounding; use Carbon\Traits\LocalFactory; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Throwable; // @codeCoverageIgnoreStart require PHP_VERSION < 8.2 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php' : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php'; // @codeCoverageIgnoreEnd /** * Substitution of DatePeriod with some modifications and many more features. * * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. * @method static static since($date = null, $inclusive = null) Alias for start(). * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. * @method static static until($date = null, $inclusive = null) Alias for end(). * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. * @method static static times($recurrences = null) Alias for recurrences(). * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance. * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. * @method static static push($callback, $name = null) Alias for filter(). * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance. * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. * @method static static year($years = 1) Alias for years(). * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. * @method static static month($months = 1) Alias for months(). * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. * @method static static week($weeks = 1) Alias for weeks(). * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. * @method static static dayz($days = 1) Alias for days(). * @method static static day($days = 1) Alias for days(). * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. * @method static static hour($hours = 1) Alias for hours(). * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. * @method static static minute($minutes = 1) Alias for minutes(). * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. * @method static static second($seconds = 1) Alias for seconds(). * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * * @mixin DeprecatedPeriodProperties * * @SuppressWarnings(TooManyFields) * @SuppressWarnings(CamelCasePropertyName) * @SuppressWarnings(CouplingBetweenObjects) */ class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue { use LocalFactory; use IntervalRounding; use Mixin { Mixin::mixin as baseMixin; } use Options { Options::__debugInfo as baseDebugInfo; } use ToStringFormat; /** * Built-in filter for limit by recurrences. * * @var callable */ public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; /** * Built-in filter for limit to an end. * * @var callable */ public const END_DATE_FILTER = [self::class, 'filterEndDate']; /** * Special value which can be returned by filters to end iteration. Also a filter. * * @var callable */ public const END_ITERATION = [self::class, 'endIteration']; /** * Exclude end date from iteration. * * @var int */ public const EXCLUDE_END_DATE = 8; /** * Yield CarbonImmutable instances. * * @var int */ public const IMMUTABLE = 4; /** * Number of maximum attempts before giving up on finding next valid date. * * @var int */ public const NEXT_MAX_ATTEMPTS = 1000; /** * Number of maximum attempts before giving up on finding end date. * * @var int */ public const END_MAX_ATTEMPTS = 10000; /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = Carbon::class; /** * The registered macros. */ protected static array $macros = []; /** * Date class of iteration items. */ protected string $dateClass = Carbon::class; /** * Underlying date interval instance. Always present, one day by default. */ protected ?CarbonInterval $dateInterval = null; /** * True once __construct is finished. */ protected bool $constructed = false; /** * Whether current date interval was set by default. */ protected bool $isDefaultInterval = false; /** * The filters stack. */ protected array $filters = []; /** * Period start date. Applied on rewind. Always present, now by default. */ protected ?CarbonInterface $startDate = null; /** * Period end date. For inverted interval should be before the start date. Applied via a filter. */ protected ?CarbonInterface $endDate = null; /** * Limit for number of recurrences. Applied via a filter. */ protected int|float|null $carbonRecurrences = null; /** * Iteration options. */ protected ?int $options = null; /** * Index of current date. Always sequential, even if some dates are skipped by filters. * Equal to null only before the first iteration. */ protected int $key = 0; /** * Current date. May temporarily hold unaccepted value when looking for a next valid date. * Equal to null only before the first iteration. */ protected ?CarbonInterface $carbonCurrent = null; /** * Timezone of current date. Taken from the start date. */ protected ?DateTimeZone $timezone = null; /** * The cached validation result for current date. */ protected array|string|bool|null $validationResult = null; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; public function getIterator(): Generator { $this->rewind(); while ($this->valid()) { $key = $this->key(); $value = $this->current(); yield $key => $value; $this->next(); } } /** * Make a CarbonPeriod instance from given variable if possible. */ public static function make(mixed $var): ?static { try { return static::instance($var); } catch (NotAPeriodException) { return static::create($var); } } /** * Create a new instance from a DatePeriod or CarbonPeriod object. */ public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); } /** * Create a new instance. */ public static function create(...$params): static { return static::createFromArray($params); } /** * Create a new instance from an array of parameters. */ public static function createFromArray(array $params): static { return new static(...$params); } /** * Create CarbonPeriod from ISO 8601 string. */ public static function createFromIso(string $iso, ?int $options = null): static { $params = static::parseIso8601($iso); $instance = static::createFromArray($params); $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options; $instance->handleChangedParameters(); return $instance; } public static function createFromISO8601String(string $iso, ?int $options = null): static { return self::createFromIso($iso, $options); } /** * Return whether the given interval contains non-zero value of any time unit. */ protected static function intervalHasTime(DateInterval $interval): bool { return $interval->h || $interval->i || $interval->s || $interval->f; } /** * Return whether given variable is an ISO 8601 specification. * * Note: Check is very basic, as actual validation will be done later when parsing. * We just want to ensure that variable is not any other type of valid parameter. */ protected static function isIso8601(mixed $var): bool { if (!\is_string($var)) { return false; } // Match slash but not within a timezone name. $part = '[a-z]+(?:[_-][a-z]+)*'; preg_match("#\b$part/$part\b|(/)#i", $var, $match); return isset($match[1]); } /** * Parse given ISO 8601 string into an array of arguments. * * @SuppressWarnings(ElseExpression) */ protected static function parseIso8601(string $iso): array { $result = []; $interval = null; $start = null; $end = null; $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = self::makeInterval($part)) { $interval = $part; } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); } $result[] = $parsed; } return $result; } /** * Add missing parts of the target date from the source date. */ protected static function addMissingParts(string $source, string $target): string { $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); return $count ? $result : $target; } private static function makeInterval(mixed $input): ?CarbonInterval { try { return CarbonInterval::make($input); } catch (Throwable) { return null; } } private static function makeTimezone(mixed $input): ?CarbonTimeZone { if (!\is_string($input)) { return null; } try { return CarbonTimeZone::create($input); } catch (Throwable) { return null; } } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonPeriod::macro('middle', function () { * return $this->getStartDate()->average($this->getEndDate()); * }); * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonPeriod::mixin(new class { * public function addDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->addDays($count) * )->setEndDate( * $this->getEndDate()->addDays($count) * ); * }; * } * public function subDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->subDays($count) * )->setEndDate( * $this->getEndDate()->subDays($count) * ); * }; * } * }); * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); * ``` * * @throws ReflectionException */ public static function mixin(object|string $mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Provide static proxy for instance aliases. */ public static function __callStatic(string $method, array $parameters): mixed { $date = new static(); if (static::hasMacro($method)) { return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters)); } return $date->$method(...$parameters); } /** * CarbonPeriod constructor. * * @SuppressWarnings(ElseExpression) * * @throws InvalidArgumentException */ public function __construct(...$arguments) { $raw = null; if (isset($arguments['raw'])) { $raw = $arguments['raw']; $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false; if (isset($arguments['dateClass'])) { $this->dateClass = $arguments['dateClass']; } $arguments = $raw; } // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. $argumentsCount = \count($arguments); if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { array_splice($arguments, 0, 1, static::parseIso8601($iso)); } if ($argumentsCount === 1) { if ($arguments[0] instanceof self) { $arguments = [ $arguments[0]->getStartDate(), $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(), $arguments[0]->getDateInterval(), $arguments[0]->getOptions(), ]; } elseif ($arguments[0] instanceof DatePeriod) { $arguments = [ $arguments[0]->start, $arguments[0]->end ?: ($arguments[0]->recurrences - 1), $arguments[0]->interval, $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, ]; } } if (is_a($this->dateClass, DateTimeImmutable::class, true)) { $this->options = static::IMMUTABLE; } $optionsSet = false; $originalArguments = []; $sortedArguments = []; foreach ($arguments as $argument) { $parsedDate = null; if ($argument instanceof DateTimeZone) { $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments); } elseif (!isset($sortedArguments['interval']) && ( (\is_string($argument) && preg_match( '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument, )) || $argument instanceof DateInterval || $argument instanceof Closure || $argument instanceof Unit ) && $parsedInterval = self::makeInterval($argument) ) { $sortedArguments['interval'] = $parsedInterval; } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) { $sortedArguments['start'] = $parsedDate; $originalArguments['start'] = $argument; } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { $sortedArguments['end'] = $parsedDate; $originalArguments['end'] = $argument; } elseif (!isset($sortedArguments['recurrences']) && !isset($sortedArguments['end']) && (\is_int($argument) || \is_float($argument)) && $argument >= 0 ) { $sortedArguments['recurrences'] = $argument; } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { $optionsSet = true; $sortedArguments['options'] = (((int) $this->options) | ((int) $argument)); } elseif ($parsedTimezone = self::makeTimezone($argument)) { $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($raw === null && isset($sortedArguments['start'])) { $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1); if (\is_float($end)) { $end = $end === INF ? PHP_INT_MAX : (int) round($end); } $raw = [ $sortedArguments['start'], $sortedArguments['interval'] ?? CarbonInterval::day(), $end, ]; } $this->setFromAssociativeArray($sortedArguments); if ($this->startDate === null) { $dateClass = $this->dateClass; $this->setStartDate($dateClass::now()); } if ($this->dateInterval === null) { $this->setDateInterval(CarbonInterval::day()); $this->isDefaultInterval = true; } if ($this->options === null) { $this->setOptions(0); } parent::__construct( $this->startDate, $this->dateInterval, $this->endDate ?? max(1, min(2147483639, $this->recurrences ?? 1)), $this->options, ); $this->constructed = true; } /** * Get a copy of the instance. */ public function copy(): static { return clone $this; } /** * Prepare the instance to be set (self if mutable to be mutated, * copy if immutable to generate a new instance). */ protected function copyIfImmutable(): static { return $this; } /** * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. */ protected function getGetter(string $name): ?callable { return match (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) { 'start', 'start_date' => [$this, 'getStartDate'], 'end', 'end_date' => [$this, 'getEndDate'], 'interval', 'date_interval' => [$this, 'getDateInterval'], 'recurrences' => [$this, 'getRecurrences'], 'include_start_date' => [$this, 'isStartIncluded'], 'include_end_date' => [$this, 'isEndIncluded'], 'current' => [$this, 'current'], 'locale' => [$this, 'locale'], 'tzname', 'tz_name' => fn () => match (true) { $this->timezoneSetting === null => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, $this->timezoneSetting instanceof DateTimeZone => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, default => null, }; } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function get(string $name) { $getter = $this->getGetter($name); if ($getter) { return $getter(); } throw new UnknownGetterException($name); } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function __get(string $name) { return $this->get($name); } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset(string $name): bool { return $this->getGetter($name) !== null; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Set the iteration item class. * * @param string $dateClass * * @return static */ public function setDateClass(string $dateClass) { if (!is_a($dateClass, CarbonInterface::class, true)) { throw new NotACarbonClassException($dateClass); } $self = $this->copyIfImmutable(); $self->dateClass = $dateClass; if (is_a($dateClass, Carbon::class, true)) { $self->options = $self->options & ~static::IMMUTABLE; } elseif (is_a($dateClass, CarbonImmutable::class, true)) { $self->options = $self->options | static::IMMUTABLE; } return $self; } /** * Returns iteration item date class. * * @return string */ public function getDateClass(): string { return $this->dateClass; } /** * Change the period date interval. * * @param DateInterval|Unit|string|int $interval * @param Unit|string $unit the unit of $interval if it's a number * * @throws InvalidIntervalException * * @return static */ public function setDateInterval(mixed $interval, Unit|string|null $unit = null): static { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->name; } if (!$interval = CarbonInterval::make($interval, $unit)) { throw new InvalidIntervalException('Invalid interval.'); } if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) { throw new InvalidIntervalException('Empty interval is not accepted.'); } $self = $this->copyIfImmutable(); $self->dateInterval = $interval; $self->isDefaultInterval = false; $self->handleChangedParameters(); return $self; } /** * Reset the date interval to the default value. * * Difference with simply setting interval to 1-day is that P1D will not appear when calling toIso8601String() * and also next adding to the interval won't include the default 1-day. */ public function resetDateInterval(): static { $self = $this->copyIfImmutable(); $self->setDateInterval(CarbonInterval::day()); $self->isDefaultInterval = true; return $self; } /** * Invert the period date interval. */ public function invertDateInterval(): static { return $this->setDateInterval($this->dateInterval->invert()); } /** * Set start and end date. * * @param DateTime|DateTimeInterface|string $start * @param DateTime|DateTimeInterface|string|null $end * * @return static */ public function setDates(mixed $start, mixed $end): static { return $this->setStartDate($start)->setEndDate($end); } /** * Change the period options. * * @param int|null $options * * @return static */ public function setOptions(?int $options): static { $self = $this->copyIfImmutable(); $self->options = $options ?? 0; $self->handleChangedParameters(); return $self; } /** * Get the period options. */ public function getOptions(): int { return $this->options ?? 0; } /** * Toggle given options on or off. * * @param int $options * @param bool|null $state * * @throws InvalidArgumentException * * @return static */ public function toggleOptions(int $options, ?bool $state = null): static { $self = $this->copyIfImmutable(); if ($state === null) { $state = ($this->options & $options) !== $options; } return $self->setOptions( $state ? $this->options | $options : $this->options & ~$options, ); } /** * Toggle EXCLUDE_START_DATE option. */ public function excludeStartDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_START_DATE, $state); } /** * Toggle EXCLUDE_END_DATE option. */ public function excludeEndDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_END_DATE, $state); } /** * Get the underlying date interval. */ public function getDateInterval(): CarbonInterval { return $this->dateInterval->copy(); } /** * Get start date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getStartDate(?string $rounding = null): CarbonInterface { $date = $this->startDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get end date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getEndDate(?string $rounding = null): ?CarbonInterface { if (!$this->endDate) { return null; } $date = $this->endDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get number of recurrences. */ #[ReturnTypeWillChange] public function getRecurrences(): int|float|null { return $this->carbonRecurrences; } /** * Returns true if the start date should be excluded. */ public function isStartExcluded(): bool { return ($this->options & static::EXCLUDE_START_DATE) !== 0; } /** * Returns true if the end date should be excluded. */ public function isEndExcluded(): bool { return ($this->options & static::EXCLUDE_END_DATE) !== 0; } /** * Returns true if the start date should be included. */ public function isStartIncluded(): bool { return !$this->isStartExcluded(); } /** * Returns true if the end date should be included. */ public function isEndIncluded(): bool { return !$this->isEndExcluded(); } /** * Return the start if it's included by option, else return the start + 1 period interval. */ public function getIncludedStartDate(): CarbonInterface { $start = $this->getStartDate(); if ($this->isStartExcluded()) { return $start->add($this->getDateInterval()); } return $start; } /** * Return the end if it's included by option, else return the end - 1 period interval. * Warning: if the period has no fixed end, this method will iterate the period to calculate it. */ public function getIncludedEndDate(): CarbonInterface { $end = $this->getEndDate(); if (!$end) { return $this->calculateEnd(); } if ($this->isEndExcluded()) { return $end->sub($this->getDateInterval()); } return $end; } /** * Add a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function addFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); $self->filters[] = $tuple; $self->handleChangedParameters(); return $self; } /** * Prepend a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function prependFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); array_unshift($self->filters, $tuple); $self->handleChangedParameters(); return $self; } /** * Remove a filter by instance or name. */ public function removeFilter(callable|string $filter): static { $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; $self->filters = array_values(array_filter( $this->filters, static fn ($tuple) => $tuple[$key] !== $filter, )); $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Return whether given instance or name is in the filter stack. */ public function hasFilter(callable|string $filter): bool { $key = \is_callable($filter) ? 0 : 1; foreach ($this->filters as $tuple) { if ($tuple[$key] === $filter) { return true; } } return false; } /** * Get filters stack. */ public function getFilters(): array { return $this->filters; } /** * Set filters stack. */ public function setFilters(array $filters): static { $self = $this->copyIfImmutable(); $self->filters = $filters; $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Reset filters stack. */ public function resetFilters(): static { $self = $this->copyIfImmutable(); $self->filters = []; if ($self->endDate !== null) { $self->filters[] = [static::END_DATE_FILTER, null]; } if ($self->carbonRecurrences !== null) { $self->filters[] = [static::RECURRENCES_FILTER, null]; } $self->handleChangedParameters(); return $self; } /** * Add a recurrences filter (set maximum number of recurrences). * * @throws InvalidArgumentException */ public function setRecurrences(int|float|null $recurrences): static { if ($recurrences === null) { return $this->removeFilter(static::RECURRENCES_FILTER); } if ($recurrences < 0) { throw new InvalidPeriodParameterException('Invalid number of recurrences.'); } /** @var self $self */ $self = $this->copyIfImmutable(); $self->carbonRecurrences = $recurrences === INF ? INF : (int) $recurrences; if (!$self->hasFilter(static::RECURRENCES_FILTER)) { return $self->addFilter(static::RECURRENCES_FILTER); } $self->handleChangedParameters(); return $self; } /** * Change the period start date. * * @param DateTime|DateTimeInterface|string $date * @param bool|null $inclusive * * @throws InvalidPeriodDateException * * @return static */ public function setStartDate(mixed $date, ?bool $inclusive = null): static { if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date, $this->timezone))) { throw new InvalidPeriodDateException('Invalid start date.'); } $self = $this->copyIfImmutable(); $self->startDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); } return $self; } /** * Change the period end date. * * @param DateTime|DateTimeInterface|string|null $date * @param bool|null $inclusive * * @throws \InvalidArgumentException * * @return static */ public function setEndDate(mixed $date, ?bool $inclusive = null): static { if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date, $this->timezone)) { throw new InvalidPeriodDateException('Invalid end date.'); } if (!$date) { return $this->removeFilter(static::END_DATE_FILTER); } $self = $this->copyIfImmutable(); $self->endDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); } if (!$self->hasFilter(static::END_DATE_FILTER)) { return $self->addFilter(static::END_DATE_FILTER); } $self->handleChangedParameters(); return $self; } /** * Check if the current position is valid. */ public function valid(): bool { return $this->validateCurrentDate() === true; } /** * Return the current key. */ public function key(): ?int { return $this->valid() ? $this->key : null; } /** * Return the current date. */ public function current(): ?CarbonInterface { return $this->valid() ? $this->prepareForReturn($this->carbonCurrent) : null; } /** * Move forward to the next date. * * @throws RuntimeException */ public function next(): void { if ($this->carbonCurrent === null) { $this->rewind(); } if ($this->validationResult !== static::END_ITERATION) { $this->key++; $this->incrementCurrentDateUntilValid(); } } /** * Rewind to the start date. * * Iterating over a date in the UTC timezone avoids bug during backward DST change. * * @see https://bugs.php.net/bug.php?id=72255 * @see https://bugs.php.net/bug.php?id=74274 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time * * @throws RuntimeException */ public function rewind(): void { $this->key = 0; $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate); $settings = $this->getSettings(); if ($this->hasLocalTranslator()) { $settings['locale'] = $this->getTranslatorLocale(); } $this->carbonCurrent->settings($settings); $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null; if ($this->timezone) { $this->carbonCurrent = $this->carbonCurrent->utc(); } $this->validationResult = null; if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { $this->incrementCurrentDateUntilValid(); } } /** * Skip iterations and returns iteration state (false if ended, true if still valid). * * @param int $count steps number to skip (1 by default) * * @return bool */ public function skip(int $count = 1): bool { for ($i = $count; $this->valid() && $i > 0; $i--) { $this->next(); } return $this->valid(); } /** * Format the date period as ISO 8601. */ public function toIso8601String(): string { $parts = []; if ($this->carbonRecurrences !== null) { $parts[] = 'R'.$this->carbonRecurrences; } $parts[] = $this->startDate->toIso8601String(); if (!$this->isDefaultInterval) { $parts[] = $this->dateInterval->spec(); } if ($this->endDate !== null) { $parts[] = $this->endDate->toIso8601String(); } return implode('/', $parts); } /** * Convert the date period into a string. */ public function toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if ($format instanceof Closure) { return $format($this); } $translator = ([$this->dateClass, 'getTranslator'])(); $parts = []; $format = $format ?? ( !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) ? 'Y-m-d H:i:s' : 'Y-m-d' ); if ($this->carbonRecurrences !== null) { $parts[] = $this->translate('period_recurrences', [], $this->carbonRecurrences, $translator); } $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([ 'join' => true, ])], null, $translator); $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator); if ($this->endDate !== null) { $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator); } $result = implode(' ', $parts); return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1); } /** * Format the date period as ISO 8601. */ public function spec(): string { return $this->toIso8601String(); } /** * Cast the current instance into the given class. * * @param string $className The $className::instance() method will be called to cast the current object. * * @return DatePeriod|object */ public function cast(string $className): object { if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( $this->rawDate($this->getStartDate()), $this->getDateInterval(), $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0, ); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Return native DatePeriod PHP object matching the current instance. * * @example * ``` * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod()); * ``` */ public function toDatePeriod(): DatePeriod { return $this->cast(DatePeriod::class); } /** * Return `true` if the period has no custom filter and is guaranteed to be endless. * * Note that we can't check if a period is endless as soon as it has custom filters * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in * a way we can't predict without actually iterating the period. */ public function isUnfilteredAndEndLess(): bool { foreach ($this->filters as $filter) { switch ($filter) { case [static::RECURRENCES_FILTER, null]: if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) { return false; } break; case [static::END_DATE_FILTER, null]: if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { return false; } break; default: return false; } } return true; } /** * Convert the date period into an array without changing current iteration state. * * @return CarbonInterface[] */ public function toArray(): array { if ($this->isUnfilteredAndEndLess()) { throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); } $state = [ $this->key, $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null, $this->validationResult, ]; $result = iterator_to_array($this); [$this->key, $this->carbonCurrent, $this->validationResult] = $state; return $result; } /** * Count dates in the date period. */ public function count(): int { return \count($this->toArray()); } /** * Return the first date in the date period. */ public function first(): ?CarbonInterface { if ($this->isUnfilteredAndEndLess()) { foreach ($this as $date) { $this->rewind(); return $date; } return null; } return ($this->toArray() ?: [])[0] ?? null; } /** * Return the last date in the date period. */ public function last(): ?CarbonInterface { $array = $this->toArray(); return $array ? $array[\count($array) - 1] : null; } /** * Convert the date period into a string. */ public function __toString(): string { return $this->toString(); } /** * Add aliases for setters. * * CarbonPeriod::days(3)->hours(5)->invert() * ->sinceNow()->until('2010-01-10') * ->filter(...) * ->count() * * Note: We use magic method to let static and instance aliases with the same names. */ public function __call(string $method, array $parameters): mixed { if (static::hasMacro($method)) { return static::bindMacroContext($this, fn () => $this->callMacro($method, $parameters)); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } $count = \count($parameters); switch ($method) { case 'start': case 'since': if ($count === 0) { return $this->getStartDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setStartDate(...$parameters); case 'sinceNow': return $this->setStartDate(new Carbon(), ...$parameters); case 'end': case 'until': if ($count === 0) { return $this->getEndDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setEndDate(...$parameters); case 'untilNow': return $this->setEndDate(new Carbon(), ...$parameters); case 'dates': case 'between': self::setDefaultParameters($parameters, [ [0, 'start', null], [1, 'end', null], ]); return $this->setDates(...$parameters); case 'recurrences': case 'times': if ($count === 0) { return $this->getRecurrences(); } self::setDefaultParameters($parameters, [ [0, 'recurrences', null], ]); return $this->setRecurrences(...$parameters); case 'options': if ($count === 0) { return $this->getOptions(); } self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->setOptions(...$parameters); case 'toggle': self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->toggleOptions(...$parameters); case 'filter': case 'push': return $this->addFilter(...$parameters); case 'prepend': return $this->prependFilter(...$parameters); case 'filters': if ($count === 0) { return $this->getFilters(); } self::setDefaultParameters($parameters, [ [0, 'filters', []], ]); return $this->setFilters(...$parameters); case 'interval': case 'each': case 'every': case 'step': case 'stepBy': if ($count === 0) { return $this->getDateInterval(); } return $this->setDateInterval(...$parameters); case 'invert': return $this->invertDateInterval(); case 'years': case 'year': case 'months': case 'month': case 'weeks': case 'week': case 'days': case 'dayz': case 'day': case 'hours': case 'hour': case 'minutes': case 'minute': case 'seconds': case 'second': case 'milliseconds': case 'millisecond': case 'microseconds': case 'microsecond': return $this->setDateInterval(( // Override default P1D when instantiating via fluent setters. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] )(...$parameters)); } $dateClass = $this->dateClass; if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { throw new UnknownMethodException($method); } return $this; } /** * Set the instance's timezone from a string or object and apply it to start/end. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->setTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->setTimezone($timezone)); } return $self; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } return $self; } /** * Returns the end is set, else calculated from start and recurrences. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. * * @return CarbonInterface */ public function calculateEnd(?string $rounding = null): CarbonInterface { if ($end = $this->getEndDate($rounding)) { return $end; } if ($this->dateInterval->isEmpty()) { return $this->getStartDate($rounding); } $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); if ($date && $rounding) { $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); } return $date; } private function getEndFromRecurrences(): ?CarbonInterface { if ($this->carbonRecurrences === null) { throw new UnreachableException( "Could not calculate period end without either explicit end or recurrences.\n". "If you're looking for a forever-period, use ->setRecurrences(INF).", ); } if ($this->carbonRecurrences === INF) { $start = $this->getStartDate(); return $start < $start->avoidMutation()->add($this->getDateInterval()) ? CarbonImmutable::endOfTime() : CarbonImmutable::startOfTime(); } if ($this->filters === [[static::RECURRENCES_FILTER, null]]) { return $this->getStartDate()->avoidMutation()->add( $this->getDateInterval()->times( $this->carbonRecurrences - ($this->isStartExcluded() ? 0 : 1), ), ); } return null; } private function iterateUntilEnd(): ?CarbonInterface { $attempts = 0; $date = null; foreach ($this as $date) { if (++$attempts > static::END_MAX_ATTEMPTS) { throw new UnreachableException( 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.', ); } } return $date; } /** * Returns true if the current period overlaps the given one (if 1 parameter passed) * or the period between 2 dates (if 2 parameters passed). * * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd * * @return bool */ public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool { $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; if (!($range instanceof self)) { $range = static::create($range); } [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); return $end > $rangeStart && $rangeEnd > $start; } /** * Execute a given function on each date of the period. * * @example * ``` * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) { * echo $date->diffInDays('2020-12-25')." days before Christmas!\n"; * }); * ``` */ public function forEach(callable $callback): void { foreach ($this as $date) { $callback($date); } } /** * Execute a given function on each date of the period and yield the result of this function. * * @example * ``` * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24'); * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) { * return $date->diffInDays('2020-12-25').' days before Christmas!'; * }))); * ``` */ public function map(callable $callback): Generator { foreach ($this as $date) { yield $callback($date); } } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. * * @see equalTo() */ public function eq(mixed $period): bool { return $this->equalTo($period); } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. */ public function equalTo(mixed $period): bool { if (!($period instanceof self)) { $period = self::make($period); } $end = $this->getEndDate(); return $period !== null && $this->getDateInterval()->eq($period->getDateInterval()) && $this->getStartDate()->eq($period->getStartDate()) && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. * * @see notEqualTo() */ public function ne(mixed $period): bool { return $this->notEqualTo($period); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. */ public function notEqualTo(mixed $period): bool { return !$this->eq($period); } /** * Determines if the start date is before another given date. * (Rather start/end are included by options is ignored.) */ public function startsBefore(mixed $date = null): bool { return $this->getStartDate()->lessThan($this->resolveCarbon($date)); } /** * Determines if the start date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsBeforeOrAt(mixed $date = null): bool { return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is after another given date. * (Rather start/end are included by options is ignored.) */ public function startsAfter(mixed $date = null): bool { return $this->getStartDate()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the start date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAfterOrAt(mixed $date = null): bool { return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAt(mixed $date = null): bool { return $this->getStartDate()->equalTo($this->resolveCarbon($date)); } /** * Determines if the end date is before another given date. * (Rather start/end are included by options is ignored.) */ public function endsBefore(mixed $date = null): bool { return $this->calculateEnd()->lessThan($this->resolveCarbon($date)); } /** * Determines if the end date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsBeforeOrAt(mixed $date = null): bool { return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is after another given date. * (Rather start/end are included by options is ignored.) */ public function endsAfter(mixed $date = null): bool { return $this->calculateEnd()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the end date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAfterOrAt(mixed $date = null): bool { return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAt(mixed $date = null): bool { return $this->calculateEnd()->equalTo($this->resolveCarbon($date)); } /** * Return true if start date is now or later. * (Rather start/end are included by options is ignored.) */ public function isStarted(): bool { return $this->startsBeforeOrAt(); } /** * Return true if end date is now or later. * (Rather start/end are included by options is ignored.) */ public function isEnded(): bool { return $this->endsBeforeOrAt(); } /** * Return true if now is between start date (included) and end date (excluded). * (Rather start/end are included by options is ignored.) */ public function isInProgress(): bool { return $this->isStarted() && !$this->isEnded(); } /** * Round the current instance at the given unit with given precision if specified and the given function. */ public function roundUnit( string $unit, DateInterval|float|int|string|null $precision = 1, callable|string $function = 'round', ): static { $self = $this->copyIfImmutable(); $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); if ($self->endDate) { $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); } /** * Truncate the current instance at the given unit with given precision if specified. */ public function floorUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. */ public function ceilUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function round( DateInterval|float|int|string|null $precision = null, callable|string $function = 'round', ): static { return $this->roundWith( $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(), $function ); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function floor(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified (else period interval is used). */ public function ceil(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'ceil'); } /** * Specify data which should be serialized to JSON. * * @link https://php.net/manual/en/jsonserializable.jsonserialize.php * * @return CarbonInterface[] */ public function jsonSerialize(): array { return $this->toArray(); } /** * Return true if the given date is between start and end. */ public function contains(mixed $date = null): bool { $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : ''); $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : ''); return $this->$startMethod($date) && $this->$endMethod($date); } /** * Return true if the current period follows a given other period (with no overlap). * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31] * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function follows(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval())); } /** * Return true if the given other period follows the current one (with no overlap). * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12] * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function isFollowedBy(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $period->follows($this); } /** * Return true if the given period either follows or is followed by the current one. * * @see follows() * @see isFollowedBy() */ public function isConsecutiveWith(mixed $period, mixed ...$arguments): bool { return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments); } public function __debugInfo(): array { $info = $this->baseDebugInfo(); unset( $info['start'], $info['end'], $info['interval'], $info['include_start_date'], $info['include_end_date'], $info['constructed'], $info["\0*\0constructed"], ); return $info; } public function __unserialize(array $data): void { try { $values = array_combine( array_map( static fn (string $key): string => preg_replace('/^\0\*\0/', '', $key), array_keys($data), ), $data, ); $this->initializeSerialization($values); foreach ($values as $key => $value) { if ($value === null) { continue; } $property = match ($key) { 'tzName' => $this->setTimezone(...), 'options' => $this->setOptions(...), 'recurrences' => $this->setRecurrences(...), 'current' => function (mixed $current): void { if (!($current instanceof CarbonInterface)) { $current = $this->resolveCarbon($current); } $this->carbonCurrent = $current; }, 'start' => 'startDate', 'interval' => $this->setDateInterval(...), 'end' => 'endDate', 'key' => null, 'include_start_date' => function (bool $included): void { $this->excludeStartDate(!$included); }, 'include_end_date' => function (bool $included): void { $this->excludeEndDate(!$included); }, default => $key, }; if ($property === null) { continue; } if (\is_callable($property)) { $property($value); continue; } if ($value instanceof DateTimeInterface && !($value instanceof CarbonInterface)) { $value = ($value instanceof DateTime) ? Carbon::instance($value) : CarbonImmutable::instance($value); } try { $this->$property = $value; } catch (Throwable) { // Must be ignored for backward-compatibility } } if (\array_key_exists('carbonRecurrences', $values)) { $this->carbonRecurrences = $values['carbonRecurrences']; } elseif (((int) ($values['recurrences'] ?? 0)) <= 1 && $this->endDate !== null) { $this->carbonRecurrences = null; } } catch (Throwable $e) { // @codeCoverageIgnoreStart if (!method_exists(parent::class, '__unserialize')) { throw $e; } parent::__unserialize($data); // @codeCoverageIgnoreEnd } } /** * Update properties after removing built-in filters. */ protected function updateInternalState(): void { if (!$this->hasFilter(static::END_DATE_FILTER)) { $this->endDate = null; } if (!$this->hasFilter(static::RECURRENCES_FILTER)) { $this->carbonRecurrences = null; } } /** * Create a filter tuple from raw parameters. * * Will create an automatic filter callback for one of Carbon's is* methods. */ protected function createFilterTuple(array $parameters): array { $method = array_shift($parameters); if (!$this->isCarbonPredicateMethod($method)) { return [$method, array_shift($parameters)]; } return [static fn ($date) => ([$date, $method])(...$parameters), $method]; } /** * Return whether given callable is a string pointing to one of Carbon's is* methods * and should be automatically converted to a filter callback. */ protected function isCarbonPredicateMethod(callable|string $callable): bool { return \is_string($callable) && str_starts_with($callable, 'is') && (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable)); } /** * Recurrences filter callback (limits number of recurrences). * * @SuppressWarnings(UnusedFormalParameter) */ protected function filterRecurrences(CarbonInterface $current, int $key): bool|callable { if ($key < $this->carbonRecurrences) { return true; } return static::END_ITERATION; } /** * End date filter callback. * * @return bool|static::END_ITERATION */ protected function filterEndDate(CarbonInterface $current): bool|callable { if (!$this->isEndExcluded() && $current == $this->endDate) { return true; } if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) { return true; } return static::END_ITERATION; } /** * End iteration filter callback. * * @return static::END_ITERATION */ protected function endIteration(): callable { return static::END_ITERATION; } /** * Handle change of the parameters. */ protected function handleChangedParameters(): void { if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { $this->dateClass = CarbonImmutable::class; } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { $this->dateClass = Carbon::class; } $this->validationResult = null; } /** * Validate current date and stop iteration when necessary. * * Returns true when current date is valid, false if it is not, or static::END_ITERATION * when iteration should be stopped. * * @return bool|static::END_ITERATION */ protected function validateCurrentDate(): bool|callable { if ($this->carbonCurrent === null) { $this->rewind(); } // Check after the first rewind to avoid repeating the initial validation. return $this->validationResult ?? ($this->validationResult = $this->checkFilters()); } /** * Check whether current value and key pass all the filters. * * @return bool|static::END_ITERATION */ protected function checkFilters(): bool|callable { $current = $this->prepareForReturn($this->carbonCurrent); foreach ($this->filters as $tuple) { $result = \call_user_func($tuple[0], $current->avoidMutation(), $this->key, $this); if ($result === static::END_ITERATION) { return static::END_ITERATION; } if (!$result) { return false; } } return true; } /** * Prepare given date to be returned to the external logic. * * @param CarbonInterface $date * * @return CarbonInterface */ protected function prepareForReturn(CarbonInterface $date) { $date = ([$this->dateClass, 'make'])($date); if ($this->timezone) { return $date->setTimezone($this->timezone); } return $date; } /** * Keep incrementing the current date until a valid date is found or the iteration is ended. * * @throws RuntimeException */ protected function incrementCurrentDateUntilValid(): void { $attempts = 0; do { $this->carbonCurrent = $this->carbonCurrent->add($this->dateInterval); $this->validationResult = null; if (++$attempts > static::NEXT_MAX_ATTEMPTS) { throw new UnreachableException('Could not find next valid date.'); } } while ($this->validateCurrentDate() === false); } /** * Call given macro. */ protected function callMacro(string $name, array $parameters): mixed { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date * * @return \Carbon\CarbonInterface */ protected function resolveCarbon($date = null) { return $this->getStartDate()->nowWithSameTz()->carbonize($date); } /** * Resolve passed arguments or DatePeriod to a CarbonPeriod object. */ protected function resolveCarbonPeriod(mixed $period, mixed ...$arguments): self { if ($period instanceof self) { return $period; } return $period instanceof DatePeriod ? static::instance($period) : static::create($period, ...$arguments); } private function orderCouple($first, $second): array { return $first > $second ? [$second, $first] : [$first, $second]; } private function makeDateTime($value): ?DateTimeInterface { if ($value instanceof DateTimeInterface) { return $value; } if ($value instanceof WeekDay || $value instanceof Month) { $dateClass = $this->dateClass; return new $dateClass($value, $this->timezoneSetting); } if (\is_string($value)) { $value = trim($value); if (!preg_match('/^P[\dT]/', $value) && !preg_match('/^R\d/', $value) && preg_match('/[a-z\d]/i', $value) ) { $dateClass = $this->dateClass; return $dateClass::parse($value, $this->timezoneSetting); } } return null; } private function isInfiniteDate($date): bool { return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); } private function rawDate($date): ?DateTimeInterface { if ($date === false || $date === null) { return null; } if ($date instanceof CarbonInterface) { return $date->isMutable() ? $date->toDateTime() : $date->toDateTimeImmutable(); } if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { return $date; } $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); } private static function setDefaultParameters(array &$parameters, array $defaults): void { foreach ($defaults as [$index, $name, $value]) { if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { $parameters[$index] = $value; } } } private function setFromAssociativeArray(array $parameters): void { if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['end'])) { $this->setEndDate($parameters['end']); } if (isset($parameters['recurrences'])) { $this->setRecurrences($parameters['recurrences']); } if (isset($parameters['interval'])) { $this->setDateInterval($parameters['interval']); } if (isset($parameters['options'])) { $this->setOptions($parameters['options']); } } private function configureTimezone(DateTimeZone $timezone, array $sortedArguments, array $originalArguments): array { $this->setTimezone($timezone); if (\is_string($originalArguments['start'] ?? null)) { $sortedArguments['start'] = $this->makeDateTime($originalArguments['start']); } if (\is_string($originalArguments['end'] ?? null)) { $sortedArguments['end'] = $this->makeDateTime($originalArguments['end']); } return $sortedArguments; } private function initializeSerialization(array $values): void { $serializationBase = [ 'start' => $values['start'] ?? $values['startDate'] ?? null, 'current' => $values['current'] ?? $values['carbonCurrent'] ?? null, 'end' => $values['end'] ?? $values['endDate'] ?? null, 'interval' => $values['interval'] ?? $values['dateInterval'] ?? null, 'recurrences' => max(1, (int) ($values['recurrences'] ?? $values['carbonRecurrences'] ?? 1)), 'include_start_date' => $values['include_start_date'] ?? true, 'include_end_date' => $values['include_end_date'] ?? false, ]; foreach (['start', 'current', 'end'] as $dateProperty) { if ($serializationBase[$dateProperty] instanceof Carbon) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTime(); } elseif ($serializationBase[$dateProperty] instanceof CarbonInterface) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTimeImmutable(); } } if ($serializationBase['interval'] instanceof CarbonInterval) { $serializationBase['interval'] = $serializationBase['interval']->toDateInterval(); } // @codeCoverageIgnoreStart if (method_exists(parent::class, '__unserialize')) { parent::__unserialize($serializationBase); return; } $excludeStart = !($values['include_start_date'] ?? true); $includeEnd = $values['include_end_date'] ?? true; parent::__construct( $serializationBase['start'], $serializationBase['interval'], $serializationBase['end'] ?? $serializationBase['recurrences'], ($excludeStart ? self::EXCLUDE_START_DATE : 0) | ($includeEnd && \defined('DatePeriod::INCLUDE_END_DATE') ? self::INCLUDE_END_DATE : 0), ); // @codeCoverageIgnoreEnd } }
PHP
{ "end_line": 992, "name": "toggleOptions", "signature": "public function toggleOptions(int $options, ?bool $state = null): static", "start_line": 979 }
{ "class_name": "CarbonPeriod", "class_signature": "class CarbonPeriod implements Countable, JsonSerializable, UnitValue", "namespace": "Carbon" }
removeFilter
Carbon/src/Carbon/CarbonPeriod.php
public function removeFilter(callable|string $filter): static { $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; $self->filters = array_values(array_filter( $this->filters, static fn ($tuple) => $tuple[$key] !== $filter, )); $self->updateInternalState(); $self->handleChangedParameters(); return $self; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotACarbonClassException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnreachableException; use Carbon\Traits\DeprecatedPeriodProperties; use Carbon\Traits\IntervalRounding; use Carbon\Traits\LocalFactory; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Throwable; // @codeCoverageIgnoreStart require PHP_VERSION < 8.2 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php' : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php'; // @codeCoverageIgnoreEnd /** * Substitution of DatePeriod with some modifications and many more features. * * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. * @method static static since($date = null, $inclusive = null) Alias for start(). * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. * @method static static until($date = null, $inclusive = null) Alias for end(). * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. * @method static static times($recurrences = null) Alias for recurrences(). * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance. * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. * @method static static push($callback, $name = null) Alias for filter(). * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance. * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. * @method static static year($years = 1) Alias for years(). * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. * @method static static month($months = 1) Alias for months(). * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. * @method static static week($weeks = 1) Alias for weeks(). * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. * @method static static dayz($days = 1) Alias for days(). * @method static static day($days = 1) Alias for days(). * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. * @method static static hour($hours = 1) Alias for hours(). * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. * @method static static minute($minutes = 1) Alias for minutes(). * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. * @method static static second($seconds = 1) Alias for seconds(). * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * * @mixin DeprecatedPeriodProperties * * @SuppressWarnings(TooManyFields) * @SuppressWarnings(CamelCasePropertyName) * @SuppressWarnings(CouplingBetweenObjects) */ class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue { use LocalFactory; use IntervalRounding; use Mixin { Mixin::mixin as baseMixin; } use Options { Options::__debugInfo as baseDebugInfo; } use ToStringFormat; /** * Built-in filter for limit by recurrences. * * @var callable */ public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; /** * Built-in filter for limit to an end. * * @var callable */ public const END_DATE_FILTER = [self::class, 'filterEndDate']; /** * Special value which can be returned by filters to end iteration. Also a filter. * * @var callable */ public const END_ITERATION = [self::class, 'endIteration']; /** * Exclude end date from iteration. * * @var int */ public const EXCLUDE_END_DATE = 8; /** * Yield CarbonImmutable instances. * * @var int */ public const IMMUTABLE = 4; /** * Number of maximum attempts before giving up on finding next valid date. * * @var int */ public const NEXT_MAX_ATTEMPTS = 1000; /** * Number of maximum attempts before giving up on finding end date. * * @var int */ public const END_MAX_ATTEMPTS = 10000; /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = Carbon::class; /** * The registered macros. */ protected static array $macros = []; /** * Date class of iteration items. */ protected string $dateClass = Carbon::class; /** * Underlying date interval instance. Always present, one day by default. */ protected ?CarbonInterval $dateInterval = null; /** * True once __construct is finished. */ protected bool $constructed = false; /** * Whether current date interval was set by default. */ protected bool $isDefaultInterval = false; /** * The filters stack. */ protected array $filters = []; /** * Period start date. Applied on rewind. Always present, now by default. */ protected ?CarbonInterface $startDate = null; /** * Period end date. For inverted interval should be before the start date. Applied via a filter. */ protected ?CarbonInterface $endDate = null; /** * Limit for number of recurrences. Applied via a filter. */ protected int|float|null $carbonRecurrences = null; /** * Iteration options. */ protected ?int $options = null; /** * Index of current date. Always sequential, even if some dates are skipped by filters. * Equal to null only before the first iteration. */ protected int $key = 0; /** * Current date. May temporarily hold unaccepted value when looking for a next valid date. * Equal to null only before the first iteration. */ protected ?CarbonInterface $carbonCurrent = null; /** * Timezone of current date. Taken from the start date. */ protected ?DateTimeZone $timezone = null; /** * The cached validation result for current date. */ protected array|string|bool|null $validationResult = null; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; public function getIterator(): Generator { $this->rewind(); while ($this->valid()) { $key = $this->key(); $value = $this->current(); yield $key => $value; $this->next(); } } /** * Make a CarbonPeriod instance from given variable if possible. */ public static function make(mixed $var): ?static { try { return static::instance($var); } catch (NotAPeriodException) { return static::create($var); } } /** * Create a new instance from a DatePeriod or CarbonPeriod object. */ public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); } /** * Create a new instance. */ public static function create(...$params): static { return static::createFromArray($params); } /** * Create a new instance from an array of parameters. */ public static function createFromArray(array $params): static { return new static(...$params); } /** * Create CarbonPeriod from ISO 8601 string. */ public static function createFromIso(string $iso, ?int $options = null): static { $params = static::parseIso8601($iso); $instance = static::createFromArray($params); $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options; $instance->handleChangedParameters(); return $instance; } public static function createFromISO8601String(string $iso, ?int $options = null): static { return self::createFromIso($iso, $options); } /** * Return whether the given interval contains non-zero value of any time unit. */ protected static function intervalHasTime(DateInterval $interval): bool { return $interval->h || $interval->i || $interval->s || $interval->f; } /** * Return whether given variable is an ISO 8601 specification. * * Note: Check is very basic, as actual validation will be done later when parsing. * We just want to ensure that variable is not any other type of valid parameter. */ protected static function isIso8601(mixed $var): bool { if (!\is_string($var)) { return false; } // Match slash but not within a timezone name. $part = '[a-z]+(?:[_-][a-z]+)*'; preg_match("#\b$part/$part\b|(/)#i", $var, $match); return isset($match[1]); } /** * Parse given ISO 8601 string into an array of arguments. * * @SuppressWarnings(ElseExpression) */ protected static function parseIso8601(string $iso): array { $result = []; $interval = null; $start = null; $end = null; $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = self::makeInterval($part)) { $interval = $part; } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); } $result[] = $parsed; } return $result; } /** * Add missing parts of the target date from the source date. */ protected static function addMissingParts(string $source, string $target): string { $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); return $count ? $result : $target; } private static function makeInterval(mixed $input): ?CarbonInterval { try { return CarbonInterval::make($input); } catch (Throwable) { return null; } } private static function makeTimezone(mixed $input): ?CarbonTimeZone { if (!\is_string($input)) { return null; } try { return CarbonTimeZone::create($input); } catch (Throwable) { return null; } } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonPeriod::macro('middle', function () { * return $this->getStartDate()->average($this->getEndDate()); * }); * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonPeriod::mixin(new class { * public function addDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->addDays($count) * )->setEndDate( * $this->getEndDate()->addDays($count) * ); * }; * } * public function subDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->subDays($count) * )->setEndDate( * $this->getEndDate()->subDays($count) * ); * }; * } * }); * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); * ``` * * @throws ReflectionException */ public static function mixin(object|string $mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Provide static proxy for instance aliases. */ public static function __callStatic(string $method, array $parameters): mixed { $date = new static(); if (static::hasMacro($method)) { return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters)); } return $date->$method(...$parameters); } /** * CarbonPeriod constructor. * * @SuppressWarnings(ElseExpression) * * @throws InvalidArgumentException */ public function __construct(...$arguments) { $raw = null; if (isset($arguments['raw'])) { $raw = $arguments['raw']; $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false; if (isset($arguments['dateClass'])) { $this->dateClass = $arguments['dateClass']; } $arguments = $raw; } // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. $argumentsCount = \count($arguments); if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { array_splice($arguments, 0, 1, static::parseIso8601($iso)); } if ($argumentsCount === 1) { if ($arguments[0] instanceof self) { $arguments = [ $arguments[0]->getStartDate(), $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(), $arguments[0]->getDateInterval(), $arguments[0]->getOptions(), ]; } elseif ($arguments[0] instanceof DatePeriod) { $arguments = [ $arguments[0]->start, $arguments[0]->end ?: ($arguments[0]->recurrences - 1), $arguments[0]->interval, $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, ]; } } if (is_a($this->dateClass, DateTimeImmutable::class, true)) { $this->options = static::IMMUTABLE; } $optionsSet = false; $originalArguments = []; $sortedArguments = []; foreach ($arguments as $argument) { $parsedDate = null; if ($argument instanceof DateTimeZone) { $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments); } elseif (!isset($sortedArguments['interval']) && ( (\is_string($argument) && preg_match( '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument, )) || $argument instanceof DateInterval || $argument instanceof Closure || $argument instanceof Unit ) && $parsedInterval = self::makeInterval($argument) ) { $sortedArguments['interval'] = $parsedInterval; } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) { $sortedArguments['start'] = $parsedDate; $originalArguments['start'] = $argument; } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { $sortedArguments['end'] = $parsedDate; $originalArguments['end'] = $argument; } elseif (!isset($sortedArguments['recurrences']) && !isset($sortedArguments['end']) && (\is_int($argument) || \is_float($argument)) && $argument >= 0 ) { $sortedArguments['recurrences'] = $argument; } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { $optionsSet = true; $sortedArguments['options'] = (((int) $this->options) | ((int) $argument)); } elseif ($parsedTimezone = self::makeTimezone($argument)) { $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($raw === null && isset($sortedArguments['start'])) { $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1); if (\is_float($end)) { $end = $end === INF ? PHP_INT_MAX : (int) round($end); } $raw = [ $sortedArguments['start'], $sortedArguments['interval'] ?? CarbonInterval::day(), $end, ]; } $this->setFromAssociativeArray($sortedArguments); if ($this->startDate === null) { $dateClass = $this->dateClass; $this->setStartDate($dateClass::now()); } if ($this->dateInterval === null) { $this->setDateInterval(CarbonInterval::day()); $this->isDefaultInterval = true; } if ($this->options === null) { $this->setOptions(0); } parent::__construct( $this->startDate, $this->dateInterval, $this->endDate ?? max(1, min(2147483639, $this->recurrences ?? 1)), $this->options, ); $this->constructed = true; } /** * Get a copy of the instance. */ public function copy(): static { return clone $this; } /** * Prepare the instance to be set (self if mutable to be mutated, * copy if immutable to generate a new instance). */ protected function copyIfImmutable(): static { return $this; } /** * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. */ protected function getGetter(string $name): ?callable { return match (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) { 'start', 'start_date' => [$this, 'getStartDate'], 'end', 'end_date' => [$this, 'getEndDate'], 'interval', 'date_interval' => [$this, 'getDateInterval'], 'recurrences' => [$this, 'getRecurrences'], 'include_start_date' => [$this, 'isStartIncluded'], 'include_end_date' => [$this, 'isEndIncluded'], 'current' => [$this, 'current'], 'locale' => [$this, 'locale'], 'tzname', 'tz_name' => fn () => match (true) { $this->timezoneSetting === null => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, $this->timezoneSetting instanceof DateTimeZone => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, default => null, }; } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function get(string $name) { $getter = $this->getGetter($name); if ($getter) { return $getter(); } throw new UnknownGetterException($name); } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function __get(string $name) { return $this->get($name); } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset(string $name): bool { return $this->getGetter($name) !== null; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Set the iteration item class. * * @param string $dateClass * * @return static */ public function setDateClass(string $dateClass) { if (!is_a($dateClass, CarbonInterface::class, true)) { throw new NotACarbonClassException($dateClass); } $self = $this->copyIfImmutable(); $self->dateClass = $dateClass; if (is_a($dateClass, Carbon::class, true)) { $self->options = $self->options & ~static::IMMUTABLE; } elseif (is_a($dateClass, CarbonImmutable::class, true)) { $self->options = $self->options | static::IMMUTABLE; } return $self; } /** * Returns iteration item date class. * * @return string */ public function getDateClass(): string { return $this->dateClass; } /** * Change the period date interval. * * @param DateInterval|Unit|string|int $interval * @param Unit|string $unit the unit of $interval if it's a number * * @throws InvalidIntervalException * * @return static */ public function setDateInterval(mixed $interval, Unit|string|null $unit = null): static { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->name; } if (!$interval = CarbonInterval::make($interval, $unit)) { throw new InvalidIntervalException('Invalid interval.'); } if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) { throw new InvalidIntervalException('Empty interval is not accepted.'); } $self = $this->copyIfImmutable(); $self->dateInterval = $interval; $self->isDefaultInterval = false; $self->handleChangedParameters(); return $self; } /** * Reset the date interval to the default value. * * Difference with simply setting interval to 1-day is that P1D will not appear when calling toIso8601String() * and also next adding to the interval won't include the default 1-day. */ public function resetDateInterval(): static { $self = $this->copyIfImmutable(); $self->setDateInterval(CarbonInterval::day()); $self->isDefaultInterval = true; return $self; } /** * Invert the period date interval. */ public function invertDateInterval(): static { return $this->setDateInterval($this->dateInterval->invert()); } /** * Set start and end date. * * @param DateTime|DateTimeInterface|string $start * @param DateTime|DateTimeInterface|string|null $end * * @return static */ public function setDates(mixed $start, mixed $end): static { return $this->setStartDate($start)->setEndDate($end); } /** * Change the period options. * * @param int|null $options * * @return static */ public function setOptions(?int $options): static { $self = $this->copyIfImmutable(); $self->options = $options ?? 0; $self->handleChangedParameters(); return $self; } /** * Get the period options. */ public function getOptions(): int { return $this->options ?? 0; } /** * Toggle given options on or off. * * @param int $options * @param bool|null $state * * @throws InvalidArgumentException * * @return static */ public function toggleOptions(int $options, ?bool $state = null): static { $self = $this->copyIfImmutable(); if ($state === null) { $state = ($this->options & $options) !== $options; } return $self->setOptions( $state ? $this->options | $options : $this->options & ~$options, ); } /** * Toggle EXCLUDE_START_DATE option. */ public function excludeStartDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_START_DATE, $state); } /** * Toggle EXCLUDE_END_DATE option. */ public function excludeEndDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_END_DATE, $state); } /** * Get the underlying date interval. */ public function getDateInterval(): CarbonInterval { return $this->dateInterval->copy(); } /** * Get start date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getStartDate(?string $rounding = null): CarbonInterface { $date = $this->startDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get end date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getEndDate(?string $rounding = null): ?CarbonInterface { if (!$this->endDate) { return null; } $date = $this->endDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get number of recurrences. */ #[ReturnTypeWillChange] public function getRecurrences(): int|float|null { return $this->carbonRecurrences; } /** * Returns true if the start date should be excluded. */ public function isStartExcluded(): bool { return ($this->options & static::EXCLUDE_START_DATE) !== 0; } /** * Returns true if the end date should be excluded. */ public function isEndExcluded(): bool { return ($this->options & static::EXCLUDE_END_DATE) !== 0; } /** * Returns true if the start date should be included. */ public function isStartIncluded(): bool { return !$this->isStartExcluded(); } /** * Returns true if the end date should be included. */ public function isEndIncluded(): bool { return !$this->isEndExcluded(); } /** * Return the start if it's included by option, else return the start + 1 period interval. */ public function getIncludedStartDate(): CarbonInterface { $start = $this->getStartDate(); if ($this->isStartExcluded()) { return $start->add($this->getDateInterval()); } return $start; } /** * Return the end if it's included by option, else return the end - 1 period interval. * Warning: if the period has no fixed end, this method will iterate the period to calculate it. */ public function getIncludedEndDate(): CarbonInterface { $end = $this->getEndDate(); if (!$end) { return $this->calculateEnd(); } if ($this->isEndExcluded()) { return $end->sub($this->getDateInterval()); } return $end; } /** * Add a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function addFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); $self->filters[] = $tuple; $self->handleChangedParameters(); return $self; } /** * Prepend a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function prependFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); array_unshift($self->filters, $tuple); $self->handleChangedParameters(); return $self; } /** * Remove a filter by instance or name. */ public function removeFilter(callable|string $filter): static { $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; $self->filters = array_values(array_filter( $this->filters, static fn ($tuple) => $tuple[$key] !== $filter, )); $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Return whether given instance or name is in the filter stack. */ public function hasFilter(callable|string $filter): bool { $key = \is_callable($filter) ? 0 : 1; foreach ($this->filters as $tuple) { if ($tuple[$key] === $filter) { return true; } } return false; } /** * Get filters stack. */ public function getFilters(): array { return $this->filters; } /** * Set filters stack. */ public function setFilters(array $filters): static { $self = $this->copyIfImmutable(); $self->filters = $filters; $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Reset filters stack. */ public function resetFilters(): static { $self = $this->copyIfImmutable(); $self->filters = []; if ($self->endDate !== null) { $self->filters[] = [static::END_DATE_FILTER, null]; } if ($self->carbonRecurrences !== null) { $self->filters[] = [static::RECURRENCES_FILTER, null]; } $self->handleChangedParameters(); return $self; } /** * Add a recurrences filter (set maximum number of recurrences). * * @throws InvalidArgumentException */ public function setRecurrences(int|float|null $recurrences): static { if ($recurrences === null) { return $this->removeFilter(static::RECURRENCES_FILTER); } if ($recurrences < 0) { throw new InvalidPeriodParameterException('Invalid number of recurrences.'); } /** @var self $self */ $self = $this->copyIfImmutable(); $self->carbonRecurrences = $recurrences === INF ? INF : (int) $recurrences; if (!$self->hasFilter(static::RECURRENCES_FILTER)) { return $self->addFilter(static::RECURRENCES_FILTER); } $self->handleChangedParameters(); return $self; } /** * Change the period start date. * * @param DateTime|DateTimeInterface|string $date * @param bool|null $inclusive * * @throws InvalidPeriodDateException * * @return static */ public function setStartDate(mixed $date, ?bool $inclusive = null): static { if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date, $this->timezone))) { throw new InvalidPeriodDateException('Invalid start date.'); } $self = $this->copyIfImmutable(); $self->startDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); } return $self; } /** * Change the period end date. * * @param DateTime|DateTimeInterface|string|null $date * @param bool|null $inclusive * * @throws \InvalidArgumentException * * @return static */ public function setEndDate(mixed $date, ?bool $inclusive = null): static { if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date, $this->timezone)) { throw new InvalidPeriodDateException('Invalid end date.'); } if (!$date) { return $this->removeFilter(static::END_DATE_FILTER); } $self = $this->copyIfImmutable(); $self->endDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); } if (!$self->hasFilter(static::END_DATE_FILTER)) { return $self->addFilter(static::END_DATE_FILTER); } $self->handleChangedParameters(); return $self; } /** * Check if the current position is valid. */ public function valid(): bool { return $this->validateCurrentDate() === true; } /** * Return the current key. */ public function key(): ?int { return $this->valid() ? $this->key : null; } /** * Return the current date. */ public function current(): ?CarbonInterface { return $this->valid() ? $this->prepareForReturn($this->carbonCurrent) : null; } /** * Move forward to the next date. * * @throws RuntimeException */ public function next(): void { if ($this->carbonCurrent === null) { $this->rewind(); } if ($this->validationResult !== static::END_ITERATION) { $this->key++; $this->incrementCurrentDateUntilValid(); } } /** * Rewind to the start date. * * Iterating over a date in the UTC timezone avoids bug during backward DST change. * * @see https://bugs.php.net/bug.php?id=72255 * @see https://bugs.php.net/bug.php?id=74274 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time * * @throws RuntimeException */ public function rewind(): void { $this->key = 0; $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate); $settings = $this->getSettings(); if ($this->hasLocalTranslator()) { $settings['locale'] = $this->getTranslatorLocale(); } $this->carbonCurrent->settings($settings); $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null; if ($this->timezone) { $this->carbonCurrent = $this->carbonCurrent->utc(); } $this->validationResult = null; if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { $this->incrementCurrentDateUntilValid(); } } /** * Skip iterations and returns iteration state (false if ended, true if still valid). * * @param int $count steps number to skip (1 by default) * * @return bool */ public function skip(int $count = 1): bool { for ($i = $count; $this->valid() && $i > 0; $i--) { $this->next(); } return $this->valid(); } /** * Format the date period as ISO 8601. */ public function toIso8601String(): string { $parts = []; if ($this->carbonRecurrences !== null) { $parts[] = 'R'.$this->carbonRecurrences; } $parts[] = $this->startDate->toIso8601String(); if (!$this->isDefaultInterval) { $parts[] = $this->dateInterval->spec(); } if ($this->endDate !== null) { $parts[] = $this->endDate->toIso8601String(); } return implode('/', $parts); } /** * Convert the date period into a string. */ public function toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if ($format instanceof Closure) { return $format($this); } $translator = ([$this->dateClass, 'getTranslator'])(); $parts = []; $format = $format ?? ( !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) ? 'Y-m-d H:i:s' : 'Y-m-d' ); if ($this->carbonRecurrences !== null) { $parts[] = $this->translate('period_recurrences', [], $this->carbonRecurrences, $translator); } $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([ 'join' => true, ])], null, $translator); $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator); if ($this->endDate !== null) { $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator); } $result = implode(' ', $parts); return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1); } /** * Format the date period as ISO 8601. */ public function spec(): string { return $this->toIso8601String(); } /** * Cast the current instance into the given class. * * @param string $className The $className::instance() method will be called to cast the current object. * * @return DatePeriod|object */ public function cast(string $className): object { if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( $this->rawDate($this->getStartDate()), $this->getDateInterval(), $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0, ); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Return native DatePeriod PHP object matching the current instance. * * @example * ``` * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod()); * ``` */ public function toDatePeriod(): DatePeriod { return $this->cast(DatePeriod::class); } /** * Return `true` if the period has no custom filter and is guaranteed to be endless. * * Note that we can't check if a period is endless as soon as it has custom filters * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in * a way we can't predict without actually iterating the period. */ public function isUnfilteredAndEndLess(): bool { foreach ($this->filters as $filter) { switch ($filter) { case [static::RECURRENCES_FILTER, null]: if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) { return false; } break; case [static::END_DATE_FILTER, null]: if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { return false; } break; default: return false; } } return true; } /** * Convert the date period into an array without changing current iteration state. * * @return CarbonInterface[] */ public function toArray(): array { if ($this->isUnfilteredAndEndLess()) { throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); } $state = [ $this->key, $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null, $this->validationResult, ]; $result = iterator_to_array($this); [$this->key, $this->carbonCurrent, $this->validationResult] = $state; return $result; } /** * Count dates in the date period. */ public function count(): int { return \count($this->toArray()); } /** * Return the first date in the date period. */ public function first(): ?CarbonInterface { if ($this->isUnfilteredAndEndLess()) { foreach ($this as $date) { $this->rewind(); return $date; } return null; } return ($this->toArray() ?: [])[0] ?? null; } /** * Return the last date in the date period. */ public function last(): ?CarbonInterface { $array = $this->toArray(); return $array ? $array[\count($array) - 1] : null; } /** * Convert the date period into a string. */ public function __toString(): string { return $this->toString(); } /** * Add aliases for setters. * * CarbonPeriod::days(3)->hours(5)->invert() * ->sinceNow()->until('2010-01-10') * ->filter(...) * ->count() * * Note: We use magic method to let static and instance aliases with the same names. */ public function __call(string $method, array $parameters): mixed { if (static::hasMacro($method)) { return static::bindMacroContext($this, fn () => $this->callMacro($method, $parameters)); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } $count = \count($parameters); switch ($method) { case 'start': case 'since': if ($count === 0) { return $this->getStartDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setStartDate(...$parameters); case 'sinceNow': return $this->setStartDate(new Carbon(), ...$parameters); case 'end': case 'until': if ($count === 0) { return $this->getEndDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setEndDate(...$parameters); case 'untilNow': return $this->setEndDate(new Carbon(), ...$parameters); case 'dates': case 'between': self::setDefaultParameters($parameters, [ [0, 'start', null], [1, 'end', null], ]); return $this->setDates(...$parameters); case 'recurrences': case 'times': if ($count === 0) { return $this->getRecurrences(); } self::setDefaultParameters($parameters, [ [0, 'recurrences', null], ]); return $this->setRecurrences(...$parameters); case 'options': if ($count === 0) { return $this->getOptions(); } self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->setOptions(...$parameters); case 'toggle': self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->toggleOptions(...$parameters); case 'filter': case 'push': return $this->addFilter(...$parameters); case 'prepend': return $this->prependFilter(...$parameters); case 'filters': if ($count === 0) { return $this->getFilters(); } self::setDefaultParameters($parameters, [ [0, 'filters', []], ]); return $this->setFilters(...$parameters); case 'interval': case 'each': case 'every': case 'step': case 'stepBy': if ($count === 0) { return $this->getDateInterval(); } return $this->setDateInterval(...$parameters); case 'invert': return $this->invertDateInterval(); case 'years': case 'year': case 'months': case 'month': case 'weeks': case 'week': case 'days': case 'dayz': case 'day': case 'hours': case 'hour': case 'minutes': case 'minute': case 'seconds': case 'second': case 'milliseconds': case 'millisecond': case 'microseconds': case 'microsecond': return $this->setDateInterval(( // Override default P1D when instantiating via fluent setters. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] )(...$parameters)); } $dateClass = $this->dateClass; if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { throw new UnknownMethodException($method); } return $this; } /** * Set the instance's timezone from a string or object and apply it to start/end. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->setTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->setTimezone($timezone)); } return $self; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } return $self; } /** * Returns the end is set, else calculated from start and recurrences. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. * * @return CarbonInterface */ public function calculateEnd(?string $rounding = null): CarbonInterface { if ($end = $this->getEndDate($rounding)) { return $end; } if ($this->dateInterval->isEmpty()) { return $this->getStartDate($rounding); } $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); if ($date && $rounding) { $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); } return $date; } private function getEndFromRecurrences(): ?CarbonInterface { if ($this->carbonRecurrences === null) { throw new UnreachableException( "Could not calculate period end without either explicit end or recurrences.\n". "If you're looking for a forever-period, use ->setRecurrences(INF).", ); } if ($this->carbonRecurrences === INF) { $start = $this->getStartDate(); return $start < $start->avoidMutation()->add($this->getDateInterval()) ? CarbonImmutable::endOfTime() : CarbonImmutable::startOfTime(); } if ($this->filters === [[static::RECURRENCES_FILTER, null]]) { return $this->getStartDate()->avoidMutation()->add( $this->getDateInterval()->times( $this->carbonRecurrences - ($this->isStartExcluded() ? 0 : 1), ), ); } return null; } private function iterateUntilEnd(): ?CarbonInterface { $attempts = 0; $date = null; foreach ($this as $date) { if (++$attempts > static::END_MAX_ATTEMPTS) { throw new UnreachableException( 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.', ); } } return $date; } /** * Returns true if the current period overlaps the given one (if 1 parameter passed) * or the period between 2 dates (if 2 parameters passed). * * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd * * @return bool */ public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool { $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; if (!($range instanceof self)) { $range = static::create($range); } [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); return $end > $rangeStart && $rangeEnd > $start; } /** * Execute a given function on each date of the period. * * @example * ``` * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) { * echo $date->diffInDays('2020-12-25')." days before Christmas!\n"; * }); * ``` */ public function forEach(callable $callback): void { foreach ($this as $date) { $callback($date); } } /** * Execute a given function on each date of the period and yield the result of this function. * * @example * ``` * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24'); * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) { * return $date->diffInDays('2020-12-25').' days before Christmas!'; * }))); * ``` */ public function map(callable $callback): Generator { foreach ($this as $date) { yield $callback($date); } } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. * * @see equalTo() */ public function eq(mixed $period): bool { return $this->equalTo($period); } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. */ public function equalTo(mixed $period): bool { if (!($period instanceof self)) { $period = self::make($period); } $end = $this->getEndDate(); return $period !== null && $this->getDateInterval()->eq($period->getDateInterval()) && $this->getStartDate()->eq($period->getStartDate()) && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. * * @see notEqualTo() */ public function ne(mixed $period): bool { return $this->notEqualTo($period); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. */ public function notEqualTo(mixed $period): bool { return !$this->eq($period); } /** * Determines if the start date is before another given date. * (Rather start/end are included by options is ignored.) */ public function startsBefore(mixed $date = null): bool { return $this->getStartDate()->lessThan($this->resolveCarbon($date)); } /** * Determines if the start date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsBeforeOrAt(mixed $date = null): bool { return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is after another given date. * (Rather start/end are included by options is ignored.) */ public function startsAfter(mixed $date = null): bool { return $this->getStartDate()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the start date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAfterOrAt(mixed $date = null): bool { return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAt(mixed $date = null): bool { return $this->getStartDate()->equalTo($this->resolveCarbon($date)); } /** * Determines if the end date is before another given date. * (Rather start/end are included by options is ignored.) */ public function endsBefore(mixed $date = null): bool { return $this->calculateEnd()->lessThan($this->resolveCarbon($date)); } /** * Determines if the end date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsBeforeOrAt(mixed $date = null): bool { return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is after another given date. * (Rather start/end are included by options is ignored.) */ public function endsAfter(mixed $date = null): bool { return $this->calculateEnd()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the end date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAfterOrAt(mixed $date = null): bool { return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAt(mixed $date = null): bool { return $this->calculateEnd()->equalTo($this->resolveCarbon($date)); } /** * Return true if start date is now or later. * (Rather start/end are included by options is ignored.) */ public function isStarted(): bool { return $this->startsBeforeOrAt(); } /** * Return true if end date is now or later. * (Rather start/end are included by options is ignored.) */ public function isEnded(): bool { return $this->endsBeforeOrAt(); } /** * Return true if now is between start date (included) and end date (excluded). * (Rather start/end are included by options is ignored.) */ public function isInProgress(): bool { return $this->isStarted() && !$this->isEnded(); } /** * Round the current instance at the given unit with given precision if specified and the given function. */ public function roundUnit( string $unit, DateInterval|float|int|string|null $precision = 1, callable|string $function = 'round', ): static { $self = $this->copyIfImmutable(); $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); if ($self->endDate) { $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); } /** * Truncate the current instance at the given unit with given precision if specified. */ public function floorUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. */ public function ceilUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function round( DateInterval|float|int|string|null $precision = null, callable|string $function = 'round', ): static { return $this->roundWith( $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(), $function ); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function floor(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified (else period interval is used). */ public function ceil(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'ceil'); } /** * Specify data which should be serialized to JSON. * * @link https://php.net/manual/en/jsonserializable.jsonserialize.php * * @return CarbonInterface[] */ public function jsonSerialize(): array { return $this->toArray(); } /** * Return true if the given date is between start and end. */ public function contains(mixed $date = null): bool { $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : ''); $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : ''); return $this->$startMethod($date) && $this->$endMethod($date); } /** * Return true if the current period follows a given other period (with no overlap). * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31] * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function follows(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval())); } /** * Return true if the given other period follows the current one (with no overlap). * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12] * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function isFollowedBy(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $period->follows($this); } /** * Return true if the given period either follows or is followed by the current one. * * @see follows() * @see isFollowedBy() */ public function isConsecutiveWith(mixed $period, mixed ...$arguments): bool { return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments); } public function __debugInfo(): array { $info = $this->baseDebugInfo(); unset( $info['start'], $info['end'], $info['interval'], $info['include_start_date'], $info['include_end_date'], $info['constructed'], $info["\0*\0constructed"], ); return $info; } public function __unserialize(array $data): void { try { $values = array_combine( array_map( static fn (string $key): string => preg_replace('/^\0\*\0/', '', $key), array_keys($data), ), $data, ); $this->initializeSerialization($values); foreach ($values as $key => $value) { if ($value === null) { continue; } $property = match ($key) { 'tzName' => $this->setTimezone(...), 'options' => $this->setOptions(...), 'recurrences' => $this->setRecurrences(...), 'current' => function (mixed $current): void { if (!($current instanceof CarbonInterface)) { $current = $this->resolveCarbon($current); } $this->carbonCurrent = $current; }, 'start' => 'startDate', 'interval' => $this->setDateInterval(...), 'end' => 'endDate', 'key' => null, 'include_start_date' => function (bool $included): void { $this->excludeStartDate(!$included); }, 'include_end_date' => function (bool $included): void { $this->excludeEndDate(!$included); }, default => $key, }; if ($property === null) { continue; } if (\is_callable($property)) { $property($value); continue; } if ($value instanceof DateTimeInterface && !($value instanceof CarbonInterface)) { $value = ($value instanceof DateTime) ? Carbon::instance($value) : CarbonImmutable::instance($value); } try { $this->$property = $value; } catch (Throwable) { // Must be ignored for backward-compatibility } } if (\array_key_exists('carbonRecurrences', $values)) { $this->carbonRecurrences = $values['carbonRecurrences']; } elseif (((int) ($values['recurrences'] ?? 0)) <= 1 && $this->endDate !== null) { $this->carbonRecurrences = null; } } catch (Throwable $e) { // @codeCoverageIgnoreStart if (!method_exists(parent::class, '__unserialize')) { throw $e; } parent::__unserialize($data); // @codeCoverageIgnoreEnd } } /** * Update properties after removing built-in filters. */ protected function updateInternalState(): void { if (!$this->hasFilter(static::END_DATE_FILTER)) { $this->endDate = null; } if (!$this->hasFilter(static::RECURRENCES_FILTER)) { $this->carbonRecurrences = null; } } /** * Create a filter tuple from raw parameters. * * Will create an automatic filter callback for one of Carbon's is* methods. */ protected function createFilterTuple(array $parameters): array { $method = array_shift($parameters); if (!$this->isCarbonPredicateMethod($method)) { return [$method, array_shift($parameters)]; } return [static fn ($date) => ([$date, $method])(...$parameters), $method]; } /** * Return whether given callable is a string pointing to one of Carbon's is* methods * and should be automatically converted to a filter callback. */ protected function isCarbonPredicateMethod(callable|string $callable): bool { return \is_string($callable) && str_starts_with($callable, 'is') && (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable)); } /** * Recurrences filter callback (limits number of recurrences). * * @SuppressWarnings(UnusedFormalParameter) */ protected function filterRecurrences(CarbonInterface $current, int $key): bool|callable { if ($key < $this->carbonRecurrences) { return true; } return static::END_ITERATION; } /** * End date filter callback. * * @return bool|static::END_ITERATION */ protected function filterEndDate(CarbonInterface $current): bool|callable { if (!$this->isEndExcluded() && $current == $this->endDate) { return true; } if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) { return true; } return static::END_ITERATION; } /** * End iteration filter callback. * * @return static::END_ITERATION */ protected function endIteration(): callable { return static::END_ITERATION; } /** * Handle change of the parameters. */ protected function handleChangedParameters(): void { if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { $this->dateClass = CarbonImmutable::class; } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { $this->dateClass = Carbon::class; } $this->validationResult = null; } /** * Validate current date and stop iteration when necessary. * * Returns true when current date is valid, false if it is not, or static::END_ITERATION * when iteration should be stopped. * * @return bool|static::END_ITERATION */ protected function validateCurrentDate(): bool|callable { if ($this->carbonCurrent === null) { $this->rewind(); } // Check after the first rewind to avoid repeating the initial validation. return $this->validationResult ?? ($this->validationResult = $this->checkFilters()); } /** * Check whether current value and key pass all the filters. * * @return bool|static::END_ITERATION */ protected function checkFilters(): bool|callable { $current = $this->prepareForReturn($this->carbonCurrent); foreach ($this->filters as $tuple) { $result = \call_user_func($tuple[0], $current->avoidMutation(), $this->key, $this); if ($result === static::END_ITERATION) { return static::END_ITERATION; } if (!$result) { return false; } } return true; } /** * Prepare given date to be returned to the external logic. * * @param CarbonInterface $date * * @return CarbonInterface */ protected function prepareForReturn(CarbonInterface $date) { $date = ([$this->dateClass, 'make'])($date); if ($this->timezone) { return $date->setTimezone($this->timezone); } return $date; } /** * Keep incrementing the current date until a valid date is found or the iteration is ended. * * @throws RuntimeException */ protected function incrementCurrentDateUntilValid(): void { $attempts = 0; do { $this->carbonCurrent = $this->carbonCurrent->add($this->dateInterval); $this->validationResult = null; if (++$attempts > static::NEXT_MAX_ATTEMPTS) { throw new UnreachableException('Could not find next valid date.'); } } while ($this->validateCurrentDate() === false); } /** * Call given macro. */ protected function callMacro(string $name, array $parameters): mixed { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date * * @return \Carbon\CarbonInterface */ protected function resolveCarbon($date = null) { return $this->getStartDate()->nowWithSameTz()->carbonize($date); } /** * Resolve passed arguments or DatePeriod to a CarbonPeriod object. */ protected function resolveCarbonPeriod(mixed $period, mixed ...$arguments): self { if ($period instanceof self) { return $period; } return $period instanceof DatePeriod ? static::instance($period) : static::create($period, ...$arguments); } private function orderCouple($first, $second): array { return $first > $second ? [$second, $first] : [$first, $second]; } private function makeDateTime($value): ?DateTimeInterface { if ($value instanceof DateTimeInterface) { return $value; } if ($value instanceof WeekDay || $value instanceof Month) { $dateClass = $this->dateClass; return new $dateClass($value, $this->timezoneSetting); } if (\is_string($value)) { $value = trim($value); if (!preg_match('/^P[\dT]/', $value) && !preg_match('/^R\d/', $value) && preg_match('/[a-z\d]/i', $value) ) { $dateClass = $this->dateClass; return $dateClass::parse($value, $this->timezoneSetting); } } return null; } private function isInfiniteDate($date): bool { return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); } private function rawDate($date): ?DateTimeInterface { if ($date === false || $date === null) { return null; } if ($date instanceof CarbonInterface) { return $date->isMutable() ? $date->toDateTime() : $date->toDateTimeImmutable(); } if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { return $date; } $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); } private static function setDefaultParameters(array &$parameters, array $defaults): void { foreach ($defaults as [$index, $name, $value]) { if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { $parameters[$index] = $value; } } } private function setFromAssociativeArray(array $parameters): void { if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['end'])) { $this->setEndDate($parameters['end']); } if (isset($parameters['recurrences'])) { $this->setRecurrences($parameters['recurrences']); } if (isset($parameters['interval'])) { $this->setDateInterval($parameters['interval']); } if (isset($parameters['options'])) { $this->setOptions($parameters['options']); } } private function configureTimezone(DateTimeZone $timezone, array $sortedArguments, array $originalArguments): array { $this->setTimezone($timezone); if (\is_string($originalArguments['start'] ?? null)) { $sortedArguments['start'] = $this->makeDateTime($originalArguments['start']); } if (\is_string($originalArguments['end'] ?? null)) { $sortedArguments['end'] = $this->makeDateTime($originalArguments['end']); } return $sortedArguments; } private function initializeSerialization(array $values): void { $serializationBase = [ 'start' => $values['start'] ?? $values['startDate'] ?? null, 'current' => $values['current'] ?? $values['carbonCurrent'] ?? null, 'end' => $values['end'] ?? $values['endDate'] ?? null, 'interval' => $values['interval'] ?? $values['dateInterval'] ?? null, 'recurrences' => max(1, (int) ($values['recurrences'] ?? $values['carbonRecurrences'] ?? 1)), 'include_start_date' => $values['include_start_date'] ?? true, 'include_end_date' => $values['include_end_date'] ?? false, ]; foreach (['start', 'current', 'end'] as $dateProperty) { if ($serializationBase[$dateProperty] instanceof Carbon) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTime(); } elseif ($serializationBase[$dateProperty] instanceof CarbonInterface) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTimeImmutable(); } } if ($serializationBase['interval'] instanceof CarbonInterval) { $serializationBase['interval'] = $serializationBase['interval']->toDateInterval(); } // @codeCoverageIgnoreStart if (method_exists(parent::class, '__unserialize')) { parent::__unserialize($serializationBase); return; } $excludeStart = !($values['include_start_date'] ?? true); $includeEnd = $values['include_end_date'] ?? true; parent::__construct( $serializationBase['start'], $serializationBase['interval'], $serializationBase['end'] ?? $serializationBase['recurrences'], ($excludeStart ? self::EXCLUDE_START_DATE : 0) | ($includeEnd && \defined('DatePeriod::INCLUDE_END_DATE') ? self::INCLUDE_END_DATE : 0), ); // @codeCoverageIgnoreEnd } }
PHP
{ "end_line": 1172, "name": "removeFilter", "signature": "public function removeFilter(callable|string $filter): static", "start_line": 1157 }
{ "class_name": "CarbonPeriod", "class_signature": "class CarbonPeriod implements Countable, JsonSerializable, UnitValue", "namespace": "Carbon" }
hasFilter
Carbon/src/Carbon/CarbonPeriod.php
public function hasFilter(callable|string $filter): bool { $key = \is_callable($filter) ? 0 : 1; foreach ($this->filters as $tuple) { if ($tuple[$key] === $filter) { return true; } } return false; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotACarbonClassException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnreachableException; use Carbon\Traits\DeprecatedPeriodProperties; use Carbon\Traits\IntervalRounding; use Carbon\Traits\LocalFactory; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Throwable; // @codeCoverageIgnoreStart require PHP_VERSION < 8.2 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php' : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php'; // @codeCoverageIgnoreEnd /** * Substitution of DatePeriod with some modifications and many more features. * * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. * @method static static since($date = null, $inclusive = null) Alias for start(). * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. * @method static static until($date = null, $inclusive = null) Alias for end(). * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. * @method static static times($recurrences = null) Alias for recurrences(). * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance. * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. * @method static static push($callback, $name = null) Alias for filter(). * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance. * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. * @method static static year($years = 1) Alias for years(). * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. * @method static static month($months = 1) Alias for months(). * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. * @method static static week($weeks = 1) Alias for weeks(). * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. * @method static static dayz($days = 1) Alias for days(). * @method static static day($days = 1) Alias for days(). * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. * @method static static hour($hours = 1) Alias for hours(). * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. * @method static static minute($minutes = 1) Alias for minutes(). * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. * @method static static second($seconds = 1) Alias for seconds(). * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * * @mixin DeprecatedPeriodProperties * * @SuppressWarnings(TooManyFields) * @SuppressWarnings(CamelCasePropertyName) * @SuppressWarnings(CouplingBetweenObjects) */ class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue { use LocalFactory; use IntervalRounding; use Mixin { Mixin::mixin as baseMixin; } use Options { Options::__debugInfo as baseDebugInfo; } use ToStringFormat; /** * Built-in filter for limit by recurrences. * * @var callable */ public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; /** * Built-in filter for limit to an end. * * @var callable */ public const END_DATE_FILTER = [self::class, 'filterEndDate']; /** * Special value which can be returned by filters to end iteration. Also a filter. * * @var callable */ public const END_ITERATION = [self::class, 'endIteration']; /** * Exclude end date from iteration. * * @var int */ public const EXCLUDE_END_DATE = 8; /** * Yield CarbonImmutable instances. * * @var int */ public const IMMUTABLE = 4; /** * Number of maximum attempts before giving up on finding next valid date. * * @var int */ public const NEXT_MAX_ATTEMPTS = 1000; /** * Number of maximum attempts before giving up on finding end date. * * @var int */ public const END_MAX_ATTEMPTS = 10000; /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = Carbon::class; /** * The registered macros. */ protected static array $macros = []; /** * Date class of iteration items. */ protected string $dateClass = Carbon::class; /** * Underlying date interval instance. Always present, one day by default. */ protected ?CarbonInterval $dateInterval = null; /** * True once __construct is finished. */ protected bool $constructed = false; /** * Whether current date interval was set by default. */ protected bool $isDefaultInterval = false; /** * The filters stack. */ protected array $filters = []; /** * Period start date. Applied on rewind. Always present, now by default. */ protected ?CarbonInterface $startDate = null; /** * Period end date. For inverted interval should be before the start date. Applied via a filter. */ protected ?CarbonInterface $endDate = null; /** * Limit for number of recurrences. Applied via a filter. */ protected int|float|null $carbonRecurrences = null; /** * Iteration options. */ protected ?int $options = null; /** * Index of current date. Always sequential, even if some dates are skipped by filters. * Equal to null only before the first iteration. */ protected int $key = 0; /** * Current date. May temporarily hold unaccepted value when looking for a next valid date. * Equal to null only before the first iteration. */ protected ?CarbonInterface $carbonCurrent = null; /** * Timezone of current date. Taken from the start date. */ protected ?DateTimeZone $timezone = null; /** * The cached validation result for current date. */ protected array|string|bool|null $validationResult = null; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; public function getIterator(): Generator { $this->rewind(); while ($this->valid()) { $key = $this->key(); $value = $this->current(); yield $key => $value; $this->next(); } } /** * Make a CarbonPeriod instance from given variable if possible. */ public static function make(mixed $var): ?static { try { return static::instance($var); } catch (NotAPeriodException) { return static::create($var); } } /** * Create a new instance from a DatePeriod or CarbonPeriod object. */ public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); } /** * Create a new instance. */ public static function create(...$params): static { return static::createFromArray($params); } /** * Create a new instance from an array of parameters. */ public static function createFromArray(array $params): static { return new static(...$params); } /** * Create CarbonPeriod from ISO 8601 string. */ public static function createFromIso(string $iso, ?int $options = null): static { $params = static::parseIso8601($iso); $instance = static::createFromArray($params); $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options; $instance->handleChangedParameters(); return $instance; } public static function createFromISO8601String(string $iso, ?int $options = null): static { return self::createFromIso($iso, $options); } /** * Return whether the given interval contains non-zero value of any time unit. */ protected static function intervalHasTime(DateInterval $interval): bool { return $interval->h || $interval->i || $interval->s || $interval->f; } /** * Return whether given variable is an ISO 8601 specification. * * Note: Check is very basic, as actual validation will be done later when parsing. * We just want to ensure that variable is not any other type of valid parameter. */ protected static function isIso8601(mixed $var): bool { if (!\is_string($var)) { return false; } // Match slash but not within a timezone name. $part = '[a-z]+(?:[_-][a-z]+)*'; preg_match("#\b$part/$part\b|(/)#i", $var, $match); return isset($match[1]); } /** * Parse given ISO 8601 string into an array of arguments. * * @SuppressWarnings(ElseExpression) */ protected static function parseIso8601(string $iso): array { $result = []; $interval = null; $start = null; $end = null; $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = self::makeInterval($part)) { $interval = $part; } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); } $result[] = $parsed; } return $result; } /** * Add missing parts of the target date from the source date. */ protected static function addMissingParts(string $source, string $target): string { $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); return $count ? $result : $target; } private static function makeInterval(mixed $input): ?CarbonInterval { try { return CarbonInterval::make($input); } catch (Throwable) { return null; } } private static function makeTimezone(mixed $input): ?CarbonTimeZone { if (!\is_string($input)) { return null; } try { return CarbonTimeZone::create($input); } catch (Throwable) { return null; } } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonPeriod::macro('middle', function () { * return $this->getStartDate()->average($this->getEndDate()); * }); * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonPeriod::mixin(new class { * public function addDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->addDays($count) * )->setEndDate( * $this->getEndDate()->addDays($count) * ); * }; * } * public function subDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->subDays($count) * )->setEndDate( * $this->getEndDate()->subDays($count) * ); * }; * } * }); * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); * ``` * * @throws ReflectionException */ public static function mixin(object|string $mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Provide static proxy for instance aliases. */ public static function __callStatic(string $method, array $parameters): mixed { $date = new static(); if (static::hasMacro($method)) { return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters)); } return $date->$method(...$parameters); } /** * CarbonPeriod constructor. * * @SuppressWarnings(ElseExpression) * * @throws InvalidArgumentException */ public function __construct(...$arguments) { $raw = null; if (isset($arguments['raw'])) { $raw = $arguments['raw']; $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false; if (isset($arguments['dateClass'])) { $this->dateClass = $arguments['dateClass']; } $arguments = $raw; } // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. $argumentsCount = \count($arguments); if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { array_splice($arguments, 0, 1, static::parseIso8601($iso)); } if ($argumentsCount === 1) { if ($arguments[0] instanceof self) { $arguments = [ $arguments[0]->getStartDate(), $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(), $arguments[0]->getDateInterval(), $arguments[0]->getOptions(), ]; } elseif ($arguments[0] instanceof DatePeriod) { $arguments = [ $arguments[0]->start, $arguments[0]->end ?: ($arguments[0]->recurrences - 1), $arguments[0]->interval, $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, ]; } } if (is_a($this->dateClass, DateTimeImmutable::class, true)) { $this->options = static::IMMUTABLE; } $optionsSet = false; $originalArguments = []; $sortedArguments = []; foreach ($arguments as $argument) { $parsedDate = null; if ($argument instanceof DateTimeZone) { $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments); } elseif (!isset($sortedArguments['interval']) && ( (\is_string($argument) && preg_match( '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument, )) || $argument instanceof DateInterval || $argument instanceof Closure || $argument instanceof Unit ) && $parsedInterval = self::makeInterval($argument) ) { $sortedArguments['interval'] = $parsedInterval; } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) { $sortedArguments['start'] = $parsedDate; $originalArguments['start'] = $argument; } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { $sortedArguments['end'] = $parsedDate; $originalArguments['end'] = $argument; } elseif (!isset($sortedArguments['recurrences']) && !isset($sortedArguments['end']) && (\is_int($argument) || \is_float($argument)) && $argument >= 0 ) { $sortedArguments['recurrences'] = $argument; } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { $optionsSet = true; $sortedArguments['options'] = (((int) $this->options) | ((int) $argument)); } elseif ($parsedTimezone = self::makeTimezone($argument)) { $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($raw === null && isset($sortedArguments['start'])) { $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1); if (\is_float($end)) { $end = $end === INF ? PHP_INT_MAX : (int) round($end); } $raw = [ $sortedArguments['start'], $sortedArguments['interval'] ?? CarbonInterval::day(), $end, ]; } $this->setFromAssociativeArray($sortedArguments); if ($this->startDate === null) { $dateClass = $this->dateClass; $this->setStartDate($dateClass::now()); } if ($this->dateInterval === null) { $this->setDateInterval(CarbonInterval::day()); $this->isDefaultInterval = true; } if ($this->options === null) { $this->setOptions(0); } parent::__construct( $this->startDate, $this->dateInterval, $this->endDate ?? max(1, min(2147483639, $this->recurrences ?? 1)), $this->options, ); $this->constructed = true; } /** * Get a copy of the instance. */ public function copy(): static { return clone $this; } /** * Prepare the instance to be set (self if mutable to be mutated, * copy if immutable to generate a new instance). */ protected function copyIfImmutable(): static { return $this; } /** * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. */ protected function getGetter(string $name): ?callable { return match (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) { 'start', 'start_date' => [$this, 'getStartDate'], 'end', 'end_date' => [$this, 'getEndDate'], 'interval', 'date_interval' => [$this, 'getDateInterval'], 'recurrences' => [$this, 'getRecurrences'], 'include_start_date' => [$this, 'isStartIncluded'], 'include_end_date' => [$this, 'isEndIncluded'], 'current' => [$this, 'current'], 'locale' => [$this, 'locale'], 'tzname', 'tz_name' => fn () => match (true) { $this->timezoneSetting === null => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, $this->timezoneSetting instanceof DateTimeZone => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, default => null, }; } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function get(string $name) { $getter = $this->getGetter($name); if ($getter) { return $getter(); } throw new UnknownGetterException($name); } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function __get(string $name) { return $this->get($name); } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset(string $name): bool { return $this->getGetter($name) !== null; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Set the iteration item class. * * @param string $dateClass * * @return static */ public function setDateClass(string $dateClass) { if (!is_a($dateClass, CarbonInterface::class, true)) { throw new NotACarbonClassException($dateClass); } $self = $this->copyIfImmutable(); $self->dateClass = $dateClass; if (is_a($dateClass, Carbon::class, true)) { $self->options = $self->options & ~static::IMMUTABLE; } elseif (is_a($dateClass, CarbonImmutable::class, true)) { $self->options = $self->options | static::IMMUTABLE; } return $self; } /** * Returns iteration item date class. * * @return string */ public function getDateClass(): string { return $this->dateClass; } /** * Change the period date interval. * * @param DateInterval|Unit|string|int $interval * @param Unit|string $unit the unit of $interval if it's a number * * @throws InvalidIntervalException * * @return static */ public function setDateInterval(mixed $interval, Unit|string|null $unit = null): static { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->name; } if (!$interval = CarbonInterval::make($interval, $unit)) { throw new InvalidIntervalException('Invalid interval.'); } if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) { throw new InvalidIntervalException('Empty interval is not accepted.'); } $self = $this->copyIfImmutable(); $self->dateInterval = $interval; $self->isDefaultInterval = false; $self->handleChangedParameters(); return $self; } /** * Reset the date interval to the default value. * * Difference with simply setting interval to 1-day is that P1D will not appear when calling toIso8601String() * and also next adding to the interval won't include the default 1-day. */ public function resetDateInterval(): static { $self = $this->copyIfImmutable(); $self->setDateInterval(CarbonInterval::day()); $self->isDefaultInterval = true; return $self; } /** * Invert the period date interval. */ public function invertDateInterval(): static { return $this->setDateInterval($this->dateInterval->invert()); } /** * Set start and end date. * * @param DateTime|DateTimeInterface|string $start * @param DateTime|DateTimeInterface|string|null $end * * @return static */ public function setDates(mixed $start, mixed $end): static { return $this->setStartDate($start)->setEndDate($end); } /** * Change the period options. * * @param int|null $options * * @return static */ public function setOptions(?int $options): static { $self = $this->copyIfImmutable(); $self->options = $options ?? 0; $self->handleChangedParameters(); return $self; } /** * Get the period options. */ public function getOptions(): int { return $this->options ?? 0; } /** * Toggle given options on or off. * * @param int $options * @param bool|null $state * * @throws InvalidArgumentException * * @return static */ public function toggleOptions(int $options, ?bool $state = null): static { $self = $this->copyIfImmutable(); if ($state === null) { $state = ($this->options & $options) !== $options; } return $self->setOptions( $state ? $this->options | $options : $this->options & ~$options, ); } /** * Toggle EXCLUDE_START_DATE option. */ public function excludeStartDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_START_DATE, $state); } /** * Toggle EXCLUDE_END_DATE option. */ public function excludeEndDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_END_DATE, $state); } /** * Get the underlying date interval. */ public function getDateInterval(): CarbonInterval { return $this->dateInterval->copy(); } /** * Get start date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getStartDate(?string $rounding = null): CarbonInterface { $date = $this->startDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get end date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getEndDate(?string $rounding = null): ?CarbonInterface { if (!$this->endDate) { return null; } $date = $this->endDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get number of recurrences. */ #[ReturnTypeWillChange] public function getRecurrences(): int|float|null { return $this->carbonRecurrences; } /** * Returns true if the start date should be excluded. */ public function isStartExcluded(): bool { return ($this->options & static::EXCLUDE_START_DATE) !== 0; } /** * Returns true if the end date should be excluded. */ public function isEndExcluded(): bool { return ($this->options & static::EXCLUDE_END_DATE) !== 0; } /** * Returns true if the start date should be included. */ public function isStartIncluded(): bool { return !$this->isStartExcluded(); } /** * Returns true if the end date should be included. */ public function isEndIncluded(): bool { return !$this->isEndExcluded(); } /** * Return the start if it's included by option, else return the start + 1 period interval. */ public function getIncludedStartDate(): CarbonInterface { $start = $this->getStartDate(); if ($this->isStartExcluded()) { return $start->add($this->getDateInterval()); } return $start; } /** * Return the end if it's included by option, else return the end - 1 period interval. * Warning: if the period has no fixed end, this method will iterate the period to calculate it. */ public function getIncludedEndDate(): CarbonInterface { $end = $this->getEndDate(); if (!$end) { return $this->calculateEnd(); } if ($this->isEndExcluded()) { return $end->sub($this->getDateInterval()); } return $end; } /** * Add a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function addFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); $self->filters[] = $tuple; $self->handleChangedParameters(); return $self; } /** * Prepend a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function prependFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); array_unshift($self->filters, $tuple); $self->handleChangedParameters(); return $self; } /** * Remove a filter by instance or name. */ public function removeFilter(callable|string $filter): static { $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; $self->filters = array_values(array_filter( $this->filters, static fn ($tuple) => $tuple[$key] !== $filter, )); $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Return whether given instance or name is in the filter stack. */ public function hasFilter(callable|string $filter): bool { $key = \is_callable($filter) ? 0 : 1; foreach ($this->filters as $tuple) { if ($tuple[$key] === $filter) { return true; } } return false; } /** * Get filters stack. */ public function getFilters(): array { return $this->filters; } /** * Set filters stack. */ public function setFilters(array $filters): static { $self = $this->copyIfImmutable(); $self->filters = $filters; $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Reset filters stack. */ public function resetFilters(): static { $self = $this->copyIfImmutable(); $self->filters = []; if ($self->endDate !== null) { $self->filters[] = [static::END_DATE_FILTER, null]; } if ($self->carbonRecurrences !== null) { $self->filters[] = [static::RECURRENCES_FILTER, null]; } $self->handleChangedParameters(); return $self; } /** * Add a recurrences filter (set maximum number of recurrences). * * @throws InvalidArgumentException */ public function setRecurrences(int|float|null $recurrences): static { if ($recurrences === null) { return $this->removeFilter(static::RECURRENCES_FILTER); } if ($recurrences < 0) { throw new InvalidPeriodParameterException('Invalid number of recurrences.'); } /** @var self $self */ $self = $this->copyIfImmutable(); $self->carbonRecurrences = $recurrences === INF ? INF : (int) $recurrences; if (!$self->hasFilter(static::RECURRENCES_FILTER)) { return $self->addFilter(static::RECURRENCES_FILTER); } $self->handleChangedParameters(); return $self; } /** * Change the period start date. * * @param DateTime|DateTimeInterface|string $date * @param bool|null $inclusive * * @throws InvalidPeriodDateException * * @return static */ public function setStartDate(mixed $date, ?bool $inclusive = null): static { if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date, $this->timezone))) { throw new InvalidPeriodDateException('Invalid start date.'); } $self = $this->copyIfImmutable(); $self->startDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); } return $self; } /** * Change the period end date. * * @param DateTime|DateTimeInterface|string|null $date * @param bool|null $inclusive * * @throws \InvalidArgumentException * * @return static */ public function setEndDate(mixed $date, ?bool $inclusive = null): static { if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date, $this->timezone)) { throw new InvalidPeriodDateException('Invalid end date.'); } if (!$date) { return $this->removeFilter(static::END_DATE_FILTER); } $self = $this->copyIfImmutable(); $self->endDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); } if (!$self->hasFilter(static::END_DATE_FILTER)) { return $self->addFilter(static::END_DATE_FILTER); } $self->handleChangedParameters(); return $self; } /** * Check if the current position is valid. */ public function valid(): bool { return $this->validateCurrentDate() === true; } /** * Return the current key. */ public function key(): ?int { return $this->valid() ? $this->key : null; } /** * Return the current date. */ public function current(): ?CarbonInterface { return $this->valid() ? $this->prepareForReturn($this->carbonCurrent) : null; } /** * Move forward to the next date. * * @throws RuntimeException */ public function next(): void { if ($this->carbonCurrent === null) { $this->rewind(); } if ($this->validationResult !== static::END_ITERATION) { $this->key++; $this->incrementCurrentDateUntilValid(); } } /** * Rewind to the start date. * * Iterating over a date in the UTC timezone avoids bug during backward DST change. * * @see https://bugs.php.net/bug.php?id=72255 * @see https://bugs.php.net/bug.php?id=74274 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time * * @throws RuntimeException */ public function rewind(): void { $this->key = 0; $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate); $settings = $this->getSettings(); if ($this->hasLocalTranslator()) { $settings['locale'] = $this->getTranslatorLocale(); } $this->carbonCurrent->settings($settings); $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null; if ($this->timezone) { $this->carbonCurrent = $this->carbonCurrent->utc(); } $this->validationResult = null; if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { $this->incrementCurrentDateUntilValid(); } } /** * Skip iterations and returns iteration state (false if ended, true if still valid). * * @param int $count steps number to skip (1 by default) * * @return bool */ public function skip(int $count = 1): bool { for ($i = $count; $this->valid() && $i > 0; $i--) { $this->next(); } return $this->valid(); } /** * Format the date period as ISO 8601. */ public function toIso8601String(): string { $parts = []; if ($this->carbonRecurrences !== null) { $parts[] = 'R'.$this->carbonRecurrences; } $parts[] = $this->startDate->toIso8601String(); if (!$this->isDefaultInterval) { $parts[] = $this->dateInterval->spec(); } if ($this->endDate !== null) { $parts[] = $this->endDate->toIso8601String(); } return implode('/', $parts); } /** * Convert the date period into a string. */ public function toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if ($format instanceof Closure) { return $format($this); } $translator = ([$this->dateClass, 'getTranslator'])(); $parts = []; $format = $format ?? ( !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) ? 'Y-m-d H:i:s' : 'Y-m-d' ); if ($this->carbonRecurrences !== null) { $parts[] = $this->translate('period_recurrences', [], $this->carbonRecurrences, $translator); } $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([ 'join' => true, ])], null, $translator); $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator); if ($this->endDate !== null) { $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator); } $result = implode(' ', $parts); return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1); } /** * Format the date period as ISO 8601. */ public function spec(): string { return $this->toIso8601String(); } /** * Cast the current instance into the given class. * * @param string $className The $className::instance() method will be called to cast the current object. * * @return DatePeriod|object */ public function cast(string $className): object { if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( $this->rawDate($this->getStartDate()), $this->getDateInterval(), $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0, ); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Return native DatePeriod PHP object matching the current instance. * * @example * ``` * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod()); * ``` */ public function toDatePeriod(): DatePeriod { return $this->cast(DatePeriod::class); } /** * Return `true` if the period has no custom filter and is guaranteed to be endless. * * Note that we can't check if a period is endless as soon as it has custom filters * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in * a way we can't predict without actually iterating the period. */ public function isUnfilteredAndEndLess(): bool { foreach ($this->filters as $filter) { switch ($filter) { case [static::RECURRENCES_FILTER, null]: if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) { return false; } break; case [static::END_DATE_FILTER, null]: if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { return false; } break; default: return false; } } return true; } /** * Convert the date period into an array without changing current iteration state. * * @return CarbonInterface[] */ public function toArray(): array { if ($this->isUnfilteredAndEndLess()) { throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); } $state = [ $this->key, $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null, $this->validationResult, ]; $result = iterator_to_array($this); [$this->key, $this->carbonCurrent, $this->validationResult] = $state; return $result; } /** * Count dates in the date period. */ public function count(): int { return \count($this->toArray()); } /** * Return the first date in the date period. */ public function first(): ?CarbonInterface { if ($this->isUnfilteredAndEndLess()) { foreach ($this as $date) { $this->rewind(); return $date; } return null; } return ($this->toArray() ?: [])[0] ?? null; } /** * Return the last date in the date period. */ public function last(): ?CarbonInterface { $array = $this->toArray(); return $array ? $array[\count($array) - 1] : null; } /** * Convert the date period into a string. */ public function __toString(): string { return $this->toString(); } /** * Add aliases for setters. * * CarbonPeriod::days(3)->hours(5)->invert() * ->sinceNow()->until('2010-01-10') * ->filter(...) * ->count() * * Note: We use magic method to let static and instance aliases with the same names. */ public function __call(string $method, array $parameters): mixed { if (static::hasMacro($method)) { return static::bindMacroContext($this, fn () => $this->callMacro($method, $parameters)); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } $count = \count($parameters); switch ($method) { case 'start': case 'since': if ($count === 0) { return $this->getStartDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setStartDate(...$parameters); case 'sinceNow': return $this->setStartDate(new Carbon(), ...$parameters); case 'end': case 'until': if ($count === 0) { return $this->getEndDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setEndDate(...$parameters); case 'untilNow': return $this->setEndDate(new Carbon(), ...$parameters); case 'dates': case 'between': self::setDefaultParameters($parameters, [ [0, 'start', null], [1, 'end', null], ]); return $this->setDates(...$parameters); case 'recurrences': case 'times': if ($count === 0) { return $this->getRecurrences(); } self::setDefaultParameters($parameters, [ [0, 'recurrences', null], ]); return $this->setRecurrences(...$parameters); case 'options': if ($count === 0) { return $this->getOptions(); } self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->setOptions(...$parameters); case 'toggle': self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->toggleOptions(...$parameters); case 'filter': case 'push': return $this->addFilter(...$parameters); case 'prepend': return $this->prependFilter(...$parameters); case 'filters': if ($count === 0) { return $this->getFilters(); } self::setDefaultParameters($parameters, [ [0, 'filters', []], ]); return $this->setFilters(...$parameters); case 'interval': case 'each': case 'every': case 'step': case 'stepBy': if ($count === 0) { return $this->getDateInterval(); } return $this->setDateInterval(...$parameters); case 'invert': return $this->invertDateInterval(); case 'years': case 'year': case 'months': case 'month': case 'weeks': case 'week': case 'days': case 'dayz': case 'day': case 'hours': case 'hour': case 'minutes': case 'minute': case 'seconds': case 'second': case 'milliseconds': case 'millisecond': case 'microseconds': case 'microsecond': return $this->setDateInterval(( // Override default P1D when instantiating via fluent setters. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] )(...$parameters)); } $dateClass = $this->dateClass; if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { throw new UnknownMethodException($method); } return $this; } /** * Set the instance's timezone from a string or object and apply it to start/end. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->setTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->setTimezone($timezone)); } return $self; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } return $self; } /** * Returns the end is set, else calculated from start and recurrences. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. * * @return CarbonInterface */ public function calculateEnd(?string $rounding = null): CarbonInterface { if ($end = $this->getEndDate($rounding)) { return $end; } if ($this->dateInterval->isEmpty()) { return $this->getStartDate($rounding); } $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); if ($date && $rounding) { $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); } return $date; } private function getEndFromRecurrences(): ?CarbonInterface { if ($this->carbonRecurrences === null) { throw new UnreachableException( "Could not calculate period end without either explicit end or recurrences.\n". "If you're looking for a forever-period, use ->setRecurrences(INF).", ); } if ($this->carbonRecurrences === INF) { $start = $this->getStartDate(); return $start < $start->avoidMutation()->add($this->getDateInterval()) ? CarbonImmutable::endOfTime() : CarbonImmutable::startOfTime(); } if ($this->filters === [[static::RECURRENCES_FILTER, null]]) { return $this->getStartDate()->avoidMutation()->add( $this->getDateInterval()->times( $this->carbonRecurrences - ($this->isStartExcluded() ? 0 : 1), ), ); } return null; } private function iterateUntilEnd(): ?CarbonInterface { $attempts = 0; $date = null; foreach ($this as $date) { if (++$attempts > static::END_MAX_ATTEMPTS) { throw new UnreachableException( 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.', ); } } return $date; } /** * Returns true if the current period overlaps the given one (if 1 parameter passed) * or the period between 2 dates (if 2 parameters passed). * * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd * * @return bool */ public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool { $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; if (!($range instanceof self)) { $range = static::create($range); } [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); return $end > $rangeStart && $rangeEnd > $start; } /** * Execute a given function on each date of the period. * * @example * ``` * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) { * echo $date->diffInDays('2020-12-25')." days before Christmas!\n"; * }); * ``` */ public function forEach(callable $callback): void { foreach ($this as $date) { $callback($date); } } /** * Execute a given function on each date of the period and yield the result of this function. * * @example * ``` * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24'); * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) { * return $date->diffInDays('2020-12-25').' days before Christmas!'; * }))); * ``` */ public function map(callable $callback): Generator { foreach ($this as $date) { yield $callback($date); } } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. * * @see equalTo() */ public function eq(mixed $period): bool { return $this->equalTo($period); } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. */ public function equalTo(mixed $period): bool { if (!($period instanceof self)) { $period = self::make($period); } $end = $this->getEndDate(); return $period !== null && $this->getDateInterval()->eq($period->getDateInterval()) && $this->getStartDate()->eq($period->getStartDate()) && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. * * @see notEqualTo() */ public function ne(mixed $period): bool { return $this->notEqualTo($period); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. */ public function notEqualTo(mixed $period): bool { return !$this->eq($period); } /** * Determines if the start date is before another given date. * (Rather start/end are included by options is ignored.) */ public function startsBefore(mixed $date = null): bool { return $this->getStartDate()->lessThan($this->resolveCarbon($date)); } /** * Determines if the start date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsBeforeOrAt(mixed $date = null): bool { return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is after another given date. * (Rather start/end are included by options is ignored.) */ public function startsAfter(mixed $date = null): bool { return $this->getStartDate()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the start date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAfterOrAt(mixed $date = null): bool { return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAt(mixed $date = null): bool { return $this->getStartDate()->equalTo($this->resolveCarbon($date)); } /** * Determines if the end date is before another given date. * (Rather start/end are included by options is ignored.) */ public function endsBefore(mixed $date = null): bool { return $this->calculateEnd()->lessThan($this->resolveCarbon($date)); } /** * Determines if the end date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsBeforeOrAt(mixed $date = null): bool { return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is after another given date. * (Rather start/end are included by options is ignored.) */ public function endsAfter(mixed $date = null): bool { return $this->calculateEnd()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the end date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAfterOrAt(mixed $date = null): bool { return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAt(mixed $date = null): bool { return $this->calculateEnd()->equalTo($this->resolveCarbon($date)); } /** * Return true if start date is now or later. * (Rather start/end are included by options is ignored.) */ public function isStarted(): bool { return $this->startsBeforeOrAt(); } /** * Return true if end date is now or later. * (Rather start/end are included by options is ignored.) */ public function isEnded(): bool { return $this->endsBeforeOrAt(); } /** * Return true if now is between start date (included) and end date (excluded). * (Rather start/end are included by options is ignored.) */ public function isInProgress(): bool { return $this->isStarted() && !$this->isEnded(); } /** * Round the current instance at the given unit with given precision if specified and the given function. */ public function roundUnit( string $unit, DateInterval|float|int|string|null $precision = 1, callable|string $function = 'round', ): static { $self = $this->copyIfImmutable(); $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); if ($self->endDate) { $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); } /** * Truncate the current instance at the given unit with given precision if specified. */ public function floorUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. */ public function ceilUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function round( DateInterval|float|int|string|null $precision = null, callable|string $function = 'round', ): static { return $this->roundWith( $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(), $function ); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function floor(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified (else period interval is used). */ public function ceil(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'ceil'); } /** * Specify data which should be serialized to JSON. * * @link https://php.net/manual/en/jsonserializable.jsonserialize.php * * @return CarbonInterface[] */ public function jsonSerialize(): array { return $this->toArray(); } /** * Return true if the given date is between start and end. */ public function contains(mixed $date = null): bool { $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : ''); $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : ''); return $this->$startMethod($date) && $this->$endMethod($date); } /** * Return true if the current period follows a given other period (with no overlap). * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31] * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function follows(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval())); } /** * Return true if the given other period follows the current one (with no overlap). * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12] * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function isFollowedBy(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $period->follows($this); } /** * Return true if the given period either follows or is followed by the current one. * * @see follows() * @see isFollowedBy() */ public function isConsecutiveWith(mixed $period, mixed ...$arguments): bool { return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments); } public function __debugInfo(): array { $info = $this->baseDebugInfo(); unset( $info['start'], $info['end'], $info['interval'], $info['include_start_date'], $info['include_end_date'], $info['constructed'], $info["\0*\0constructed"], ); return $info; } public function __unserialize(array $data): void { try { $values = array_combine( array_map( static fn (string $key): string => preg_replace('/^\0\*\0/', '', $key), array_keys($data), ), $data, ); $this->initializeSerialization($values); foreach ($values as $key => $value) { if ($value === null) { continue; } $property = match ($key) { 'tzName' => $this->setTimezone(...), 'options' => $this->setOptions(...), 'recurrences' => $this->setRecurrences(...), 'current' => function (mixed $current): void { if (!($current instanceof CarbonInterface)) { $current = $this->resolveCarbon($current); } $this->carbonCurrent = $current; }, 'start' => 'startDate', 'interval' => $this->setDateInterval(...), 'end' => 'endDate', 'key' => null, 'include_start_date' => function (bool $included): void { $this->excludeStartDate(!$included); }, 'include_end_date' => function (bool $included): void { $this->excludeEndDate(!$included); }, default => $key, }; if ($property === null) { continue; } if (\is_callable($property)) { $property($value); continue; } if ($value instanceof DateTimeInterface && !($value instanceof CarbonInterface)) { $value = ($value instanceof DateTime) ? Carbon::instance($value) : CarbonImmutable::instance($value); } try { $this->$property = $value; } catch (Throwable) { // Must be ignored for backward-compatibility } } if (\array_key_exists('carbonRecurrences', $values)) { $this->carbonRecurrences = $values['carbonRecurrences']; } elseif (((int) ($values['recurrences'] ?? 0)) <= 1 && $this->endDate !== null) { $this->carbonRecurrences = null; } } catch (Throwable $e) { // @codeCoverageIgnoreStart if (!method_exists(parent::class, '__unserialize')) { throw $e; } parent::__unserialize($data); // @codeCoverageIgnoreEnd } } /** * Update properties after removing built-in filters. */ protected function updateInternalState(): void { if (!$this->hasFilter(static::END_DATE_FILTER)) { $this->endDate = null; } if (!$this->hasFilter(static::RECURRENCES_FILTER)) { $this->carbonRecurrences = null; } } /** * Create a filter tuple from raw parameters. * * Will create an automatic filter callback for one of Carbon's is* methods. */ protected function createFilterTuple(array $parameters): array { $method = array_shift($parameters); if (!$this->isCarbonPredicateMethod($method)) { return [$method, array_shift($parameters)]; } return [static fn ($date) => ([$date, $method])(...$parameters), $method]; } /** * Return whether given callable is a string pointing to one of Carbon's is* methods * and should be automatically converted to a filter callback. */ protected function isCarbonPredicateMethod(callable|string $callable): bool { return \is_string($callable) && str_starts_with($callable, 'is') && (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable)); } /** * Recurrences filter callback (limits number of recurrences). * * @SuppressWarnings(UnusedFormalParameter) */ protected function filterRecurrences(CarbonInterface $current, int $key): bool|callable { if ($key < $this->carbonRecurrences) { return true; } return static::END_ITERATION; } /** * End date filter callback. * * @return bool|static::END_ITERATION */ protected function filterEndDate(CarbonInterface $current): bool|callable { if (!$this->isEndExcluded() && $current == $this->endDate) { return true; } if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) { return true; } return static::END_ITERATION; } /** * End iteration filter callback. * * @return static::END_ITERATION */ protected function endIteration(): callable { return static::END_ITERATION; } /** * Handle change of the parameters. */ protected function handleChangedParameters(): void { if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { $this->dateClass = CarbonImmutable::class; } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { $this->dateClass = Carbon::class; } $this->validationResult = null; } /** * Validate current date and stop iteration when necessary. * * Returns true when current date is valid, false if it is not, or static::END_ITERATION * when iteration should be stopped. * * @return bool|static::END_ITERATION */ protected function validateCurrentDate(): bool|callable { if ($this->carbonCurrent === null) { $this->rewind(); } // Check after the first rewind to avoid repeating the initial validation. return $this->validationResult ?? ($this->validationResult = $this->checkFilters()); } /** * Check whether current value and key pass all the filters. * * @return bool|static::END_ITERATION */ protected function checkFilters(): bool|callable { $current = $this->prepareForReturn($this->carbonCurrent); foreach ($this->filters as $tuple) { $result = \call_user_func($tuple[0], $current->avoidMutation(), $this->key, $this); if ($result === static::END_ITERATION) { return static::END_ITERATION; } if (!$result) { return false; } } return true; } /** * Prepare given date to be returned to the external logic. * * @param CarbonInterface $date * * @return CarbonInterface */ protected function prepareForReturn(CarbonInterface $date) { $date = ([$this->dateClass, 'make'])($date); if ($this->timezone) { return $date->setTimezone($this->timezone); } return $date; } /** * Keep incrementing the current date until a valid date is found or the iteration is ended. * * @throws RuntimeException */ protected function incrementCurrentDateUntilValid(): void { $attempts = 0; do { $this->carbonCurrent = $this->carbonCurrent->add($this->dateInterval); $this->validationResult = null; if (++$attempts > static::NEXT_MAX_ATTEMPTS) { throw new UnreachableException('Could not find next valid date.'); } } while ($this->validateCurrentDate() === false); } /** * Call given macro. */ protected function callMacro(string $name, array $parameters): mixed { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date * * @return \Carbon\CarbonInterface */ protected function resolveCarbon($date = null) { return $this->getStartDate()->nowWithSameTz()->carbonize($date); } /** * Resolve passed arguments or DatePeriod to a CarbonPeriod object. */ protected function resolveCarbonPeriod(mixed $period, mixed ...$arguments): self { if ($period instanceof self) { return $period; } return $period instanceof DatePeriod ? static::instance($period) : static::create($period, ...$arguments); } private function orderCouple($first, $second): array { return $first > $second ? [$second, $first] : [$first, $second]; } private function makeDateTime($value): ?DateTimeInterface { if ($value instanceof DateTimeInterface) { return $value; } if ($value instanceof WeekDay || $value instanceof Month) { $dateClass = $this->dateClass; return new $dateClass($value, $this->timezoneSetting); } if (\is_string($value)) { $value = trim($value); if (!preg_match('/^P[\dT]/', $value) && !preg_match('/^R\d/', $value) && preg_match('/[a-z\d]/i', $value) ) { $dateClass = $this->dateClass; return $dateClass::parse($value, $this->timezoneSetting); } } return null; } private function isInfiniteDate($date): bool { return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); } private function rawDate($date): ?DateTimeInterface { if ($date === false || $date === null) { return null; } if ($date instanceof CarbonInterface) { return $date->isMutable() ? $date->toDateTime() : $date->toDateTimeImmutable(); } if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { return $date; } $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); } private static function setDefaultParameters(array &$parameters, array $defaults): void { foreach ($defaults as [$index, $name, $value]) { if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { $parameters[$index] = $value; } } } private function setFromAssociativeArray(array $parameters): void { if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['end'])) { $this->setEndDate($parameters['end']); } if (isset($parameters['recurrences'])) { $this->setRecurrences($parameters['recurrences']); } if (isset($parameters['interval'])) { $this->setDateInterval($parameters['interval']); } if (isset($parameters['options'])) { $this->setOptions($parameters['options']); } } private function configureTimezone(DateTimeZone $timezone, array $sortedArguments, array $originalArguments): array { $this->setTimezone($timezone); if (\is_string($originalArguments['start'] ?? null)) { $sortedArguments['start'] = $this->makeDateTime($originalArguments['start']); } if (\is_string($originalArguments['end'] ?? null)) { $sortedArguments['end'] = $this->makeDateTime($originalArguments['end']); } return $sortedArguments; } private function initializeSerialization(array $values): void { $serializationBase = [ 'start' => $values['start'] ?? $values['startDate'] ?? null, 'current' => $values['current'] ?? $values['carbonCurrent'] ?? null, 'end' => $values['end'] ?? $values['endDate'] ?? null, 'interval' => $values['interval'] ?? $values['dateInterval'] ?? null, 'recurrences' => max(1, (int) ($values['recurrences'] ?? $values['carbonRecurrences'] ?? 1)), 'include_start_date' => $values['include_start_date'] ?? true, 'include_end_date' => $values['include_end_date'] ?? false, ]; foreach (['start', 'current', 'end'] as $dateProperty) { if ($serializationBase[$dateProperty] instanceof Carbon) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTime(); } elseif ($serializationBase[$dateProperty] instanceof CarbonInterface) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTimeImmutable(); } } if ($serializationBase['interval'] instanceof CarbonInterval) { $serializationBase['interval'] = $serializationBase['interval']->toDateInterval(); } // @codeCoverageIgnoreStart if (method_exists(parent::class, '__unserialize')) { parent::__unserialize($serializationBase); return; } $excludeStart = !($values['include_start_date'] ?? true); $includeEnd = $values['include_end_date'] ?? true; parent::__construct( $serializationBase['start'], $serializationBase['interval'], $serializationBase['end'] ?? $serializationBase['recurrences'], ($excludeStart ? self::EXCLUDE_START_DATE : 0) | ($includeEnd && \defined('DatePeriod::INCLUDE_END_DATE') ? self::INCLUDE_END_DATE : 0), ); // @codeCoverageIgnoreEnd } }
PHP
{ "end_line": 1188, "name": "hasFilter", "signature": "public function hasFilter(callable|string $filter): bool", "start_line": 1177 }
{ "class_name": "CarbonPeriod", "class_signature": "class CarbonPeriod implements Countable, JsonSerializable, UnitValue", "namespace": "Carbon" }
resetFilters
Carbon/src/Carbon/CarbonPeriod.php
public function resetFilters(): static { $self = $this->copyIfImmutable(); $self->filters = []; if ($self->endDate !== null) { $self->filters[] = [static::END_DATE_FILTER, null]; } if ($self->carbonRecurrences !== null) { $self->filters[] = [static::RECURRENCES_FILTER, null]; } $self->handleChangedParameters(); return $self; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotACarbonClassException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnreachableException; use Carbon\Traits\DeprecatedPeriodProperties; use Carbon\Traits\IntervalRounding; use Carbon\Traits\LocalFactory; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Throwable; // @codeCoverageIgnoreStart require PHP_VERSION < 8.2 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php' : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php'; // @codeCoverageIgnoreEnd /** * Substitution of DatePeriod with some modifications and many more features. * * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. * @method static static since($date = null, $inclusive = null) Alias for start(). * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. * @method static static until($date = null, $inclusive = null) Alias for end(). * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. * @method static static times($recurrences = null) Alias for recurrences(). * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance. * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. * @method static static push($callback, $name = null) Alias for filter(). * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance. * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. * @method static static year($years = 1) Alias for years(). * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. * @method static static month($months = 1) Alias for months(). * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. * @method static static week($weeks = 1) Alias for weeks(). * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. * @method static static dayz($days = 1) Alias for days(). * @method static static day($days = 1) Alias for days(). * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. * @method static static hour($hours = 1) Alias for hours(). * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. * @method static static minute($minutes = 1) Alias for minutes(). * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. * @method static static second($seconds = 1) Alias for seconds(). * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * * @mixin DeprecatedPeriodProperties * * @SuppressWarnings(TooManyFields) * @SuppressWarnings(CamelCasePropertyName) * @SuppressWarnings(CouplingBetweenObjects) */ class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue { use LocalFactory; use IntervalRounding; use Mixin { Mixin::mixin as baseMixin; } use Options { Options::__debugInfo as baseDebugInfo; } use ToStringFormat; /** * Built-in filter for limit by recurrences. * * @var callable */ public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; /** * Built-in filter for limit to an end. * * @var callable */ public const END_DATE_FILTER = [self::class, 'filterEndDate']; /** * Special value which can be returned by filters to end iteration. Also a filter. * * @var callable */ public const END_ITERATION = [self::class, 'endIteration']; /** * Exclude end date from iteration. * * @var int */ public const EXCLUDE_END_DATE = 8; /** * Yield CarbonImmutable instances. * * @var int */ public const IMMUTABLE = 4; /** * Number of maximum attempts before giving up on finding next valid date. * * @var int */ public const NEXT_MAX_ATTEMPTS = 1000; /** * Number of maximum attempts before giving up on finding end date. * * @var int */ public const END_MAX_ATTEMPTS = 10000; /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = Carbon::class; /** * The registered macros. */ protected static array $macros = []; /** * Date class of iteration items. */ protected string $dateClass = Carbon::class; /** * Underlying date interval instance. Always present, one day by default. */ protected ?CarbonInterval $dateInterval = null; /** * True once __construct is finished. */ protected bool $constructed = false; /** * Whether current date interval was set by default. */ protected bool $isDefaultInterval = false; /** * The filters stack. */ protected array $filters = []; /** * Period start date. Applied on rewind. Always present, now by default. */ protected ?CarbonInterface $startDate = null; /** * Period end date. For inverted interval should be before the start date. Applied via a filter. */ protected ?CarbonInterface $endDate = null; /** * Limit for number of recurrences. Applied via a filter. */ protected int|float|null $carbonRecurrences = null; /** * Iteration options. */ protected ?int $options = null; /** * Index of current date. Always sequential, even if some dates are skipped by filters. * Equal to null only before the first iteration. */ protected int $key = 0; /** * Current date. May temporarily hold unaccepted value when looking for a next valid date. * Equal to null only before the first iteration. */ protected ?CarbonInterface $carbonCurrent = null; /** * Timezone of current date. Taken from the start date. */ protected ?DateTimeZone $timezone = null; /** * The cached validation result for current date. */ protected array|string|bool|null $validationResult = null; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; public function getIterator(): Generator { $this->rewind(); while ($this->valid()) { $key = $this->key(); $value = $this->current(); yield $key => $value; $this->next(); } } /** * Make a CarbonPeriod instance from given variable if possible. */ public static function make(mixed $var): ?static { try { return static::instance($var); } catch (NotAPeriodException) { return static::create($var); } } /** * Create a new instance from a DatePeriod or CarbonPeriod object. */ public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); } /** * Create a new instance. */ public static function create(...$params): static { return static::createFromArray($params); } /** * Create a new instance from an array of parameters. */ public static function createFromArray(array $params): static { return new static(...$params); } /** * Create CarbonPeriod from ISO 8601 string. */ public static function createFromIso(string $iso, ?int $options = null): static { $params = static::parseIso8601($iso); $instance = static::createFromArray($params); $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options; $instance->handleChangedParameters(); return $instance; } public static function createFromISO8601String(string $iso, ?int $options = null): static { return self::createFromIso($iso, $options); } /** * Return whether the given interval contains non-zero value of any time unit. */ protected static function intervalHasTime(DateInterval $interval): bool { return $interval->h || $interval->i || $interval->s || $interval->f; } /** * Return whether given variable is an ISO 8601 specification. * * Note: Check is very basic, as actual validation will be done later when parsing. * We just want to ensure that variable is not any other type of valid parameter. */ protected static function isIso8601(mixed $var): bool { if (!\is_string($var)) { return false; } // Match slash but not within a timezone name. $part = '[a-z]+(?:[_-][a-z]+)*'; preg_match("#\b$part/$part\b|(/)#i", $var, $match); return isset($match[1]); } /** * Parse given ISO 8601 string into an array of arguments. * * @SuppressWarnings(ElseExpression) */ protected static function parseIso8601(string $iso): array { $result = []; $interval = null; $start = null; $end = null; $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = self::makeInterval($part)) { $interval = $part; } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); } $result[] = $parsed; } return $result; } /** * Add missing parts of the target date from the source date. */ protected static function addMissingParts(string $source, string $target): string { $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); return $count ? $result : $target; } private static function makeInterval(mixed $input): ?CarbonInterval { try { return CarbonInterval::make($input); } catch (Throwable) { return null; } } private static function makeTimezone(mixed $input): ?CarbonTimeZone { if (!\is_string($input)) { return null; } try { return CarbonTimeZone::create($input); } catch (Throwable) { return null; } } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonPeriod::macro('middle', function () { * return $this->getStartDate()->average($this->getEndDate()); * }); * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonPeriod::mixin(new class { * public function addDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->addDays($count) * )->setEndDate( * $this->getEndDate()->addDays($count) * ); * }; * } * public function subDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->subDays($count) * )->setEndDate( * $this->getEndDate()->subDays($count) * ); * }; * } * }); * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); * ``` * * @throws ReflectionException */ public static function mixin(object|string $mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Provide static proxy for instance aliases. */ public static function __callStatic(string $method, array $parameters): mixed { $date = new static(); if (static::hasMacro($method)) { return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters)); } return $date->$method(...$parameters); } /** * CarbonPeriod constructor. * * @SuppressWarnings(ElseExpression) * * @throws InvalidArgumentException */ public function __construct(...$arguments) { $raw = null; if (isset($arguments['raw'])) { $raw = $arguments['raw']; $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false; if (isset($arguments['dateClass'])) { $this->dateClass = $arguments['dateClass']; } $arguments = $raw; } // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. $argumentsCount = \count($arguments); if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { array_splice($arguments, 0, 1, static::parseIso8601($iso)); } if ($argumentsCount === 1) { if ($arguments[0] instanceof self) { $arguments = [ $arguments[0]->getStartDate(), $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(), $arguments[0]->getDateInterval(), $arguments[0]->getOptions(), ]; } elseif ($arguments[0] instanceof DatePeriod) { $arguments = [ $arguments[0]->start, $arguments[0]->end ?: ($arguments[0]->recurrences - 1), $arguments[0]->interval, $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, ]; } } if (is_a($this->dateClass, DateTimeImmutable::class, true)) { $this->options = static::IMMUTABLE; } $optionsSet = false; $originalArguments = []; $sortedArguments = []; foreach ($arguments as $argument) { $parsedDate = null; if ($argument instanceof DateTimeZone) { $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments); } elseif (!isset($sortedArguments['interval']) && ( (\is_string($argument) && preg_match( '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument, )) || $argument instanceof DateInterval || $argument instanceof Closure || $argument instanceof Unit ) && $parsedInterval = self::makeInterval($argument) ) { $sortedArguments['interval'] = $parsedInterval; } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) { $sortedArguments['start'] = $parsedDate; $originalArguments['start'] = $argument; } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { $sortedArguments['end'] = $parsedDate; $originalArguments['end'] = $argument; } elseif (!isset($sortedArguments['recurrences']) && !isset($sortedArguments['end']) && (\is_int($argument) || \is_float($argument)) && $argument >= 0 ) { $sortedArguments['recurrences'] = $argument; } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { $optionsSet = true; $sortedArguments['options'] = (((int) $this->options) | ((int) $argument)); } elseif ($parsedTimezone = self::makeTimezone($argument)) { $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($raw === null && isset($sortedArguments['start'])) { $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1); if (\is_float($end)) { $end = $end === INF ? PHP_INT_MAX : (int) round($end); } $raw = [ $sortedArguments['start'], $sortedArguments['interval'] ?? CarbonInterval::day(), $end, ]; } $this->setFromAssociativeArray($sortedArguments); if ($this->startDate === null) { $dateClass = $this->dateClass; $this->setStartDate($dateClass::now()); } if ($this->dateInterval === null) { $this->setDateInterval(CarbonInterval::day()); $this->isDefaultInterval = true; } if ($this->options === null) { $this->setOptions(0); } parent::__construct( $this->startDate, $this->dateInterval, $this->endDate ?? max(1, min(2147483639, $this->recurrences ?? 1)), $this->options, ); $this->constructed = true; } /** * Get a copy of the instance. */ public function copy(): static { return clone $this; } /** * Prepare the instance to be set (self if mutable to be mutated, * copy if immutable to generate a new instance). */ protected function copyIfImmutable(): static { return $this; } /** * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. */ protected function getGetter(string $name): ?callable { return match (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) { 'start', 'start_date' => [$this, 'getStartDate'], 'end', 'end_date' => [$this, 'getEndDate'], 'interval', 'date_interval' => [$this, 'getDateInterval'], 'recurrences' => [$this, 'getRecurrences'], 'include_start_date' => [$this, 'isStartIncluded'], 'include_end_date' => [$this, 'isEndIncluded'], 'current' => [$this, 'current'], 'locale' => [$this, 'locale'], 'tzname', 'tz_name' => fn () => match (true) { $this->timezoneSetting === null => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, $this->timezoneSetting instanceof DateTimeZone => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, default => null, }; } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function get(string $name) { $getter = $this->getGetter($name); if ($getter) { return $getter(); } throw new UnknownGetterException($name); } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function __get(string $name) { return $this->get($name); } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset(string $name): bool { return $this->getGetter($name) !== null; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Set the iteration item class. * * @param string $dateClass * * @return static */ public function setDateClass(string $dateClass) { if (!is_a($dateClass, CarbonInterface::class, true)) { throw new NotACarbonClassException($dateClass); } $self = $this->copyIfImmutable(); $self->dateClass = $dateClass; if (is_a($dateClass, Carbon::class, true)) { $self->options = $self->options & ~static::IMMUTABLE; } elseif (is_a($dateClass, CarbonImmutable::class, true)) { $self->options = $self->options | static::IMMUTABLE; } return $self; } /** * Returns iteration item date class. * * @return string */ public function getDateClass(): string { return $this->dateClass; } /** * Change the period date interval. * * @param DateInterval|Unit|string|int $interval * @param Unit|string $unit the unit of $interval if it's a number * * @throws InvalidIntervalException * * @return static */ public function setDateInterval(mixed $interval, Unit|string|null $unit = null): static { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->name; } if (!$interval = CarbonInterval::make($interval, $unit)) { throw new InvalidIntervalException('Invalid interval.'); } if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) { throw new InvalidIntervalException('Empty interval is not accepted.'); } $self = $this->copyIfImmutable(); $self->dateInterval = $interval; $self->isDefaultInterval = false; $self->handleChangedParameters(); return $self; } /** * Reset the date interval to the default value. * * Difference with simply setting interval to 1-day is that P1D will not appear when calling toIso8601String() * and also next adding to the interval won't include the default 1-day. */ public function resetDateInterval(): static { $self = $this->copyIfImmutable(); $self->setDateInterval(CarbonInterval::day()); $self->isDefaultInterval = true; return $self; } /** * Invert the period date interval. */ public function invertDateInterval(): static { return $this->setDateInterval($this->dateInterval->invert()); } /** * Set start and end date. * * @param DateTime|DateTimeInterface|string $start * @param DateTime|DateTimeInterface|string|null $end * * @return static */ public function setDates(mixed $start, mixed $end): static { return $this->setStartDate($start)->setEndDate($end); } /** * Change the period options. * * @param int|null $options * * @return static */ public function setOptions(?int $options): static { $self = $this->copyIfImmutable(); $self->options = $options ?? 0; $self->handleChangedParameters(); return $self; } /** * Get the period options. */ public function getOptions(): int { return $this->options ?? 0; } /** * Toggle given options on or off. * * @param int $options * @param bool|null $state * * @throws InvalidArgumentException * * @return static */ public function toggleOptions(int $options, ?bool $state = null): static { $self = $this->copyIfImmutable(); if ($state === null) { $state = ($this->options & $options) !== $options; } return $self->setOptions( $state ? $this->options | $options : $this->options & ~$options, ); } /** * Toggle EXCLUDE_START_DATE option. */ public function excludeStartDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_START_DATE, $state); } /** * Toggle EXCLUDE_END_DATE option. */ public function excludeEndDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_END_DATE, $state); } /** * Get the underlying date interval. */ public function getDateInterval(): CarbonInterval { return $this->dateInterval->copy(); } /** * Get start date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getStartDate(?string $rounding = null): CarbonInterface { $date = $this->startDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get end date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getEndDate(?string $rounding = null): ?CarbonInterface { if (!$this->endDate) { return null; } $date = $this->endDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get number of recurrences. */ #[ReturnTypeWillChange] public function getRecurrences(): int|float|null { return $this->carbonRecurrences; } /** * Returns true if the start date should be excluded. */ public function isStartExcluded(): bool { return ($this->options & static::EXCLUDE_START_DATE) !== 0; } /** * Returns true if the end date should be excluded. */ public function isEndExcluded(): bool { return ($this->options & static::EXCLUDE_END_DATE) !== 0; } /** * Returns true if the start date should be included. */ public function isStartIncluded(): bool { return !$this->isStartExcluded(); } /** * Returns true if the end date should be included. */ public function isEndIncluded(): bool { return !$this->isEndExcluded(); } /** * Return the start if it's included by option, else return the start + 1 period interval. */ public function getIncludedStartDate(): CarbonInterface { $start = $this->getStartDate(); if ($this->isStartExcluded()) { return $start->add($this->getDateInterval()); } return $start; } /** * Return the end if it's included by option, else return the end - 1 period interval. * Warning: if the period has no fixed end, this method will iterate the period to calculate it. */ public function getIncludedEndDate(): CarbonInterface { $end = $this->getEndDate(); if (!$end) { return $this->calculateEnd(); } if ($this->isEndExcluded()) { return $end->sub($this->getDateInterval()); } return $end; } /** * Add a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function addFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); $self->filters[] = $tuple; $self->handleChangedParameters(); return $self; } /** * Prepend a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function prependFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); array_unshift($self->filters, $tuple); $self->handleChangedParameters(); return $self; } /** * Remove a filter by instance or name. */ public function removeFilter(callable|string $filter): static { $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; $self->filters = array_values(array_filter( $this->filters, static fn ($tuple) => $tuple[$key] !== $filter, )); $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Return whether given instance or name is in the filter stack. */ public function hasFilter(callable|string $filter): bool { $key = \is_callable($filter) ? 0 : 1; foreach ($this->filters as $tuple) { if ($tuple[$key] === $filter) { return true; } } return false; } /** * Get filters stack. */ public function getFilters(): array { return $this->filters; } /** * Set filters stack. */ public function setFilters(array $filters): static { $self = $this->copyIfImmutable(); $self->filters = $filters; $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Reset filters stack. */ public function resetFilters(): static { $self = $this->copyIfImmutable(); $self->filters = []; if ($self->endDate !== null) { $self->filters[] = [static::END_DATE_FILTER, null]; } if ($self->carbonRecurrences !== null) { $self->filters[] = [static::RECURRENCES_FILTER, null]; } $self->handleChangedParameters(); return $self; } /** * Add a recurrences filter (set maximum number of recurrences). * * @throws InvalidArgumentException */ public function setRecurrences(int|float|null $recurrences): static { if ($recurrences === null) { return $this->removeFilter(static::RECURRENCES_FILTER); } if ($recurrences < 0) { throw new InvalidPeriodParameterException('Invalid number of recurrences.'); } /** @var self $self */ $self = $this->copyIfImmutable(); $self->carbonRecurrences = $recurrences === INF ? INF : (int) $recurrences; if (!$self->hasFilter(static::RECURRENCES_FILTER)) { return $self->addFilter(static::RECURRENCES_FILTER); } $self->handleChangedParameters(); return $self; } /** * Change the period start date. * * @param DateTime|DateTimeInterface|string $date * @param bool|null $inclusive * * @throws InvalidPeriodDateException * * @return static */ public function setStartDate(mixed $date, ?bool $inclusive = null): static { if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date, $this->timezone))) { throw new InvalidPeriodDateException('Invalid start date.'); } $self = $this->copyIfImmutable(); $self->startDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); } return $self; } /** * Change the period end date. * * @param DateTime|DateTimeInterface|string|null $date * @param bool|null $inclusive * * @throws \InvalidArgumentException * * @return static */ public function setEndDate(mixed $date, ?bool $inclusive = null): static { if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date, $this->timezone)) { throw new InvalidPeriodDateException('Invalid end date.'); } if (!$date) { return $this->removeFilter(static::END_DATE_FILTER); } $self = $this->copyIfImmutable(); $self->endDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); } if (!$self->hasFilter(static::END_DATE_FILTER)) { return $self->addFilter(static::END_DATE_FILTER); } $self->handleChangedParameters(); return $self; } /** * Check if the current position is valid. */ public function valid(): bool { return $this->validateCurrentDate() === true; } /** * Return the current key. */ public function key(): ?int { return $this->valid() ? $this->key : null; } /** * Return the current date. */ public function current(): ?CarbonInterface { return $this->valid() ? $this->prepareForReturn($this->carbonCurrent) : null; } /** * Move forward to the next date. * * @throws RuntimeException */ public function next(): void { if ($this->carbonCurrent === null) { $this->rewind(); } if ($this->validationResult !== static::END_ITERATION) { $this->key++; $this->incrementCurrentDateUntilValid(); } } /** * Rewind to the start date. * * Iterating over a date in the UTC timezone avoids bug during backward DST change. * * @see https://bugs.php.net/bug.php?id=72255 * @see https://bugs.php.net/bug.php?id=74274 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time * * @throws RuntimeException */ public function rewind(): void { $this->key = 0; $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate); $settings = $this->getSettings(); if ($this->hasLocalTranslator()) { $settings['locale'] = $this->getTranslatorLocale(); } $this->carbonCurrent->settings($settings); $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null; if ($this->timezone) { $this->carbonCurrent = $this->carbonCurrent->utc(); } $this->validationResult = null; if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { $this->incrementCurrentDateUntilValid(); } } /** * Skip iterations and returns iteration state (false if ended, true if still valid). * * @param int $count steps number to skip (1 by default) * * @return bool */ public function skip(int $count = 1): bool { for ($i = $count; $this->valid() && $i > 0; $i--) { $this->next(); } return $this->valid(); } /** * Format the date period as ISO 8601. */ public function toIso8601String(): string { $parts = []; if ($this->carbonRecurrences !== null) { $parts[] = 'R'.$this->carbonRecurrences; } $parts[] = $this->startDate->toIso8601String(); if (!$this->isDefaultInterval) { $parts[] = $this->dateInterval->spec(); } if ($this->endDate !== null) { $parts[] = $this->endDate->toIso8601String(); } return implode('/', $parts); } /** * Convert the date period into a string. */ public function toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if ($format instanceof Closure) { return $format($this); } $translator = ([$this->dateClass, 'getTranslator'])(); $parts = []; $format = $format ?? ( !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) ? 'Y-m-d H:i:s' : 'Y-m-d' ); if ($this->carbonRecurrences !== null) { $parts[] = $this->translate('period_recurrences', [], $this->carbonRecurrences, $translator); } $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([ 'join' => true, ])], null, $translator); $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator); if ($this->endDate !== null) { $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator); } $result = implode(' ', $parts); return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1); } /** * Format the date period as ISO 8601. */ public function spec(): string { return $this->toIso8601String(); } /** * Cast the current instance into the given class. * * @param string $className The $className::instance() method will be called to cast the current object. * * @return DatePeriod|object */ public function cast(string $className): object { if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( $this->rawDate($this->getStartDate()), $this->getDateInterval(), $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0, ); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Return native DatePeriod PHP object matching the current instance. * * @example * ``` * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod()); * ``` */ public function toDatePeriod(): DatePeriod { return $this->cast(DatePeriod::class); } /** * Return `true` if the period has no custom filter and is guaranteed to be endless. * * Note that we can't check if a period is endless as soon as it has custom filters * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in * a way we can't predict without actually iterating the period. */ public function isUnfilteredAndEndLess(): bool { foreach ($this->filters as $filter) { switch ($filter) { case [static::RECURRENCES_FILTER, null]: if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) { return false; } break; case [static::END_DATE_FILTER, null]: if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { return false; } break; default: return false; } } return true; } /** * Convert the date period into an array without changing current iteration state. * * @return CarbonInterface[] */ public function toArray(): array { if ($this->isUnfilteredAndEndLess()) { throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); } $state = [ $this->key, $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null, $this->validationResult, ]; $result = iterator_to_array($this); [$this->key, $this->carbonCurrent, $this->validationResult] = $state; return $result; } /** * Count dates in the date period. */ public function count(): int { return \count($this->toArray()); } /** * Return the first date in the date period. */ public function first(): ?CarbonInterface { if ($this->isUnfilteredAndEndLess()) { foreach ($this as $date) { $this->rewind(); return $date; } return null; } return ($this->toArray() ?: [])[0] ?? null; } /** * Return the last date in the date period. */ public function last(): ?CarbonInterface { $array = $this->toArray(); return $array ? $array[\count($array) - 1] : null; } /** * Convert the date period into a string. */ public function __toString(): string { return $this->toString(); } /** * Add aliases for setters. * * CarbonPeriod::days(3)->hours(5)->invert() * ->sinceNow()->until('2010-01-10') * ->filter(...) * ->count() * * Note: We use magic method to let static and instance aliases with the same names. */ public function __call(string $method, array $parameters): mixed { if (static::hasMacro($method)) { return static::bindMacroContext($this, fn () => $this->callMacro($method, $parameters)); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } $count = \count($parameters); switch ($method) { case 'start': case 'since': if ($count === 0) { return $this->getStartDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setStartDate(...$parameters); case 'sinceNow': return $this->setStartDate(new Carbon(), ...$parameters); case 'end': case 'until': if ($count === 0) { return $this->getEndDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setEndDate(...$parameters); case 'untilNow': return $this->setEndDate(new Carbon(), ...$parameters); case 'dates': case 'between': self::setDefaultParameters($parameters, [ [0, 'start', null], [1, 'end', null], ]); return $this->setDates(...$parameters); case 'recurrences': case 'times': if ($count === 0) { return $this->getRecurrences(); } self::setDefaultParameters($parameters, [ [0, 'recurrences', null], ]); return $this->setRecurrences(...$parameters); case 'options': if ($count === 0) { return $this->getOptions(); } self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->setOptions(...$parameters); case 'toggle': self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->toggleOptions(...$parameters); case 'filter': case 'push': return $this->addFilter(...$parameters); case 'prepend': return $this->prependFilter(...$parameters); case 'filters': if ($count === 0) { return $this->getFilters(); } self::setDefaultParameters($parameters, [ [0, 'filters', []], ]); return $this->setFilters(...$parameters); case 'interval': case 'each': case 'every': case 'step': case 'stepBy': if ($count === 0) { return $this->getDateInterval(); } return $this->setDateInterval(...$parameters); case 'invert': return $this->invertDateInterval(); case 'years': case 'year': case 'months': case 'month': case 'weeks': case 'week': case 'days': case 'dayz': case 'day': case 'hours': case 'hour': case 'minutes': case 'minute': case 'seconds': case 'second': case 'milliseconds': case 'millisecond': case 'microseconds': case 'microsecond': return $this->setDateInterval(( // Override default P1D when instantiating via fluent setters. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] )(...$parameters)); } $dateClass = $this->dateClass; if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { throw new UnknownMethodException($method); } return $this; } /** * Set the instance's timezone from a string or object and apply it to start/end. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->setTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->setTimezone($timezone)); } return $self; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } return $self; } /** * Returns the end is set, else calculated from start and recurrences. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. * * @return CarbonInterface */ public function calculateEnd(?string $rounding = null): CarbonInterface { if ($end = $this->getEndDate($rounding)) { return $end; } if ($this->dateInterval->isEmpty()) { return $this->getStartDate($rounding); } $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); if ($date && $rounding) { $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); } return $date; } private function getEndFromRecurrences(): ?CarbonInterface { if ($this->carbonRecurrences === null) { throw new UnreachableException( "Could not calculate period end without either explicit end or recurrences.\n". "If you're looking for a forever-period, use ->setRecurrences(INF).", ); } if ($this->carbonRecurrences === INF) { $start = $this->getStartDate(); return $start < $start->avoidMutation()->add($this->getDateInterval()) ? CarbonImmutable::endOfTime() : CarbonImmutable::startOfTime(); } if ($this->filters === [[static::RECURRENCES_FILTER, null]]) { return $this->getStartDate()->avoidMutation()->add( $this->getDateInterval()->times( $this->carbonRecurrences - ($this->isStartExcluded() ? 0 : 1), ), ); } return null; } private function iterateUntilEnd(): ?CarbonInterface { $attempts = 0; $date = null; foreach ($this as $date) { if (++$attempts > static::END_MAX_ATTEMPTS) { throw new UnreachableException( 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.', ); } } return $date; } /** * Returns true if the current period overlaps the given one (if 1 parameter passed) * or the period between 2 dates (if 2 parameters passed). * * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd * * @return bool */ public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool { $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; if (!($range instanceof self)) { $range = static::create($range); } [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); return $end > $rangeStart && $rangeEnd > $start; } /** * Execute a given function on each date of the period. * * @example * ``` * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) { * echo $date->diffInDays('2020-12-25')." days before Christmas!\n"; * }); * ``` */ public function forEach(callable $callback): void { foreach ($this as $date) { $callback($date); } } /** * Execute a given function on each date of the period and yield the result of this function. * * @example * ``` * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24'); * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) { * return $date->diffInDays('2020-12-25').' days before Christmas!'; * }))); * ``` */ public function map(callable $callback): Generator { foreach ($this as $date) { yield $callback($date); } } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. * * @see equalTo() */ public function eq(mixed $period): bool { return $this->equalTo($period); } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. */ public function equalTo(mixed $period): bool { if (!($period instanceof self)) { $period = self::make($period); } $end = $this->getEndDate(); return $period !== null && $this->getDateInterval()->eq($period->getDateInterval()) && $this->getStartDate()->eq($period->getStartDate()) && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. * * @see notEqualTo() */ public function ne(mixed $period): bool { return $this->notEqualTo($period); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. */ public function notEqualTo(mixed $period): bool { return !$this->eq($period); } /** * Determines if the start date is before another given date. * (Rather start/end are included by options is ignored.) */ public function startsBefore(mixed $date = null): bool { return $this->getStartDate()->lessThan($this->resolveCarbon($date)); } /** * Determines if the start date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsBeforeOrAt(mixed $date = null): bool { return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is after another given date. * (Rather start/end are included by options is ignored.) */ public function startsAfter(mixed $date = null): bool { return $this->getStartDate()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the start date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAfterOrAt(mixed $date = null): bool { return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAt(mixed $date = null): bool { return $this->getStartDate()->equalTo($this->resolveCarbon($date)); } /** * Determines if the end date is before another given date. * (Rather start/end are included by options is ignored.) */ public function endsBefore(mixed $date = null): bool { return $this->calculateEnd()->lessThan($this->resolveCarbon($date)); } /** * Determines if the end date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsBeforeOrAt(mixed $date = null): bool { return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is after another given date. * (Rather start/end are included by options is ignored.) */ public function endsAfter(mixed $date = null): bool { return $this->calculateEnd()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the end date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAfterOrAt(mixed $date = null): bool { return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAt(mixed $date = null): bool { return $this->calculateEnd()->equalTo($this->resolveCarbon($date)); } /** * Return true if start date is now or later. * (Rather start/end are included by options is ignored.) */ public function isStarted(): bool { return $this->startsBeforeOrAt(); } /** * Return true if end date is now or later. * (Rather start/end are included by options is ignored.) */ public function isEnded(): bool { return $this->endsBeforeOrAt(); } /** * Return true if now is between start date (included) and end date (excluded). * (Rather start/end are included by options is ignored.) */ public function isInProgress(): bool { return $this->isStarted() && !$this->isEnded(); } /** * Round the current instance at the given unit with given precision if specified and the given function. */ public function roundUnit( string $unit, DateInterval|float|int|string|null $precision = 1, callable|string $function = 'round', ): static { $self = $this->copyIfImmutable(); $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); if ($self->endDate) { $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); } /** * Truncate the current instance at the given unit with given precision if specified. */ public function floorUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. */ public function ceilUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function round( DateInterval|float|int|string|null $precision = null, callable|string $function = 'round', ): static { return $this->roundWith( $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(), $function ); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function floor(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified (else period interval is used). */ public function ceil(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'ceil'); } /** * Specify data which should be serialized to JSON. * * @link https://php.net/manual/en/jsonserializable.jsonserialize.php * * @return CarbonInterface[] */ public function jsonSerialize(): array { return $this->toArray(); } /** * Return true if the given date is between start and end. */ public function contains(mixed $date = null): bool { $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : ''); $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : ''); return $this->$startMethod($date) && $this->$endMethod($date); } /** * Return true if the current period follows a given other period (with no overlap). * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31] * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function follows(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval())); } /** * Return true if the given other period follows the current one (with no overlap). * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12] * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function isFollowedBy(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $period->follows($this); } /** * Return true if the given period either follows or is followed by the current one. * * @see follows() * @see isFollowedBy() */ public function isConsecutiveWith(mixed $period, mixed ...$arguments): bool { return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments); } public function __debugInfo(): array { $info = $this->baseDebugInfo(); unset( $info['start'], $info['end'], $info['interval'], $info['include_start_date'], $info['include_end_date'], $info['constructed'], $info["\0*\0constructed"], ); return $info; } public function __unserialize(array $data): void { try { $values = array_combine( array_map( static fn (string $key): string => preg_replace('/^\0\*\0/', '', $key), array_keys($data), ), $data, ); $this->initializeSerialization($values); foreach ($values as $key => $value) { if ($value === null) { continue; } $property = match ($key) { 'tzName' => $this->setTimezone(...), 'options' => $this->setOptions(...), 'recurrences' => $this->setRecurrences(...), 'current' => function (mixed $current): void { if (!($current instanceof CarbonInterface)) { $current = $this->resolveCarbon($current); } $this->carbonCurrent = $current; }, 'start' => 'startDate', 'interval' => $this->setDateInterval(...), 'end' => 'endDate', 'key' => null, 'include_start_date' => function (bool $included): void { $this->excludeStartDate(!$included); }, 'include_end_date' => function (bool $included): void { $this->excludeEndDate(!$included); }, default => $key, }; if ($property === null) { continue; } if (\is_callable($property)) { $property($value); continue; } if ($value instanceof DateTimeInterface && !($value instanceof CarbonInterface)) { $value = ($value instanceof DateTime) ? Carbon::instance($value) : CarbonImmutable::instance($value); } try { $this->$property = $value; } catch (Throwable) { // Must be ignored for backward-compatibility } } if (\array_key_exists('carbonRecurrences', $values)) { $this->carbonRecurrences = $values['carbonRecurrences']; } elseif (((int) ($values['recurrences'] ?? 0)) <= 1 && $this->endDate !== null) { $this->carbonRecurrences = null; } } catch (Throwable $e) { // @codeCoverageIgnoreStart if (!method_exists(parent::class, '__unserialize')) { throw $e; } parent::__unserialize($data); // @codeCoverageIgnoreEnd } } /** * Update properties after removing built-in filters. */ protected function updateInternalState(): void { if (!$this->hasFilter(static::END_DATE_FILTER)) { $this->endDate = null; } if (!$this->hasFilter(static::RECURRENCES_FILTER)) { $this->carbonRecurrences = null; } } /** * Create a filter tuple from raw parameters. * * Will create an automatic filter callback for one of Carbon's is* methods. */ protected function createFilterTuple(array $parameters): array { $method = array_shift($parameters); if (!$this->isCarbonPredicateMethod($method)) { return [$method, array_shift($parameters)]; } return [static fn ($date) => ([$date, $method])(...$parameters), $method]; } /** * Return whether given callable is a string pointing to one of Carbon's is* methods * and should be automatically converted to a filter callback. */ protected function isCarbonPredicateMethod(callable|string $callable): bool { return \is_string($callable) && str_starts_with($callable, 'is') && (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable)); } /** * Recurrences filter callback (limits number of recurrences). * * @SuppressWarnings(UnusedFormalParameter) */ protected function filterRecurrences(CarbonInterface $current, int $key): bool|callable { if ($key < $this->carbonRecurrences) { return true; } return static::END_ITERATION; } /** * End date filter callback. * * @return bool|static::END_ITERATION */ protected function filterEndDate(CarbonInterface $current): bool|callable { if (!$this->isEndExcluded() && $current == $this->endDate) { return true; } if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) { return true; } return static::END_ITERATION; } /** * End iteration filter callback. * * @return static::END_ITERATION */ protected function endIteration(): callable { return static::END_ITERATION; } /** * Handle change of the parameters. */ protected function handleChangedParameters(): void { if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { $this->dateClass = CarbonImmutable::class; } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { $this->dateClass = Carbon::class; } $this->validationResult = null; } /** * Validate current date and stop iteration when necessary. * * Returns true when current date is valid, false if it is not, or static::END_ITERATION * when iteration should be stopped. * * @return bool|static::END_ITERATION */ protected function validateCurrentDate(): bool|callable { if ($this->carbonCurrent === null) { $this->rewind(); } // Check after the first rewind to avoid repeating the initial validation. return $this->validationResult ?? ($this->validationResult = $this->checkFilters()); } /** * Check whether current value and key pass all the filters. * * @return bool|static::END_ITERATION */ protected function checkFilters(): bool|callable { $current = $this->prepareForReturn($this->carbonCurrent); foreach ($this->filters as $tuple) { $result = \call_user_func($tuple[0], $current->avoidMutation(), $this->key, $this); if ($result === static::END_ITERATION) { return static::END_ITERATION; } if (!$result) { return false; } } return true; } /** * Prepare given date to be returned to the external logic. * * @param CarbonInterface $date * * @return CarbonInterface */ protected function prepareForReturn(CarbonInterface $date) { $date = ([$this->dateClass, 'make'])($date); if ($this->timezone) { return $date->setTimezone($this->timezone); } return $date; } /** * Keep incrementing the current date until a valid date is found or the iteration is ended. * * @throws RuntimeException */ protected function incrementCurrentDateUntilValid(): void { $attempts = 0; do { $this->carbonCurrent = $this->carbonCurrent->add($this->dateInterval); $this->validationResult = null; if (++$attempts > static::NEXT_MAX_ATTEMPTS) { throw new UnreachableException('Could not find next valid date.'); } } while ($this->validateCurrentDate() === false); } /** * Call given macro. */ protected function callMacro(string $name, array $parameters): mixed { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date * * @return \Carbon\CarbonInterface */ protected function resolveCarbon($date = null) { return $this->getStartDate()->nowWithSameTz()->carbonize($date); } /** * Resolve passed arguments or DatePeriod to a CarbonPeriod object. */ protected function resolveCarbonPeriod(mixed $period, mixed ...$arguments): self { if ($period instanceof self) { return $period; } return $period instanceof DatePeriod ? static::instance($period) : static::create($period, ...$arguments); } private function orderCouple($first, $second): array { return $first > $second ? [$second, $first] : [$first, $second]; } private function makeDateTime($value): ?DateTimeInterface { if ($value instanceof DateTimeInterface) { return $value; } if ($value instanceof WeekDay || $value instanceof Month) { $dateClass = $this->dateClass; return new $dateClass($value, $this->timezoneSetting); } if (\is_string($value)) { $value = trim($value); if (!preg_match('/^P[\dT]/', $value) && !preg_match('/^R\d/', $value) && preg_match('/[a-z\d]/i', $value) ) { $dateClass = $this->dateClass; return $dateClass::parse($value, $this->timezoneSetting); } } return null; } private function isInfiniteDate($date): bool { return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); } private function rawDate($date): ?DateTimeInterface { if ($date === false || $date === null) { return null; } if ($date instanceof CarbonInterface) { return $date->isMutable() ? $date->toDateTime() : $date->toDateTimeImmutable(); } if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { return $date; } $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); } private static function setDefaultParameters(array &$parameters, array $defaults): void { foreach ($defaults as [$index, $name, $value]) { if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { $parameters[$index] = $value; } } } private function setFromAssociativeArray(array $parameters): void { if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['end'])) { $this->setEndDate($parameters['end']); } if (isset($parameters['recurrences'])) { $this->setRecurrences($parameters['recurrences']); } if (isset($parameters['interval'])) { $this->setDateInterval($parameters['interval']); } if (isset($parameters['options'])) { $this->setOptions($parameters['options']); } } private function configureTimezone(DateTimeZone $timezone, array $sortedArguments, array $originalArguments): array { $this->setTimezone($timezone); if (\is_string($originalArguments['start'] ?? null)) { $sortedArguments['start'] = $this->makeDateTime($originalArguments['start']); } if (\is_string($originalArguments['end'] ?? null)) { $sortedArguments['end'] = $this->makeDateTime($originalArguments['end']); } return $sortedArguments; } private function initializeSerialization(array $values): void { $serializationBase = [ 'start' => $values['start'] ?? $values['startDate'] ?? null, 'current' => $values['current'] ?? $values['carbonCurrent'] ?? null, 'end' => $values['end'] ?? $values['endDate'] ?? null, 'interval' => $values['interval'] ?? $values['dateInterval'] ?? null, 'recurrences' => max(1, (int) ($values['recurrences'] ?? $values['carbonRecurrences'] ?? 1)), 'include_start_date' => $values['include_start_date'] ?? true, 'include_end_date' => $values['include_end_date'] ?? false, ]; foreach (['start', 'current', 'end'] as $dateProperty) { if ($serializationBase[$dateProperty] instanceof Carbon) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTime(); } elseif ($serializationBase[$dateProperty] instanceof CarbonInterface) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTimeImmutable(); } } if ($serializationBase['interval'] instanceof CarbonInterval) { $serializationBase['interval'] = $serializationBase['interval']->toDateInterval(); } // @codeCoverageIgnoreStart if (method_exists(parent::class, '__unserialize')) { parent::__unserialize($serializationBase); return; } $excludeStart = !($values['include_start_date'] ?? true); $includeEnd = $values['include_end_date'] ?? true; parent::__construct( $serializationBase['start'], $serializationBase['interval'], $serializationBase['end'] ?? $serializationBase['recurrences'], ($excludeStart ? self::EXCLUDE_START_DATE : 0) | ($includeEnd && \defined('DatePeriod::INCLUDE_END_DATE') ? self::INCLUDE_END_DATE : 0), ); // @codeCoverageIgnoreEnd } }
PHP
{ "end_line": 1232, "name": "resetFilters", "signature": "public function resetFilters(): static", "start_line": 1216 }
{ "class_name": "CarbonPeriod", "class_signature": "class CarbonPeriod implements Countable, JsonSerializable, UnitValue", "namespace": "Carbon" }
next
Carbon/src/Carbon/CarbonPeriod.php
public function next(): void { if ($this->carbonCurrent === null) { $this->rewind(); } if ($this->validationResult !== static::END_ITERATION) { $this->key++; $this->incrementCurrentDateUntilValid(); } }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotACarbonClassException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnreachableException; use Carbon\Traits\DeprecatedPeriodProperties; use Carbon\Traits\IntervalRounding; use Carbon\Traits\LocalFactory; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Throwable; // @codeCoverageIgnoreStart require PHP_VERSION < 8.2 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php' : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php'; // @codeCoverageIgnoreEnd /** * Substitution of DatePeriod with some modifications and many more features. * * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. * @method static static since($date = null, $inclusive = null) Alias for start(). * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. * @method static static until($date = null, $inclusive = null) Alias for end(). * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. * @method static static times($recurrences = null) Alias for recurrences(). * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance. * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. * @method static static push($callback, $name = null) Alias for filter(). * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance. * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. * @method static static year($years = 1) Alias for years(). * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. * @method static static month($months = 1) Alias for months(). * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. * @method static static week($weeks = 1) Alias for weeks(). * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. * @method static static dayz($days = 1) Alias for days(). * @method static static day($days = 1) Alias for days(). * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. * @method static static hour($hours = 1) Alias for hours(). * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. * @method static static minute($minutes = 1) Alias for minutes(). * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. * @method static static second($seconds = 1) Alias for seconds(). * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * * @mixin DeprecatedPeriodProperties * * @SuppressWarnings(TooManyFields) * @SuppressWarnings(CamelCasePropertyName) * @SuppressWarnings(CouplingBetweenObjects) */ class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue { use LocalFactory; use IntervalRounding; use Mixin { Mixin::mixin as baseMixin; } use Options { Options::__debugInfo as baseDebugInfo; } use ToStringFormat; /** * Built-in filter for limit by recurrences. * * @var callable */ public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; /** * Built-in filter for limit to an end. * * @var callable */ public const END_DATE_FILTER = [self::class, 'filterEndDate']; /** * Special value which can be returned by filters to end iteration. Also a filter. * * @var callable */ public const END_ITERATION = [self::class, 'endIteration']; /** * Exclude end date from iteration. * * @var int */ public const EXCLUDE_END_DATE = 8; /** * Yield CarbonImmutable instances. * * @var int */ public const IMMUTABLE = 4; /** * Number of maximum attempts before giving up on finding next valid date. * * @var int */ public const NEXT_MAX_ATTEMPTS = 1000; /** * Number of maximum attempts before giving up on finding end date. * * @var int */ public const END_MAX_ATTEMPTS = 10000; /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = Carbon::class; /** * The registered macros. */ protected static array $macros = []; /** * Date class of iteration items. */ protected string $dateClass = Carbon::class; /** * Underlying date interval instance. Always present, one day by default. */ protected ?CarbonInterval $dateInterval = null; /** * True once __construct is finished. */ protected bool $constructed = false; /** * Whether current date interval was set by default. */ protected bool $isDefaultInterval = false; /** * The filters stack. */ protected array $filters = []; /** * Period start date. Applied on rewind. Always present, now by default. */ protected ?CarbonInterface $startDate = null; /** * Period end date. For inverted interval should be before the start date. Applied via a filter. */ protected ?CarbonInterface $endDate = null; /** * Limit for number of recurrences. Applied via a filter. */ protected int|float|null $carbonRecurrences = null; /** * Iteration options. */ protected ?int $options = null; /** * Index of current date. Always sequential, even if some dates are skipped by filters. * Equal to null only before the first iteration. */ protected int $key = 0; /** * Current date. May temporarily hold unaccepted value when looking for a next valid date. * Equal to null only before the first iteration. */ protected ?CarbonInterface $carbonCurrent = null; /** * Timezone of current date. Taken from the start date. */ protected ?DateTimeZone $timezone = null; /** * The cached validation result for current date. */ protected array|string|bool|null $validationResult = null; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; public function getIterator(): Generator { $this->rewind(); while ($this->valid()) { $key = $this->key(); $value = $this->current(); yield $key => $value; $this->next(); } } /** * Make a CarbonPeriod instance from given variable if possible. */ public static function make(mixed $var): ?static { try { return static::instance($var); } catch (NotAPeriodException) { return static::create($var); } } /** * Create a new instance from a DatePeriod or CarbonPeriod object. */ public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); } /** * Create a new instance. */ public static function create(...$params): static { return static::createFromArray($params); } /** * Create a new instance from an array of parameters. */ public static function createFromArray(array $params): static { return new static(...$params); } /** * Create CarbonPeriod from ISO 8601 string. */ public static function createFromIso(string $iso, ?int $options = null): static { $params = static::parseIso8601($iso); $instance = static::createFromArray($params); $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options; $instance->handleChangedParameters(); return $instance; } public static function createFromISO8601String(string $iso, ?int $options = null): static { return self::createFromIso($iso, $options); } /** * Return whether the given interval contains non-zero value of any time unit. */ protected static function intervalHasTime(DateInterval $interval): bool { return $interval->h || $interval->i || $interval->s || $interval->f; } /** * Return whether given variable is an ISO 8601 specification. * * Note: Check is very basic, as actual validation will be done later when parsing. * We just want to ensure that variable is not any other type of valid parameter. */ protected static function isIso8601(mixed $var): bool { if (!\is_string($var)) { return false; } // Match slash but not within a timezone name. $part = '[a-z]+(?:[_-][a-z]+)*'; preg_match("#\b$part/$part\b|(/)#i", $var, $match); return isset($match[1]); } /** * Parse given ISO 8601 string into an array of arguments. * * @SuppressWarnings(ElseExpression) */ protected static function parseIso8601(string $iso): array { $result = []; $interval = null; $start = null; $end = null; $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = self::makeInterval($part)) { $interval = $part; } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); } $result[] = $parsed; } return $result; } /** * Add missing parts of the target date from the source date. */ protected static function addMissingParts(string $source, string $target): string { $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); return $count ? $result : $target; } private static function makeInterval(mixed $input): ?CarbonInterval { try { return CarbonInterval::make($input); } catch (Throwable) { return null; } } private static function makeTimezone(mixed $input): ?CarbonTimeZone { if (!\is_string($input)) { return null; } try { return CarbonTimeZone::create($input); } catch (Throwable) { return null; } } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonPeriod::macro('middle', function () { * return $this->getStartDate()->average($this->getEndDate()); * }); * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonPeriod::mixin(new class { * public function addDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->addDays($count) * )->setEndDate( * $this->getEndDate()->addDays($count) * ); * }; * } * public function subDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->subDays($count) * )->setEndDate( * $this->getEndDate()->subDays($count) * ); * }; * } * }); * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); * ``` * * @throws ReflectionException */ public static function mixin(object|string $mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Provide static proxy for instance aliases. */ public static function __callStatic(string $method, array $parameters): mixed { $date = new static(); if (static::hasMacro($method)) { return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters)); } return $date->$method(...$parameters); } /** * CarbonPeriod constructor. * * @SuppressWarnings(ElseExpression) * * @throws InvalidArgumentException */ public function __construct(...$arguments) { $raw = null; if (isset($arguments['raw'])) { $raw = $arguments['raw']; $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false; if (isset($arguments['dateClass'])) { $this->dateClass = $arguments['dateClass']; } $arguments = $raw; } // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. $argumentsCount = \count($arguments); if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { array_splice($arguments, 0, 1, static::parseIso8601($iso)); } if ($argumentsCount === 1) { if ($arguments[0] instanceof self) { $arguments = [ $arguments[0]->getStartDate(), $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(), $arguments[0]->getDateInterval(), $arguments[0]->getOptions(), ]; } elseif ($arguments[0] instanceof DatePeriod) { $arguments = [ $arguments[0]->start, $arguments[0]->end ?: ($arguments[0]->recurrences - 1), $arguments[0]->interval, $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, ]; } } if (is_a($this->dateClass, DateTimeImmutable::class, true)) { $this->options = static::IMMUTABLE; } $optionsSet = false; $originalArguments = []; $sortedArguments = []; foreach ($arguments as $argument) { $parsedDate = null; if ($argument instanceof DateTimeZone) { $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments); } elseif (!isset($sortedArguments['interval']) && ( (\is_string($argument) && preg_match( '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument, )) || $argument instanceof DateInterval || $argument instanceof Closure || $argument instanceof Unit ) && $parsedInterval = self::makeInterval($argument) ) { $sortedArguments['interval'] = $parsedInterval; } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) { $sortedArguments['start'] = $parsedDate; $originalArguments['start'] = $argument; } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { $sortedArguments['end'] = $parsedDate; $originalArguments['end'] = $argument; } elseif (!isset($sortedArguments['recurrences']) && !isset($sortedArguments['end']) && (\is_int($argument) || \is_float($argument)) && $argument >= 0 ) { $sortedArguments['recurrences'] = $argument; } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { $optionsSet = true; $sortedArguments['options'] = (((int) $this->options) | ((int) $argument)); } elseif ($parsedTimezone = self::makeTimezone($argument)) { $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($raw === null && isset($sortedArguments['start'])) { $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1); if (\is_float($end)) { $end = $end === INF ? PHP_INT_MAX : (int) round($end); } $raw = [ $sortedArguments['start'], $sortedArguments['interval'] ?? CarbonInterval::day(), $end, ]; } $this->setFromAssociativeArray($sortedArguments); if ($this->startDate === null) { $dateClass = $this->dateClass; $this->setStartDate($dateClass::now()); } if ($this->dateInterval === null) { $this->setDateInterval(CarbonInterval::day()); $this->isDefaultInterval = true; } if ($this->options === null) { $this->setOptions(0); } parent::__construct( $this->startDate, $this->dateInterval, $this->endDate ?? max(1, min(2147483639, $this->recurrences ?? 1)), $this->options, ); $this->constructed = true; } /** * Get a copy of the instance. */ public function copy(): static { return clone $this; } /** * Prepare the instance to be set (self if mutable to be mutated, * copy if immutable to generate a new instance). */ protected function copyIfImmutable(): static { return $this; } /** * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. */ protected function getGetter(string $name): ?callable { return match (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) { 'start', 'start_date' => [$this, 'getStartDate'], 'end', 'end_date' => [$this, 'getEndDate'], 'interval', 'date_interval' => [$this, 'getDateInterval'], 'recurrences' => [$this, 'getRecurrences'], 'include_start_date' => [$this, 'isStartIncluded'], 'include_end_date' => [$this, 'isEndIncluded'], 'current' => [$this, 'current'], 'locale' => [$this, 'locale'], 'tzname', 'tz_name' => fn () => match (true) { $this->timezoneSetting === null => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, $this->timezoneSetting instanceof DateTimeZone => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, default => null, }; } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function get(string $name) { $getter = $this->getGetter($name); if ($getter) { return $getter(); } throw new UnknownGetterException($name); } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function __get(string $name) { return $this->get($name); } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset(string $name): bool { return $this->getGetter($name) !== null; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Set the iteration item class. * * @param string $dateClass * * @return static */ public function setDateClass(string $dateClass) { if (!is_a($dateClass, CarbonInterface::class, true)) { throw new NotACarbonClassException($dateClass); } $self = $this->copyIfImmutable(); $self->dateClass = $dateClass; if (is_a($dateClass, Carbon::class, true)) { $self->options = $self->options & ~static::IMMUTABLE; } elseif (is_a($dateClass, CarbonImmutable::class, true)) { $self->options = $self->options | static::IMMUTABLE; } return $self; } /** * Returns iteration item date class. * * @return string */ public function getDateClass(): string { return $this->dateClass; } /** * Change the period date interval. * * @param DateInterval|Unit|string|int $interval * @param Unit|string $unit the unit of $interval if it's a number * * @throws InvalidIntervalException * * @return static */ public function setDateInterval(mixed $interval, Unit|string|null $unit = null): static { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->name; } if (!$interval = CarbonInterval::make($interval, $unit)) { throw new InvalidIntervalException('Invalid interval.'); } if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) { throw new InvalidIntervalException('Empty interval is not accepted.'); } $self = $this->copyIfImmutable(); $self->dateInterval = $interval; $self->isDefaultInterval = false; $self->handleChangedParameters(); return $self; } /** * Reset the date interval to the default value. * * Difference with simply setting interval to 1-day is that P1D will not appear when calling toIso8601String() * and also next adding to the interval won't include the default 1-day. */ public function resetDateInterval(): static { $self = $this->copyIfImmutable(); $self->setDateInterval(CarbonInterval::day()); $self->isDefaultInterval = true; return $self; } /** * Invert the period date interval. */ public function invertDateInterval(): static { return $this->setDateInterval($this->dateInterval->invert()); } /** * Set start and end date. * * @param DateTime|DateTimeInterface|string $start * @param DateTime|DateTimeInterface|string|null $end * * @return static */ public function setDates(mixed $start, mixed $end): static { return $this->setStartDate($start)->setEndDate($end); } /** * Change the period options. * * @param int|null $options * * @return static */ public function setOptions(?int $options): static { $self = $this->copyIfImmutable(); $self->options = $options ?? 0; $self->handleChangedParameters(); return $self; } /** * Get the period options. */ public function getOptions(): int { return $this->options ?? 0; } /** * Toggle given options on or off. * * @param int $options * @param bool|null $state * * @throws InvalidArgumentException * * @return static */ public function toggleOptions(int $options, ?bool $state = null): static { $self = $this->copyIfImmutable(); if ($state === null) { $state = ($this->options & $options) !== $options; } return $self->setOptions( $state ? $this->options | $options : $this->options & ~$options, ); } /** * Toggle EXCLUDE_START_DATE option. */ public function excludeStartDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_START_DATE, $state); } /** * Toggle EXCLUDE_END_DATE option. */ public function excludeEndDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_END_DATE, $state); } /** * Get the underlying date interval. */ public function getDateInterval(): CarbonInterval { return $this->dateInterval->copy(); } /** * Get start date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getStartDate(?string $rounding = null): CarbonInterface { $date = $this->startDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get end date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getEndDate(?string $rounding = null): ?CarbonInterface { if (!$this->endDate) { return null; } $date = $this->endDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get number of recurrences. */ #[ReturnTypeWillChange] public function getRecurrences(): int|float|null { return $this->carbonRecurrences; } /** * Returns true if the start date should be excluded. */ public function isStartExcluded(): bool { return ($this->options & static::EXCLUDE_START_DATE) !== 0; } /** * Returns true if the end date should be excluded. */ public function isEndExcluded(): bool { return ($this->options & static::EXCLUDE_END_DATE) !== 0; } /** * Returns true if the start date should be included. */ public function isStartIncluded(): bool { return !$this->isStartExcluded(); } /** * Returns true if the end date should be included. */ public function isEndIncluded(): bool { return !$this->isEndExcluded(); } /** * Return the start if it's included by option, else return the start + 1 period interval. */ public function getIncludedStartDate(): CarbonInterface { $start = $this->getStartDate(); if ($this->isStartExcluded()) { return $start->add($this->getDateInterval()); } return $start; } /** * Return the end if it's included by option, else return the end - 1 period interval. * Warning: if the period has no fixed end, this method will iterate the period to calculate it. */ public function getIncludedEndDate(): CarbonInterface { $end = $this->getEndDate(); if (!$end) { return $this->calculateEnd(); } if ($this->isEndExcluded()) { return $end->sub($this->getDateInterval()); } return $end; } /** * Add a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function addFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); $self->filters[] = $tuple; $self->handleChangedParameters(); return $self; } /** * Prepend a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function prependFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); array_unshift($self->filters, $tuple); $self->handleChangedParameters(); return $self; } /** * Remove a filter by instance or name. */ public function removeFilter(callable|string $filter): static { $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; $self->filters = array_values(array_filter( $this->filters, static fn ($tuple) => $tuple[$key] !== $filter, )); $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Return whether given instance or name is in the filter stack. */ public function hasFilter(callable|string $filter): bool { $key = \is_callable($filter) ? 0 : 1; foreach ($this->filters as $tuple) { if ($tuple[$key] === $filter) { return true; } } return false; } /** * Get filters stack. */ public function getFilters(): array { return $this->filters; } /** * Set filters stack. */ public function setFilters(array $filters): static { $self = $this->copyIfImmutable(); $self->filters = $filters; $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Reset filters stack. */ public function resetFilters(): static { $self = $this->copyIfImmutable(); $self->filters = []; if ($self->endDate !== null) { $self->filters[] = [static::END_DATE_FILTER, null]; } if ($self->carbonRecurrences !== null) { $self->filters[] = [static::RECURRENCES_FILTER, null]; } $self->handleChangedParameters(); return $self; } /** * Add a recurrences filter (set maximum number of recurrences). * * @throws InvalidArgumentException */ public function setRecurrences(int|float|null $recurrences): static { if ($recurrences === null) { return $this->removeFilter(static::RECURRENCES_FILTER); } if ($recurrences < 0) { throw new InvalidPeriodParameterException('Invalid number of recurrences.'); } /** @var self $self */ $self = $this->copyIfImmutable(); $self->carbonRecurrences = $recurrences === INF ? INF : (int) $recurrences; if (!$self->hasFilter(static::RECURRENCES_FILTER)) { return $self->addFilter(static::RECURRENCES_FILTER); } $self->handleChangedParameters(); return $self; } /** * Change the period start date. * * @param DateTime|DateTimeInterface|string $date * @param bool|null $inclusive * * @throws InvalidPeriodDateException * * @return static */ public function setStartDate(mixed $date, ?bool $inclusive = null): static { if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date, $this->timezone))) { throw new InvalidPeriodDateException('Invalid start date.'); } $self = $this->copyIfImmutable(); $self->startDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); } return $self; } /** * Change the period end date. * * @param DateTime|DateTimeInterface|string|null $date * @param bool|null $inclusive * * @throws \InvalidArgumentException * * @return static */ public function setEndDate(mixed $date, ?bool $inclusive = null): static { if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date, $this->timezone)) { throw new InvalidPeriodDateException('Invalid end date.'); } if (!$date) { return $this->removeFilter(static::END_DATE_FILTER); } $self = $this->copyIfImmutable(); $self->endDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); } if (!$self->hasFilter(static::END_DATE_FILTER)) { return $self->addFilter(static::END_DATE_FILTER); } $self->handleChangedParameters(); return $self; } /** * Check if the current position is valid. */ public function valid(): bool { return $this->validateCurrentDate() === true; } /** * Return the current key. */ public function key(): ?int { return $this->valid() ? $this->key : null; } /** * Return the current date. */ public function current(): ?CarbonInterface { return $this->valid() ? $this->prepareForReturn($this->carbonCurrent) : null; } /** * Move forward to the next date. * * @throws RuntimeException */ public function next(): void { if ($this->carbonCurrent === null) { $this->rewind(); } if ($this->validationResult !== static::END_ITERATION) { $this->key++; $this->incrementCurrentDateUntilValid(); } } /** * Rewind to the start date. * * Iterating over a date in the UTC timezone avoids bug during backward DST change. * * @see https://bugs.php.net/bug.php?id=72255 * @see https://bugs.php.net/bug.php?id=74274 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time * * @throws RuntimeException */ public function rewind(): void { $this->key = 0; $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate); $settings = $this->getSettings(); if ($this->hasLocalTranslator()) { $settings['locale'] = $this->getTranslatorLocale(); } $this->carbonCurrent->settings($settings); $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null; if ($this->timezone) { $this->carbonCurrent = $this->carbonCurrent->utc(); } $this->validationResult = null; if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { $this->incrementCurrentDateUntilValid(); } } /** * Skip iterations and returns iteration state (false if ended, true if still valid). * * @param int $count steps number to skip (1 by default) * * @return bool */ public function skip(int $count = 1): bool { for ($i = $count; $this->valid() && $i > 0; $i--) { $this->next(); } return $this->valid(); } /** * Format the date period as ISO 8601. */ public function toIso8601String(): string { $parts = []; if ($this->carbonRecurrences !== null) { $parts[] = 'R'.$this->carbonRecurrences; } $parts[] = $this->startDate->toIso8601String(); if (!$this->isDefaultInterval) { $parts[] = $this->dateInterval->spec(); } if ($this->endDate !== null) { $parts[] = $this->endDate->toIso8601String(); } return implode('/', $parts); } /** * Convert the date period into a string. */ public function toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if ($format instanceof Closure) { return $format($this); } $translator = ([$this->dateClass, 'getTranslator'])(); $parts = []; $format = $format ?? ( !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) ? 'Y-m-d H:i:s' : 'Y-m-d' ); if ($this->carbonRecurrences !== null) { $parts[] = $this->translate('period_recurrences', [], $this->carbonRecurrences, $translator); } $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([ 'join' => true, ])], null, $translator); $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator); if ($this->endDate !== null) { $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator); } $result = implode(' ', $parts); return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1); } /** * Format the date period as ISO 8601. */ public function spec(): string { return $this->toIso8601String(); } /** * Cast the current instance into the given class. * * @param string $className The $className::instance() method will be called to cast the current object. * * @return DatePeriod|object */ public function cast(string $className): object { if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( $this->rawDate($this->getStartDate()), $this->getDateInterval(), $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0, ); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Return native DatePeriod PHP object matching the current instance. * * @example * ``` * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod()); * ``` */ public function toDatePeriod(): DatePeriod { return $this->cast(DatePeriod::class); } /** * Return `true` if the period has no custom filter and is guaranteed to be endless. * * Note that we can't check if a period is endless as soon as it has custom filters * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in * a way we can't predict without actually iterating the period. */ public function isUnfilteredAndEndLess(): bool { foreach ($this->filters as $filter) { switch ($filter) { case [static::RECURRENCES_FILTER, null]: if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) { return false; } break; case [static::END_DATE_FILTER, null]: if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { return false; } break; default: return false; } } return true; } /** * Convert the date period into an array without changing current iteration state. * * @return CarbonInterface[] */ public function toArray(): array { if ($this->isUnfilteredAndEndLess()) { throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); } $state = [ $this->key, $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null, $this->validationResult, ]; $result = iterator_to_array($this); [$this->key, $this->carbonCurrent, $this->validationResult] = $state; return $result; } /** * Count dates in the date period. */ public function count(): int { return \count($this->toArray()); } /** * Return the first date in the date period. */ public function first(): ?CarbonInterface { if ($this->isUnfilteredAndEndLess()) { foreach ($this as $date) { $this->rewind(); return $date; } return null; } return ($this->toArray() ?: [])[0] ?? null; } /** * Return the last date in the date period. */ public function last(): ?CarbonInterface { $array = $this->toArray(); return $array ? $array[\count($array) - 1] : null; } /** * Convert the date period into a string. */ public function __toString(): string { return $this->toString(); } /** * Add aliases for setters. * * CarbonPeriod::days(3)->hours(5)->invert() * ->sinceNow()->until('2010-01-10') * ->filter(...) * ->count() * * Note: We use magic method to let static and instance aliases with the same names. */ public function __call(string $method, array $parameters): mixed { if (static::hasMacro($method)) { return static::bindMacroContext($this, fn () => $this->callMacro($method, $parameters)); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } $count = \count($parameters); switch ($method) { case 'start': case 'since': if ($count === 0) { return $this->getStartDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setStartDate(...$parameters); case 'sinceNow': return $this->setStartDate(new Carbon(), ...$parameters); case 'end': case 'until': if ($count === 0) { return $this->getEndDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setEndDate(...$parameters); case 'untilNow': return $this->setEndDate(new Carbon(), ...$parameters); case 'dates': case 'between': self::setDefaultParameters($parameters, [ [0, 'start', null], [1, 'end', null], ]); return $this->setDates(...$parameters); case 'recurrences': case 'times': if ($count === 0) { return $this->getRecurrences(); } self::setDefaultParameters($parameters, [ [0, 'recurrences', null], ]); return $this->setRecurrences(...$parameters); case 'options': if ($count === 0) { return $this->getOptions(); } self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->setOptions(...$parameters); case 'toggle': self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->toggleOptions(...$parameters); case 'filter': case 'push': return $this->addFilter(...$parameters); case 'prepend': return $this->prependFilter(...$parameters); case 'filters': if ($count === 0) { return $this->getFilters(); } self::setDefaultParameters($parameters, [ [0, 'filters', []], ]); return $this->setFilters(...$parameters); case 'interval': case 'each': case 'every': case 'step': case 'stepBy': if ($count === 0) { return $this->getDateInterval(); } return $this->setDateInterval(...$parameters); case 'invert': return $this->invertDateInterval(); case 'years': case 'year': case 'months': case 'month': case 'weeks': case 'week': case 'days': case 'dayz': case 'day': case 'hours': case 'hour': case 'minutes': case 'minute': case 'seconds': case 'second': case 'milliseconds': case 'millisecond': case 'microseconds': case 'microsecond': return $this->setDateInterval(( // Override default P1D when instantiating via fluent setters. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] )(...$parameters)); } $dateClass = $this->dateClass; if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { throw new UnknownMethodException($method); } return $this; } /** * Set the instance's timezone from a string or object and apply it to start/end. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->setTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->setTimezone($timezone)); } return $self; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } return $self; } /** * Returns the end is set, else calculated from start and recurrences. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. * * @return CarbonInterface */ public function calculateEnd(?string $rounding = null): CarbonInterface { if ($end = $this->getEndDate($rounding)) { return $end; } if ($this->dateInterval->isEmpty()) { return $this->getStartDate($rounding); } $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); if ($date && $rounding) { $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); } return $date; } private function getEndFromRecurrences(): ?CarbonInterface { if ($this->carbonRecurrences === null) { throw new UnreachableException( "Could not calculate period end without either explicit end or recurrences.\n". "If you're looking for a forever-period, use ->setRecurrences(INF).", ); } if ($this->carbonRecurrences === INF) { $start = $this->getStartDate(); return $start < $start->avoidMutation()->add($this->getDateInterval()) ? CarbonImmutable::endOfTime() : CarbonImmutable::startOfTime(); } if ($this->filters === [[static::RECURRENCES_FILTER, null]]) { return $this->getStartDate()->avoidMutation()->add( $this->getDateInterval()->times( $this->carbonRecurrences - ($this->isStartExcluded() ? 0 : 1), ), ); } return null; } private function iterateUntilEnd(): ?CarbonInterface { $attempts = 0; $date = null; foreach ($this as $date) { if (++$attempts > static::END_MAX_ATTEMPTS) { throw new UnreachableException( 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.', ); } } return $date; } /** * Returns true if the current period overlaps the given one (if 1 parameter passed) * or the period between 2 dates (if 2 parameters passed). * * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd * * @return bool */ public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool { $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; if (!($range instanceof self)) { $range = static::create($range); } [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); return $end > $rangeStart && $rangeEnd > $start; } /** * Execute a given function on each date of the period. * * @example * ``` * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) { * echo $date->diffInDays('2020-12-25')." days before Christmas!\n"; * }); * ``` */ public function forEach(callable $callback): void { foreach ($this as $date) { $callback($date); } } /** * Execute a given function on each date of the period and yield the result of this function. * * @example * ``` * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24'); * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) { * return $date->diffInDays('2020-12-25').' days before Christmas!'; * }))); * ``` */ public function map(callable $callback): Generator { foreach ($this as $date) { yield $callback($date); } } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. * * @see equalTo() */ public function eq(mixed $period): bool { return $this->equalTo($period); } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. */ public function equalTo(mixed $period): bool { if (!($period instanceof self)) { $period = self::make($period); } $end = $this->getEndDate(); return $period !== null && $this->getDateInterval()->eq($period->getDateInterval()) && $this->getStartDate()->eq($period->getStartDate()) && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. * * @see notEqualTo() */ public function ne(mixed $period): bool { return $this->notEqualTo($period); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. */ public function notEqualTo(mixed $period): bool { return !$this->eq($period); } /** * Determines if the start date is before another given date. * (Rather start/end are included by options is ignored.) */ public function startsBefore(mixed $date = null): bool { return $this->getStartDate()->lessThan($this->resolveCarbon($date)); } /** * Determines if the start date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsBeforeOrAt(mixed $date = null): bool { return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is after another given date. * (Rather start/end are included by options is ignored.) */ public function startsAfter(mixed $date = null): bool { return $this->getStartDate()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the start date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAfterOrAt(mixed $date = null): bool { return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAt(mixed $date = null): bool { return $this->getStartDate()->equalTo($this->resolveCarbon($date)); } /** * Determines if the end date is before another given date. * (Rather start/end are included by options is ignored.) */ public function endsBefore(mixed $date = null): bool { return $this->calculateEnd()->lessThan($this->resolveCarbon($date)); } /** * Determines if the end date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsBeforeOrAt(mixed $date = null): bool { return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is after another given date. * (Rather start/end are included by options is ignored.) */ public function endsAfter(mixed $date = null): bool { return $this->calculateEnd()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the end date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAfterOrAt(mixed $date = null): bool { return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAt(mixed $date = null): bool { return $this->calculateEnd()->equalTo($this->resolveCarbon($date)); } /** * Return true if start date is now or later. * (Rather start/end are included by options is ignored.) */ public function isStarted(): bool { return $this->startsBeforeOrAt(); } /** * Return true if end date is now or later. * (Rather start/end are included by options is ignored.) */ public function isEnded(): bool { return $this->endsBeforeOrAt(); } /** * Return true if now is between start date (included) and end date (excluded). * (Rather start/end are included by options is ignored.) */ public function isInProgress(): bool { return $this->isStarted() && !$this->isEnded(); } /** * Round the current instance at the given unit with given precision if specified and the given function. */ public function roundUnit( string $unit, DateInterval|float|int|string|null $precision = 1, callable|string $function = 'round', ): static { $self = $this->copyIfImmutable(); $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); if ($self->endDate) { $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); } /** * Truncate the current instance at the given unit with given precision if specified. */ public function floorUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. */ public function ceilUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function round( DateInterval|float|int|string|null $precision = null, callable|string $function = 'round', ): static { return $this->roundWith( $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(), $function ); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function floor(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified (else period interval is used). */ public function ceil(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'ceil'); } /** * Specify data which should be serialized to JSON. * * @link https://php.net/manual/en/jsonserializable.jsonserialize.php * * @return CarbonInterface[] */ public function jsonSerialize(): array { return $this->toArray(); } /** * Return true if the given date is between start and end. */ public function contains(mixed $date = null): bool { $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : ''); $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : ''); return $this->$startMethod($date) && $this->$endMethod($date); } /** * Return true if the current period follows a given other period (with no overlap). * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31] * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function follows(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval())); } /** * Return true if the given other period follows the current one (with no overlap). * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12] * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function isFollowedBy(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $period->follows($this); } /** * Return true if the given period either follows or is followed by the current one. * * @see follows() * @see isFollowedBy() */ public function isConsecutiveWith(mixed $period, mixed ...$arguments): bool { return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments); } public function __debugInfo(): array { $info = $this->baseDebugInfo(); unset( $info['start'], $info['end'], $info['interval'], $info['include_start_date'], $info['include_end_date'], $info['constructed'], $info["\0*\0constructed"], ); return $info; } public function __unserialize(array $data): void { try { $values = array_combine( array_map( static fn (string $key): string => preg_replace('/^\0\*\0/', '', $key), array_keys($data), ), $data, ); $this->initializeSerialization($values); foreach ($values as $key => $value) { if ($value === null) { continue; } $property = match ($key) { 'tzName' => $this->setTimezone(...), 'options' => $this->setOptions(...), 'recurrences' => $this->setRecurrences(...), 'current' => function (mixed $current): void { if (!($current instanceof CarbonInterface)) { $current = $this->resolveCarbon($current); } $this->carbonCurrent = $current; }, 'start' => 'startDate', 'interval' => $this->setDateInterval(...), 'end' => 'endDate', 'key' => null, 'include_start_date' => function (bool $included): void { $this->excludeStartDate(!$included); }, 'include_end_date' => function (bool $included): void { $this->excludeEndDate(!$included); }, default => $key, }; if ($property === null) { continue; } if (\is_callable($property)) { $property($value); continue; } if ($value instanceof DateTimeInterface && !($value instanceof CarbonInterface)) { $value = ($value instanceof DateTime) ? Carbon::instance($value) : CarbonImmutable::instance($value); } try { $this->$property = $value; } catch (Throwable) { // Must be ignored for backward-compatibility } } if (\array_key_exists('carbonRecurrences', $values)) { $this->carbonRecurrences = $values['carbonRecurrences']; } elseif (((int) ($values['recurrences'] ?? 0)) <= 1 && $this->endDate !== null) { $this->carbonRecurrences = null; } } catch (Throwable $e) { // @codeCoverageIgnoreStart if (!method_exists(parent::class, '__unserialize')) { throw $e; } parent::__unserialize($data); // @codeCoverageIgnoreEnd } } /** * Update properties after removing built-in filters. */ protected function updateInternalState(): void { if (!$this->hasFilter(static::END_DATE_FILTER)) { $this->endDate = null; } if (!$this->hasFilter(static::RECURRENCES_FILTER)) { $this->carbonRecurrences = null; } } /** * Create a filter tuple from raw parameters. * * Will create an automatic filter callback for one of Carbon's is* methods. */ protected function createFilterTuple(array $parameters): array { $method = array_shift($parameters); if (!$this->isCarbonPredicateMethod($method)) { return [$method, array_shift($parameters)]; } return [static fn ($date) => ([$date, $method])(...$parameters), $method]; } /** * Return whether given callable is a string pointing to one of Carbon's is* methods * and should be automatically converted to a filter callback. */ protected function isCarbonPredicateMethod(callable|string $callable): bool { return \is_string($callable) && str_starts_with($callable, 'is') && (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable)); } /** * Recurrences filter callback (limits number of recurrences). * * @SuppressWarnings(UnusedFormalParameter) */ protected function filterRecurrences(CarbonInterface $current, int $key): bool|callable { if ($key < $this->carbonRecurrences) { return true; } return static::END_ITERATION; } /** * End date filter callback. * * @return bool|static::END_ITERATION */ protected function filterEndDate(CarbonInterface $current): bool|callable { if (!$this->isEndExcluded() && $current == $this->endDate) { return true; } if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) { return true; } return static::END_ITERATION; } /** * End iteration filter callback. * * @return static::END_ITERATION */ protected function endIteration(): callable { return static::END_ITERATION; } /** * Handle change of the parameters. */ protected function handleChangedParameters(): void { if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { $this->dateClass = CarbonImmutable::class; } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { $this->dateClass = Carbon::class; } $this->validationResult = null; } /** * Validate current date and stop iteration when necessary. * * Returns true when current date is valid, false if it is not, or static::END_ITERATION * when iteration should be stopped. * * @return bool|static::END_ITERATION */ protected function validateCurrentDate(): bool|callable { if ($this->carbonCurrent === null) { $this->rewind(); } // Check after the first rewind to avoid repeating the initial validation. return $this->validationResult ?? ($this->validationResult = $this->checkFilters()); } /** * Check whether current value and key pass all the filters. * * @return bool|static::END_ITERATION */ protected function checkFilters(): bool|callable { $current = $this->prepareForReturn($this->carbonCurrent); foreach ($this->filters as $tuple) { $result = \call_user_func($tuple[0], $current->avoidMutation(), $this->key, $this); if ($result === static::END_ITERATION) { return static::END_ITERATION; } if (!$result) { return false; } } return true; } /** * Prepare given date to be returned to the external logic. * * @param CarbonInterface $date * * @return CarbonInterface */ protected function prepareForReturn(CarbonInterface $date) { $date = ([$this->dateClass, 'make'])($date); if ($this->timezone) { return $date->setTimezone($this->timezone); } return $date; } /** * Keep incrementing the current date until a valid date is found or the iteration is ended. * * @throws RuntimeException */ protected function incrementCurrentDateUntilValid(): void { $attempts = 0; do { $this->carbonCurrent = $this->carbonCurrent->add($this->dateInterval); $this->validationResult = null; if (++$attempts > static::NEXT_MAX_ATTEMPTS) { throw new UnreachableException('Could not find next valid date.'); } } while ($this->validateCurrentDate() === false); } /** * Call given macro. */ protected function callMacro(string $name, array $parameters): mixed { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date * * @return \Carbon\CarbonInterface */ protected function resolveCarbon($date = null) { return $this->getStartDate()->nowWithSameTz()->carbonize($date); } /** * Resolve passed arguments or DatePeriod to a CarbonPeriod object. */ protected function resolveCarbonPeriod(mixed $period, mixed ...$arguments): self { if ($period instanceof self) { return $period; } return $period instanceof DatePeriod ? static::instance($period) : static::create($period, ...$arguments); } private function orderCouple($first, $second): array { return $first > $second ? [$second, $first] : [$first, $second]; } private function makeDateTime($value): ?DateTimeInterface { if ($value instanceof DateTimeInterface) { return $value; } if ($value instanceof WeekDay || $value instanceof Month) { $dateClass = $this->dateClass; return new $dateClass($value, $this->timezoneSetting); } if (\is_string($value)) { $value = trim($value); if (!preg_match('/^P[\dT]/', $value) && !preg_match('/^R\d/', $value) && preg_match('/[a-z\d]/i', $value) ) { $dateClass = $this->dateClass; return $dateClass::parse($value, $this->timezoneSetting); } } return null; } private function isInfiniteDate($date): bool { return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); } private function rawDate($date): ?DateTimeInterface { if ($date === false || $date === null) { return null; } if ($date instanceof CarbonInterface) { return $date->isMutable() ? $date->toDateTime() : $date->toDateTimeImmutable(); } if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { return $date; } $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); } private static function setDefaultParameters(array &$parameters, array $defaults): void { foreach ($defaults as [$index, $name, $value]) { if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { $parameters[$index] = $value; } } } private function setFromAssociativeArray(array $parameters): void { if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['end'])) { $this->setEndDate($parameters['end']); } if (isset($parameters['recurrences'])) { $this->setRecurrences($parameters['recurrences']); } if (isset($parameters['interval'])) { $this->setDateInterval($parameters['interval']); } if (isset($parameters['options'])) { $this->setOptions($parameters['options']); } } private function configureTimezone(DateTimeZone $timezone, array $sortedArguments, array $originalArguments): array { $this->setTimezone($timezone); if (\is_string($originalArguments['start'] ?? null)) { $sortedArguments['start'] = $this->makeDateTime($originalArguments['start']); } if (\is_string($originalArguments['end'] ?? null)) { $sortedArguments['end'] = $this->makeDateTime($originalArguments['end']); } return $sortedArguments; } private function initializeSerialization(array $values): void { $serializationBase = [ 'start' => $values['start'] ?? $values['startDate'] ?? null, 'current' => $values['current'] ?? $values['carbonCurrent'] ?? null, 'end' => $values['end'] ?? $values['endDate'] ?? null, 'interval' => $values['interval'] ?? $values['dateInterval'] ?? null, 'recurrences' => max(1, (int) ($values['recurrences'] ?? $values['carbonRecurrences'] ?? 1)), 'include_start_date' => $values['include_start_date'] ?? true, 'include_end_date' => $values['include_end_date'] ?? false, ]; foreach (['start', 'current', 'end'] as $dateProperty) { if ($serializationBase[$dateProperty] instanceof Carbon) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTime(); } elseif ($serializationBase[$dateProperty] instanceof CarbonInterface) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTimeImmutable(); } } if ($serializationBase['interval'] instanceof CarbonInterval) { $serializationBase['interval'] = $serializationBase['interval']->toDateInterval(); } // @codeCoverageIgnoreStart if (method_exists(parent::class, '__unserialize')) { parent::__unserialize($serializationBase); return; } $excludeStart = !($values['include_start_date'] ?? true); $includeEnd = $values['include_end_date'] ?? true; parent::__construct( $serializationBase['start'], $serializationBase['interval'], $serializationBase['end'] ?? $serializationBase['recurrences'], ($excludeStart ? self::EXCLUDE_START_DATE : 0) | ($includeEnd && \defined('DatePeriod::INCLUDE_END_DATE') ? self::INCLUDE_END_DATE : 0), ); // @codeCoverageIgnoreEnd } }
PHP
{ "end_line": 1368, "name": "next", "signature": "public function next(): void", "start_line": 1357 }
{ "class_name": "CarbonPeriod", "class_signature": "class CarbonPeriod implements Countable, JsonSerializable, UnitValue", "namespace": "Carbon" }
rewind
Carbon/src/Carbon/CarbonPeriod.php
public function rewind(): void { $this->key = 0; $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate); $settings = $this->getSettings(); if ($this->hasLocalTranslator()) { $settings['locale'] = $this->getTranslatorLocale(); } $this->carbonCurrent->settings($settings); $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null; if ($this->timezone) { $this->carbonCurrent = $this->carbonCurrent->utc(); } $this->validationResult = null; if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { $this->incrementCurrentDateUntilValid(); } }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotACarbonClassException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnreachableException; use Carbon\Traits\DeprecatedPeriodProperties; use Carbon\Traits\IntervalRounding; use Carbon\Traits\LocalFactory; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Throwable; // @codeCoverageIgnoreStart require PHP_VERSION < 8.2 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php' : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php'; // @codeCoverageIgnoreEnd /** * Substitution of DatePeriod with some modifications and many more features. * * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. * @method static static since($date = null, $inclusive = null) Alias for start(). * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. * @method static static until($date = null, $inclusive = null) Alias for end(). * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. * @method static static times($recurrences = null) Alias for recurrences(). * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance. * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. * @method static static push($callback, $name = null) Alias for filter(). * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance. * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. * @method static static year($years = 1) Alias for years(). * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. * @method static static month($months = 1) Alias for months(). * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. * @method static static week($weeks = 1) Alias for weeks(). * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. * @method static static dayz($days = 1) Alias for days(). * @method static static day($days = 1) Alias for days(). * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. * @method static static hour($hours = 1) Alias for hours(). * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. * @method static static minute($minutes = 1) Alias for minutes(). * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. * @method static static second($seconds = 1) Alias for seconds(). * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * * @mixin DeprecatedPeriodProperties * * @SuppressWarnings(TooManyFields) * @SuppressWarnings(CamelCasePropertyName) * @SuppressWarnings(CouplingBetweenObjects) */ class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue { use LocalFactory; use IntervalRounding; use Mixin { Mixin::mixin as baseMixin; } use Options { Options::__debugInfo as baseDebugInfo; } use ToStringFormat; /** * Built-in filter for limit by recurrences. * * @var callable */ public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; /** * Built-in filter for limit to an end. * * @var callable */ public const END_DATE_FILTER = [self::class, 'filterEndDate']; /** * Special value which can be returned by filters to end iteration. Also a filter. * * @var callable */ public const END_ITERATION = [self::class, 'endIteration']; /** * Exclude end date from iteration. * * @var int */ public const EXCLUDE_END_DATE = 8; /** * Yield CarbonImmutable instances. * * @var int */ public const IMMUTABLE = 4; /** * Number of maximum attempts before giving up on finding next valid date. * * @var int */ public const NEXT_MAX_ATTEMPTS = 1000; /** * Number of maximum attempts before giving up on finding end date. * * @var int */ public const END_MAX_ATTEMPTS = 10000; /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = Carbon::class; /** * The registered macros. */ protected static array $macros = []; /** * Date class of iteration items. */ protected string $dateClass = Carbon::class; /** * Underlying date interval instance. Always present, one day by default. */ protected ?CarbonInterval $dateInterval = null; /** * True once __construct is finished. */ protected bool $constructed = false; /** * Whether current date interval was set by default. */ protected bool $isDefaultInterval = false; /** * The filters stack. */ protected array $filters = []; /** * Period start date. Applied on rewind. Always present, now by default. */ protected ?CarbonInterface $startDate = null; /** * Period end date. For inverted interval should be before the start date. Applied via a filter. */ protected ?CarbonInterface $endDate = null; /** * Limit for number of recurrences. Applied via a filter. */ protected int|float|null $carbonRecurrences = null; /** * Iteration options. */ protected ?int $options = null; /** * Index of current date. Always sequential, even if some dates are skipped by filters. * Equal to null only before the first iteration. */ protected int $key = 0; /** * Current date. May temporarily hold unaccepted value when looking for a next valid date. * Equal to null only before the first iteration. */ protected ?CarbonInterface $carbonCurrent = null; /** * Timezone of current date. Taken from the start date. */ protected ?DateTimeZone $timezone = null; /** * The cached validation result for current date. */ protected array|string|bool|null $validationResult = null; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; public function getIterator(): Generator { $this->rewind(); while ($this->valid()) { $key = $this->key(); $value = $this->current(); yield $key => $value; $this->next(); } } /** * Make a CarbonPeriod instance from given variable if possible. */ public static function make(mixed $var): ?static { try { return static::instance($var); } catch (NotAPeriodException) { return static::create($var); } } /** * Create a new instance from a DatePeriod or CarbonPeriod object. */ public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); } /** * Create a new instance. */ public static function create(...$params): static { return static::createFromArray($params); } /** * Create a new instance from an array of parameters. */ public static function createFromArray(array $params): static { return new static(...$params); } /** * Create CarbonPeriod from ISO 8601 string. */ public static function createFromIso(string $iso, ?int $options = null): static { $params = static::parseIso8601($iso); $instance = static::createFromArray($params); $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options; $instance->handleChangedParameters(); return $instance; } public static function createFromISO8601String(string $iso, ?int $options = null): static { return self::createFromIso($iso, $options); } /** * Return whether the given interval contains non-zero value of any time unit. */ protected static function intervalHasTime(DateInterval $interval): bool { return $interval->h || $interval->i || $interval->s || $interval->f; } /** * Return whether given variable is an ISO 8601 specification. * * Note: Check is very basic, as actual validation will be done later when parsing. * We just want to ensure that variable is not any other type of valid parameter. */ protected static function isIso8601(mixed $var): bool { if (!\is_string($var)) { return false; } // Match slash but not within a timezone name. $part = '[a-z]+(?:[_-][a-z]+)*'; preg_match("#\b$part/$part\b|(/)#i", $var, $match); return isset($match[1]); } /** * Parse given ISO 8601 string into an array of arguments. * * @SuppressWarnings(ElseExpression) */ protected static function parseIso8601(string $iso): array { $result = []; $interval = null; $start = null; $end = null; $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = self::makeInterval($part)) { $interval = $part; } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); } $result[] = $parsed; } return $result; } /** * Add missing parts of the target date from the source date. */ protected static function addMissingParts(string $source, string $target): string { $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); return $count ? $result : $target; } private static function makeInterval(mixed $input): ?CarbonInterval { try { return CarbonInterval::make($input); } catch (Throwable) { return null; } } private static function makeTimezone(mixed $input): ?CarbonTimeZone { if (!\is_string($input)) { return null; } try { return CarbonTimeZone::create($input); } catch (Throwable) { return null; } } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonPeriod::macro('middle', function () { * return $this->getStartDate()->average($this->getEndDate()); * }); * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonPeriod::mixin(new class { * public function addDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->addDays($count) * )->setEndDate( * $this->getEndDate()->addDays($count) * ); * }; * } * public function subDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->subDays($count) * )->setEndDate( * $this->getEndDate()->subDays($count) * ); * }; * } * }); * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); * ``` * * @throws ReflectionException */ public static function mixin(object|string $mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Provide static proxy for instance aliases. */ public static function __callStatic(string $method, array $parameters): mixed { $date = new static(); if (static::hasMacro($method)) { return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters)); } return $date->$method(...$parameters); } /** * CarbonPeriod constructor. * * @SuppressWarnings(ElseExpression) * * @throws InvalidArgumentException */ public function __construct(...$arguments) { $raw = null; if (isset($arguments['raw'])) { $raw = $arguments['raw']; $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false; if (isset($arguments['dateClass'])) { $this->dateClass = $arguments['dateClass']; } $arguments = $raw; } // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. $argumentsCount = \count($arguments); if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { array_splice($arguments, 0, 1, static::parseIso8601($iso)); } if ($argumentsCount === 1) { if ($arguments[0] instanceof self) { $arguments = [ $arguments[0]->getStartDate(), $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(), $arguments[0]->getDateInterval(), $arguments[0]->getOptions(), ]; } elseif ($arguments[0] instanceof DatePeriod) { $arguments = [ $arguments[0]->start, $arguments[0]->end ?: ($arguments[0]->recurrences - 1), $arguments[0]->interval, $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, ]; } } if (is_a($this->dateClass, DateTimeImmutable::class, true)) { $this->options = static::IMMUTABLE; } $optionsSet = false; $originalArguments = []; $sortedArguments = []; foreach ($arguments as $argument) { $parsedDate = null; if ($argument instanceof DateTimeZone) { $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments); } elseif (!isset($sortedArguments['interval']) && ( (\is_string($argument) && preg_match( '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument, )) || $argument instanceof DateInterval || $argument instanceof Closure || $argument instanceof Unit ) && $parsedInterval = self::makeInterval($argument) ) { $sortedArguments['interval'] = $parsedInterval; } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) { $sortedArguments['start'] = $parsedDate; $originalArguments['start'] = $argument; } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { $sortedArguments['end'] = $parsedDate; $originalArguments['end'] = $argument; } elseif (!isset($sortedArguments['recurrences']) && !isset($sortedArguments['end']) && (\is_int($argument) || \is_float($argument)) && $argument >= 0 ) { $sortedArguments['recurrences'] = $argument; } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { $optionsSet = true; $sortedArguments['options'] = (((int) $this->options) | ((int) $argument)); } elseif ($parsedTimezone = self::makeTimezone($argument)) { $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($raw === null && isset($sortedArguments['start'])) { $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1); if (\is_float($end)) { $end = $end === INF ? PHP_INT_MAX : (int) round($end); } $raw = [ $sortedArguments['start'], $sortedArguments['interval'] ?? CarbonInterval::day(), $end, ]; } $this->setFromAssociativeArray($sortedArguments); if ($this->startDate === null) { $dateClass = $this->dateClass; $this->setStartDate($dateClass::now()); } if ($this->dateInterval === null) { $this->setDateInterval(CarbonInterval::day()); $this->isDefaultInterval = true; } if ($this->options === null) { $this->setOptions(0); } parent::__construct( $this->startDate, $this->dateInterval, $this->endDate ?? max(1, min(2147483639, $this->recurrences ?? 1)), $this->options, ); $this->constructed = true; } /** * Get a copy of the instance. */ public function copy(): static { return clone $this; } /** * Prepare the instance to be set (self if mutable to be mutated, * copy if immutable to generate a new instance). */ protected function copyIfImmutable(): static { return $this; } /** * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. */ protected function getGetter(string $name): ?callable { return match (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) { 'start', 'start_date' => [$this, 'getStartDate'], 'end', 'end_date' => [$this, 'getEndDate'], 'interval', 'date_interval' => [$this, 'getDateInterval'], 'recurrences' => [$this, 'getRecurrences'], 'include_start_date' => [$this, 'isStartIncluded'], 'include_end_date' => [$this, 'isEndIncluded'], 'current' => [$this, 'current'], 'locale' => [$this, 'locale'], 'tzname', 'tz_name' => fn () => match (true) { $this->timezoneSetting === null => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, $this->timezoneSetting instanceof DateTimeZone => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, default => null, }; } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function get(string $name) { $getter = $this->getGetter($name); if ($getter) { return $getter(); } throw new UnknownGetterException($name); } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function __get(string $name) { return $this->get($name); } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset(string $name): bool { return $this->getGetter($name) !== null; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Set the iteration item class. * * @param string $dateClass * * @return static */ public function setDateClass(string $dateClass) { if (!is_a($dateClass, CarbonInterface::class, true)) { throw new NotACarbonClassException($dateClass); } $self = $this->copyIfImmutable(); $self->dateClass = $dateClass; if (is_a($dateClass, Carbon::class, true)) { $self->options = $self->options & ~static::IMMUTABLE; } elseif (is_a($dateClass, CarbonImmutable::class, true)) { $self->options = $self->options | static::IMMUTABLE; } return $self; } /** * Returns iteration item date class. * * @return string */ public function getDateClass(): string { return $this->dateClass; } /** * Change the period date interval. * * @param DateInterval|Unit|string|int $interval * @param Unit|string $unit the unit of $interval if it's a number * * @throws InvalidIntervalException * * @return static */ public function setDateInterval(mixed $interval, Unit|string|null $unit = null): static { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->name; } if (!$interval = CarbonInterval::make($interval, $unit)) { throw new InvalidIntervalException('Invalid interval.'); } if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) { throw new InvalidIntervalException('Empty interval is not accepted.'); } $self = $this->copyIfImmutable(); $self->dateInterval = $interval; $self->isDefaultInterval = false; $self->handleChangedParameters(); return $self; } /** * Reset the date interval to the default value. * * Difference with simply setting interval to 1-day is that P1D will not appear when calling toIso8601String() * and also next adding to the interval won't include the default 1-day. */ public function resetDateInterval(): static { $self = $this->copyIfImmutable(); $self->setDateInterval(CarbonInterval::day()); $self->isDefaultInterval = true; return $self; } /** * Invert the period date interval. */ public function invertDateInterval(): static { return $this->setDateInterval($this->dateInterval->invert()); } /** * Set start and end date. * * @param DateTime|DateTimeInterface|string $start * @param DateTime|DateTimeInterface|string|null $end * * @return static */ public function setDates(mixed $start, mixed $end): static { return $this->setStartDate($start)->setEndDate($end); } /** * Change the period options. * * @param int|null $options * * @return static */ public function setOptions(?int $options): static { $self = $this->copyIfImmutable(); $self->options = $options ?? 0; $self->handleChangedParameters(); return $self; } /** * Get the period options. */ public function getOptions(): int { return $this->options ?? 0; } /** * Toggle given options on or off. * * @param int $options * @param bool|null $state * * @throws InvalidArgumentException * * @return static */ public function toggleOptions(int $options, ?bool $state = null): static { $self = $this->copyIfImmutable(); if ($state === null) { $state = ($this->options & $options) !== $options; } return $self->setOptions( $state ? $this->options | $options : $this->options & ~$options, ); } /** * Toggle EXCLUDE_START_DATE option. */ public function excludeStartDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_START_DATE, $state); } /** * Toggle EXCLUDE_END_DATE option. */ public function excludeEndDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_END_DATE, $state); } /** * Get the underlying date interval. */ public function getDateInterval(): CarbonInterval { return $this->dateInterval->copy(); } /** * Get start date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getStartDate(?string $rounding = null): CarbonInterface { $date = $this->startDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get end date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getEndDate(?string $rounding = null): ?CarbonInterface { if (!$this->endDate) { return null; } $date = $this->endDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get number of recurrences. */ #[ReturnTypeWillChange] public function getRecurrences(): int|float|null { return $this->carbonRecurrences; } /** * Returns true if the start date should be excluded. */ public function isStartExcluded(): bool { return ($this->options & static::EXCLUDE_START_DATE) !== 0; } /** * Returns true if the end date should be excluded. */ public function isEndExcluded(): bool { return ($this->options & static::EXCLUDE_END_DATE) !== 0; } /** * Returns true if the start date should be included. */ public function isStartIncluded(): bool { return !$this->isStartExcluded(); } /** * Returns true if the end date should be included. */ public function isEndIncluded(): bool { return !$this->isEndExcluded(); } /** * Return the start if it's included by option, else return the start + 1 period interval. */ public function getIncludedStartDate(): CarbonInterface { $start = $this->getStartDate(); if ($this->isStartExcluded()) { return $start->add($this->getDateInterval()); } return $start; } /** * Return the end if it's included by option, else return the end - 1 period interval. * Warning: if the period has no fixed end, this method will iterate the period to calculate it. */ public function getIncludedEndDate(): CarbonInterface { $end = $this->getEndDate(); if (!$end) { return $this->calculateEnd(); } if ($this->isEndExcluded()) { return $end->sub($this->getDateInterval()); } return $end; } /** * Add a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function addFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); $self->filters[] = $tuple; $self->handleChangedParameters(); return $self; } /** * Prepend a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function prependFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); array_unshift($self->filters, $tuple); $self->handleChangedParameters(); return $self; } /** * Remove a filter by instance or name. */ public function removeFilter(callable|string $filter): static { $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; $self->filters = array_values(array_filter( $this->filters, static fn ($tuple) => $tuple[$key] !== $filter, )); $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Return whether given instance or name is in the filter stack. */ public function hasFilter(callable|string $filter): bool { $key = \is_callable($filter) ? 0 : 1; foreach ($this->filters as $tuple) { if ($tuple[$key] === $filter) { return true; } } return false; } /** * Get filters stack. */ public function getFilters(): array { return $this->filters; } /** * Set filters stack. */ public function setFilters(array $filters): static { $self = $this->copyIfImmutable(); $self->filters = $filters; $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Reset filters stack. */ public function resetFilters(): static { $self = $this->copyIfImmutable(); $self->filters = []; if ($self->endDate !== null) { $self->filters[] = [static::END_DATE_FILTER, null]; } if ($self->carbonRecurrences !== null) { $self->filters[] = [static::RECURRENCES_FILTER, null]; } $self->handleChangedParameters(); return $self; } /** * Add a recurrences filter (set maximum number of recurrences). * * @throws InvalidArgumentException */ public function setRecurrences(int|float|null $recurrences): static { if ($recurrences === null) { return $this->removeFilter(static::RECURRENCES_FILTER); } if ($recurrences < 0) { throw new InvalidPeriodParameterException('Invalid number of recurrences.'); } /** @var self $self */ $self = $this->copyIfImmutable(); $self->carbonRecurrences = $recurrences === INF ? INF : (int) $recurrences; if (!$self->hasFilter(static::RECURRENCES_FILTER)) { return $self->addFilter(static::RECURRENCES_FILTER); } $self->handleChangedParameters(); return $self; } /** * Change the period start date. * * @param DateTime|DateTimeInterface|string $date * @param bool|null $inclusive * * @throws InvalidPeriodDateException * * @return static */ public function setStartDate(mixed $date, ?bool $inclusive = null): static { if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date, $this->timezone))) { throw new InvalidPeriodDateException('Invalid start date.'); } $self = $this->copyIfImmutable(); $self->startDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); } return $self; } /** * Change the period end date. * * @param DateTime|DateTimeInterface|string|null $date * @param bool|null $inclusive * * @throws \InvalidArgumentException * * @return static */ public function setEndDate(mixed $date, ?bool $inclusive = null): static { if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date, $this->timezone)) { throw new InvalidPeriodDateException('Invalid end date.'); } if (!$date) { return $this->removeFilter(static::END_DATE_FILTER); } $self = $this->copyIfImmutable(); $self->endDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); } if (!$self->hasFilter(static::END_DATE_FILTER)) { return $self->addFilter(static::END_DATE_FILTER); } $self->handleChangedParameters(); return $self; } /** * Check if the current position is valid. */ public function valid(): bool { return $this->validateCurrentDate() === true; } /** * Return the current key. */ public function key(): ?int { return $this->valid() ? $this->key : null; } /** * Return the current date. */ public function current(): ?CarbonInterface { return $this->valid() ? $this->prepareForReturn($this->carbonCurrent) : null; } /** * Move forward to the next date. * * @throws RuntimeException */ public function next(): void { if ($this->carbonCurrent === null) { $this->rewind(); } if ($this->validationResult !== static::END_ITERATION) { $this->key++; $this->incrementCurrentDateUntilValid(); } } /** * Rewind to the start date. * * Iterating over a date in the UTC timezone avoids bug during backward DST change. * * @see https://bugs.php.net/bug.php?id=72255 * @see https://bugs.php.net/bug.php?id=74274 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time * * @throws RuntimeException */ public function rewind(): void { $this->key = 0; $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate); $settings = $this->getSettings(); if ($this->hasLocalTranslator()) { $settings['locale'] = $this->getTranslatorLocale(); } $this->carbonCurrent->settings($settings); $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null; if ($this->timezone) { $this->carbonCurrent = $this->carbonCurrent->utc(); } $this->validationResult = null; if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { $this->incrementCurrentDateUntilValid(); } } /** * Skip iterations and returns iteration state (false if ended, true if still valid). * * @param int $count steps number to skip (1 by default) * * @return bool */ public function skip(int $count = 1): bool { for ($i = $count; $this->valid() && $i > 0; $i--) { $this->next(); } return $this->valid(); } /** * Format the date period as ISO 8601. */ public function toIso8601String(): string { $parts = []; if ($this->carbonRecurrences !== null) { $parts[] = 'R'.$this->carbonRecurrences; } $parts[] = $this->startDate->toIso8601String(); if (!$this->isDefaultInterval) { $parts[] = $this->dateInterval->spec(); } if ($this->endDate !== null) { $parts[] = $this->endDate->toIso8601String(); } return implode('/', $parts); } /** * Convert the date period into a string. */ public function toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if ($format instanceof Closure) { return $format($this); } $translator = ([$this->dateClass, 'getTranslator'])(); $parts = []; $format = $format ?? ( !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) ? 'Y-m-d H:i:s' : 'Y-m-d' ); if ($this->carbonRecurrences !== null) { $parts[] = $this->translate('period_recurrences', [], $this->carbonRecurrences, $translator); } $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([ 'join' => true, ])], null, $translator); $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator); if ($this->endDate !== null) { $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator); } $result = implode(' ', $parts); return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1); } /** * Format the date period as ISO 8601. */ public function spec(): string { return $this->toIso8601String(); } /** * Cast the current instance into the given class. * * @param string $className The $className::instance() method will be called to cast the current object. * * @return DatePeriod|object */ public function cast(string $className): object { if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( $this->rawDate($this->getStartDate()), $this->getDateInterval(), $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0, ); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Return native DatePeriod PHP object matching the current instance. * * @example * ``` * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod()); * ``` */ public function toDatePeriod(): DatePeriod { return $this->cast(DatePeriod::class); } /** * Return `true` if the period has no custom filter and is guaranteed to be endless. * * Note that we can't check if a period is endless as soon as it has custom filters * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in * a way we can't predict without actually iterating the period. */ public function isUnfilteredAndEndLess(): bool { foreach ($this->filters as $filter) { switch ($filter) { case [static::RECURRENCES_FILTER, null]: if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) { return false; } break; case [static::END_DATE_FILTER, null]: if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { return false; } break; default: return false; } } return true; } /** * Convert the date period into an array without changing current iteration state. * * @return CarbonInterface[] */ public function toArray(): array { if ($this->isUnfilteredAndEndLess()) { throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); } $state = [ $this->key, $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null, $this->validationResult, ]; $result = iterator_to_array($this); [$this->key, $this->carbonCurrent, $this->validationResult] = $state; return $result; } /** * Count dates in the date period. */ public function count(): int { return \count($this->toArray()); } /** * Return the first date in the date period. */ public function first(): ?CarbonInterface { if ($this->isUnfilteredAndEndLess()) { foreach ($this as $date) { $this->rewind(); return $date; } return null; } return ($this->toArray() ?: [])[0] ?? null; } /** * Return the last date in the date period. */ public function last(): ?CarbonInterface { $array = $this->toArray(); return $array ? $array[\count($array) - 1] : null; } /** * Convert the date period into a string. */ public function __toString(): string { return $this->toString(); } /** * Add aliases for setters. * * CarbonPeriod::days(3)->hours(5)->invert() * ->sinceNow()->until('2010-01-10') * ->filter(...) * ->count() * * Note: We use magic method to let static and instance aliases with the same names. */ public function __call(string $method, array $parameters): mixed { if (static::hasMacro($method)) { return static::bindMacroContext($this, fn () => $this->callMacro($method, $parameters)); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } $count = \count($parameters); switch ($method) { case 'start': case 'since': if ($count === 0) { return $this->getStartDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setStartDate(...$parameters); case 'sinceNow': return $this->setStartDate(new Carbon(), ...$parameters); case 'end': case 'until': if ($count === 0) { return $this->getEndDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setEndDate(...$parameters); case 'untilNow': return $this->setEndDate(new Carbon(), ...$parameters); case 'dates': case 'between': self::setDefaultParameters($parameters, [ [0, 'start', null], [1, 'end', null], ]); return $this->setDates(...$parameters); case 'recurrences': case 'times': if ($count === 0) { return $this->getRecurrences(); } self::setDefaultParameters($parameters, [ [0, 'recurrences', null], ]); return $this->setRecurrences(...$parameters); case 'options': if ($count === 0) { return $this->getOptions(); } self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->setOptions(...$parameters); case 'toggle': self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->toggleOptions(...$parameters); case 'filter': case 'push': return $this->addFilter(...$parameters); case 'prepend': return $this->prependFilter(...$parameters); case 'filters': if ($count === 0) { return $this->getFilters(); } self::setDefaultParameters($parameters, [ [0, 'filters', []], ]); return $this->setFilters(...$parameters); case 'interval': case 'each': case 'every': case 'step': case 'stepBy': if ($count === 0) { return $this->getDateInterval(); } return $this->setDateInterval(...$parameters); case 'invert': return $this->invertDateInterval(); case 'years': case 'year': case 'months': case 'month': case 'weeks': case 'week': case 'days': case 'dayz': case 'day': case 'hours': case 'hour': case 'minutes': case 'minute': case 'seconds': case 'second': case 'milliseconds': case 'millisecond': case 'microseconds': case 'microsecond': return $this->setDateInterval(( // Override default P1D when instantiating via fluent setters. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] )(...$parameters)); } $dateClass = $this->dateClass; if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { throw new UnknownMethodException($method); } return $this; } /** * Set the instance's timezone from a string or object and apply it to start/end. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->setTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->setTimezone($timezone)); } return $self; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } return $self; } /** * Returns the end is set, else calculated from start and recurrences. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. * * @return CarbonInterface */ public function calculateEnd(?string $rounding = null): CarbonInterface { if ($end = $this->getEndDate($rounding)) { return $end; } if ($this->dateInterval->isEmpty()) { return $this->getStartDate($rounding); } $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); if ($date && $rounding) { $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); } return $date; } private function getEndFromRecurrences(): ?CarbonInterface { if ($this->carbonRecurrences === null) { throw new UnreachableException( "Could not calculate period end without either explicit end or recurrences.\n". "If you're looking for a forever-period, use ->setRecurrences(INF).", ); } if ($this->carbonRecurrences === INF) { $start = $this->getStartDate(); return $start < $start->avoidMutation()->add($this->getDateInterval()) ? CarbonImmutable::endOfTime() : CarbonImmutable::startOfTime(); } if ($this->filters === [[static::RECURRENCES_FILTER, null]]) { return $this->getStartDate()->avoidMutation()->add( $this->getDateInterval()->times( $this->carbonRecurrences - ($this->isStartExcluded() ? 0 : 1), ), ); } return null; } private function iterateUntilEnd(): ?CarbonInterface { $attempts = 0; $date = null; foreach ($this as $date) { if (++$attempts > static::END_MAX_ATTEMPTS) { throw new UnreachableException( 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.', ); } } return $date; } /** * Returns true if the current period overlaps the given one (if 1 parameter passed) * or the period between 2 dates (if 2 parameters passed). * * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd * * @return bool */ public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool { $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; if (!($range instanceof self)) { $range = static::create($range); } [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); return $end > $rangeStart && $rangeEnd > $start; } /** * Execute a given function on each date of the period. * * @example * ``` * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) { * echo $date->diffInDays('2020-12-25')." days before Christmas!\n"; * }); * ``` */ public function forEach(callable $callback): void { foreach ($this as $date) { $callback($date); } } /** * Execute a given function on each date of the period and yield the result of this function. * * @example * ``` * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24'); * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) { * return $date->diffInDays('2020-12-25').' days before Christmas!'; * }))); * ``` */ public function map(callable $callback): Generator { foreach ($this as $date) { yield $callback($date); } } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. * * @see equalTo() */ public function eq(mixed $period): bool { return $this->equalTo($period); } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. */ public function equalTo(mixed $period): bool { if (!($period instanceof self)) { $period = self::make($period); } $end = $this->getEndDate(); return $period !== null && $this->getDateInterval()->eq($period->getDateInterval()) && $this->getStartDate()->eq($period->getStartDate()) && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. * * @see notEqualTo() */ public function ne(mixed $period): bool { return $this->notEqualTo($period); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. */ public function notEqualTo(mixed $period): bool { return !$this->eq($period); } /** * Determines if the start date is before another given date. * (Rather start/end are included by options is ignored.) */ public function startsBefore(mixed $date = null): bool { return $this->getStartDate()->lessThan($this->resolveCarbon($date)); } /** * Determines if the start date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsBeforeOrAt(mixed $date = null): bool { return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is after another given date. * (Rather start/end are included by options is ignored.) */ public function startsAfter(mixed $date = null): bool { return $this->getStartDate()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the start date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAfterOrAt(mixed $date = null): bool { return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAt(mixed $date = null): bool { return $this->getStartDate()->equalTo($this->resolveCarbon($date)); } /** * Determines if the end date is before another given date. * (Rather start/end are included by options is ignored.) */ public function endsBefore(mixed $date = null): bool { return $this->calculateEnd()->lessThan($this->resolveCarbon($date)); } /** * Determines if the end date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsBeforeOrAt(mixed $date = null): bool { return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is after another given date. * (Rather start/end are included by options is ignored.) */ public function endsAfter(mixed $date = null): bool { return $this->calculateEnd()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the end date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAfterOrAt(mixed $date = null): bool { return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAt(mixed $date = null): bool { return $this->calculateEnd()->equalTo($this->resolveCarbon($date)); } /** * Return true if start date is now or later. * (Rather start/end are included by options is ignored.) */ public function isStarted(): bool { return $this->startsBeforeOrAt(); } /** * Return true if end date is now or later. * (Rather start/end are included by options is ignored.) */ public function isEnded(): bool { return $this->endsBeforeOrAt(); } /** * Return true if now is between start date (included) and end date (excluded). * (Rather start/end are included by options is ignored.) */ public function isInProgress(): bool { return $this->isStarted() && !$this->isEnded(); } /** * Round the current instance at the given unit with given precision if specified and the given function. */ public function roundUnit( string $unit, DateInterval|float|int|string|null $precision = 1, callable|string $function = 'round', ): static { $self = $this->copyIfImmutable(); $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); if ($self->endDate) { $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); } /** * Truncate the current instance at the given unit with given precision if specified. */ public function floorUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. */ public function ceilUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function round( DateInterval|float|int|string|null $precision = null, callable|string $function = 'round', ): static { return $this->roundWith( $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(), $function ); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function floor(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified (else period interval is used). */ public function ceil(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'ceil'); } /** * Specify data which should be serialized to JSON. * * @link https://php.net/manual/en/jsonserializable.jsonserialize.php * * @return CarbonInterface[] */ public function jsonSerialize(): array { return $this->toArray(); } /** * Return true if the given date is between start and end. */ public function contains(mixed $date = null): bool { $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : ''); $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : ''); return $this->$startMethod($date) && $this->$endMethod($date); } /** * Return true if the current period follows a given other period (with no overlap). * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31] * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function follows(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval())); } /** * Return true if the given other period follows the current one (with no overlap). * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12] * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function isFollowedBy(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $period->follows($this); } /** * Return true if the given period either follows or is followed by the current one. * * @see follows() * @see isFollowedBy() */ public function isConsecutiveWith(mixed $period, mixed ...$arguments): bool { return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments); } public function __debugInfo(): array { $info = $this->baseDebugInfo(); unset( $info['start'], $info['end'], $info['interval'], $info['include_start_date'], $info['include_end_date'], $info['constructed'], $info["\0*\0constructed"], ); return $info; } public function __unserialize(array $data): void { try { $values = array_combine( array_map( static fn (string $key): string => preg_replace('/^\0\*\0/', '', $key), array_keys($data), ), $data, ); $this->initializeSerialization($values); foreach ($values as $key => $value) { if ($value === null) { continue; } $property = match ($key) { 'tzName' => $this->setTimezone(...), 'options' => $this->setOptions(...), 'recurrences' => $this->setRecurrences(...), 'current' => function (mixed $current): void { if (!($current instanceof CarbonInterface)) { $current = $this->resolveCarbon($current); } $this->carbonCurrent = $current; }, 'start' => 'startDate', 'interval' => $this->setDateInterval(...), 'end' => 'endDate', 'key' => null, 'include_start_date' => function (bool $included): void { $this->excludeStartDate(!$included); }, 'include_end_date' => function (bool $included): void { $this->excludeEndDate(!$included); }, default => $key, }; if ($property === null) { continue; } if (\is_callable($property)) { $property($value); continue; } if ($value instanceof DateTimeInterface && !($value instanceof CarbonInterface)) { $value = ($value instanceof DateTime) ? Carbon::instance($value) : CarbonImmutable::instance($value); } try { $this->$property = $value; } catch (Throwable) { // Must be ignored for backward-compatibility } } if (\array_key_exists('carbonRecurrences', $values)) { $this->carbonRecurrences = $values['carbonRecurrences']; } elseif (((int) ($values['recurrences'] ?? 0)) <= 1 && $this->endDate !== null) { $this->carbonRecurrences = null; } } catch (Throwable $e) { // @codeCoverageIgnoreStart if (!method_exists(parent::class, '__unserialize')) { throw $e; } parent::__unserialize($data); // @codeCoverageIgnoreEnd } } /** * Update properties after removing built-in filters. */ protected function updateInternalState(): void { if (!$this->hasFilter(static::END_DATE_FILTER)) { $this->endDate = null; } if (!$this->hasFilter(static::RECURRENCES_FILTER)) { $this->carbonRecurrences = null; } } /** * Create a filter tuple from raw parameters. * * Will create an automatic filter callback for one of Carbon's is* methods. */ protected function createFilterTuple(array $parameters): array { $method = array_shift($parameters); if (!$this->isCarbonPredicateMethod($method)) { return [$method, array_shift($parameters)]; } return [static fn ($date) => ([$date, $method])(...$parameters), $method]; } /** * Return whether given callable is a string pointing to one of Carbon's is* methods * and should be automatically converted to a filter callback. */ protected function isCarbonPredicateMethod(callable|string $callable): bool { return \is_string($callable) && str_starts_with($callable, 'is') && (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable)); } /** * Recurrences filter callback (limits number of recurrences). * * @SuppressWarnings(UnusedFormalParameter) */ protected function filterRecurrences(CarbonInterface $current, int $key): bool|callable { if ($key < $this->carbonRecurrences) { return true; } return static::END_ITERATION; } /** * End date filter callback. * * @return bool|static::END_ITERATION */ protected function filterEndDate(CarbonInterface $current): bool|callable { if (!$this->isEndExcluded() && $current == $this->endDate) { return true; } if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) { return true; } return static::END_ITERATION; } /** * End iteration filter callback. * * @return static::END_ITERATION */ protected function endIteration(): callable { return static::END_ITERATION; } /** * Handle change of the parameters. */ protected function handleChangedParameters(): void { if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { $this->dateClass = CarbonImmutable::class; } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { $this->dateClass = Carbon::class; } $this->validationResult = null; } /** * Validate current date and stop iteration when necessary. * * Returns true when current date is valid, false if it is not, or static::END_ITERATION * when iteration should be stopped. * * @return bool|static::END_ITERATION */ protected function validateCurrentDate(): bool|callable { if ($this->carbonCurrent === null) { $this->rewind(); } // Check after the first rewind to avoid repeating the initial validation. return $this->validationResult ?? ($this->validationResult = $this->checkFilters()); } /** * Check whether current value and key pass all the filters. * * @return bool|static::END_ITERATION */ protected function checkFilters(): bool|callable { $current = $this->prepareForReturn($this->carbonCurrent); foreach ($this->filters as $tuple) { $result = \call_user_func($tuple[0], $current->avoidMutation(), $this->key, $this); if ($result === static::END_ITERATION) { return static::END_ITERATION; } if (!$result) { return false; } } return true; } /** * Prepare given date to be returned to the external logic. * * @param CarbonInterface $date * * @return CarbonInterface */ protected function prepareForReturn(CarbonInterface $date) { $date = ([$this->dateClass, 'make'])($date); if ($this->timezone) { return $date->setTimezone($this->timezone); } return $date; } /** * Keep incrementing the current date until a valid date is found or the iteration is ended. * * @throws RuntimeException */ protected function incrementCurrentDateUntilValid(): void { $attempts = 0; do { $this->carbonCurrent = $this->carbonCurrent->add($this->dateInterval); $this->validationResult = null; if (++$attempts > static::NEXT_MAX_ATTEMPTS) { throw new UnreachableException('Could not find next valid date.'); } } while ($this->validateCurrentDate() === false); } /** * Call given macro. */ protected function callMacro(string $name, array $parameters): mixed { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date * * @return \Carbon\CarbonInterface */ protected function resolveCarbon($date = null) { return $this->getStartDate()->nowWithSameTz()->carbonize($date); } /** * Resolve passed arguments or DatePeriod to a CarbonPeriod object. */ protected function resolveCarbonPeriod(mixed $period, mixed ...$arguments): self { if ($period instanceof self) { return $period; } return $period instanceof DatePeriod ? static::instance($period) : static::create($period, ...$arguments); } private function orderCouple($first, $second): array { return $first > $second ? [$second, $first] : [$first, $second]; } private function makeDateTime($value): ?DateTimeInterface { if ($value instanceof DateTimeInterface) { return $value; } if ($value instanceof WeekDay || $value instanceof Month) { $dateClass = $this->dateClass; return new $dateClass($value, $this->timezoneSetting); } if (\is_string($value)) { $value = trim($value); if (!preg_match('/^P[\dT]/', $value) && !preg_match('/^R\d/', $value) && preg_match('/[a-z\d]/i', $value) ) { $dateClass = $this->dateClass; return $dateClass::parse($value, $this->timezoneSetting); } } return null; } private function isInfiniteDate($date): bool { return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); } private function rawDate($date): ?DateTimeInterface { if ($date === false || $date === null) { return null; } if ($date instanceof CarbonInterface) { return $date->isMutable() ? $date->toDateTime() : $date->toDateTimeImmutable(); } if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { return $date; } $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); } private static function setDefaultParameters(array &$parameters, array $defaults): void { foreach ($defaults as [$index, $name, $value]) { if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { $parameters[$index] = $value; } } } private function setFromAssociativeArray(array $parameters): void { if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['end'])) { $this->setEndDate($parameters['end']); } if (isset($parameters['recurrences'])) { $this->setRecurrences($parameters['recurrences']); } if (isset($parameters['interval'])) { $this->setDateInterval($parameters['interval']); } if (isset($parameters['options'])) { $this->setOptions($parameters['options']); } } private function configureTimezone(DateTimeZone $timezone, array $sortedArguments, array $originalArguments): array { $this->setTimezone($timezone); if (\is_string($originalArguments['start'] ?? null)) { $sortedArguments['start'] = $this->makeDateTime($originalArguments['start']); } if (\is_string($originalArguments['end'] ?? null)) { $sortedArguments['end'] = $this->makeDateTime($originalArguments['end']); } return $sortedArguments; } private function initializeSerialization(array $values): void { $serializationBase = [ 'start' => $values['start'] ?? $values['startDate'] ?? null, 'current' => $values['current'] ?? $values['carbonCurrent'] ?? null, 'end' => $values['end'] ?? $values['endDate'] ?? null, 'interval' => $values['interval'] ?? $values['dateInterval'] ?? null, 'recurrences' => max(1, (int) ($values['recurrences'] ?? $values['carbonRecurrences'] ?? 1)), 'include_start_date' => $values['include_start_date'] ?? true, 'include_end_date' => $values['include_end_date'] ?? false, ]; foreach (['start', 'current', 'end'] as $dateProperty) { if ($serializationBase[$dateProperty] instanceof Carbon) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTime(); } elseif ($serializationBase[$dateProperty] instanceof CarbonInterface) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTimeImmutable(); } } if ($serializationBase['interval'] instanceof CarbonInterval) { $serializationBase['interval'] = $serializationBase['interval']->toDateInterval(); } // @codeCoverageIgnoreStart if (method_exists(parent::class, '__unserialize')) { parent::__unserialize($serializationBase); return; } $excludeStart = !($values['include_start_date'] ?? true); $includeEnd = $values['include_end_date'] ?? true; parent::__construct( $serializationBase['start'], $serializationBase['interval'], $serializationBase['end'] ?? $serializationBase['recurrences'], ($excludeStart ? self::EXCLUDE_START_DATE : 0) | ($includeEnd && \defined('DatePeriod::INCLUDE_END_DATE') ? self::INCLUDE_END_DATE : 0), ); // @codeCoverageIgnoreEnd } }
PHP
{ "end_line": 1403, "name": "rewind", "signature": "public function rewind(): void", "start_line": 1381 }
{ "class_name": "CarbonPeriod", "class_signature": "class CarbonPeriod implements Countable, JsonSerializable, UnitValue", "namespace": "Carbon" }
toIso8601String
Carbon/src/Carbon/CarbonPeriod.php
public function toIso8601String(): string { $parts = []; if ($this->carbonRecurrences !== null) { $parts[] = 'R'.$this->carbonRecurrences; } $parts[] = $this->startDate->toIso8601String(); if (!$this->isDefaultInterval) { $parts[] = $this->dateInterval->spec(); } if ($this->endDate !== null) { $parts[] = $this->endDate->toIso8601String(); } return implode('/', $parts); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotACarbonClassException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnreachableException; use Carbon\Traits\DeprecatedPeriodProperties; use Carbon\Traits\IntervalRounding; use Carbon\Traits\LocalFactory; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Throwable; // @codeCoverageIgnoreStart require PHP_VERSION < 8.2 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php' : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php'; // @codeCoverageIgnoreEnd /** * Substitution of DatePeriod with some modifications and many more features. * * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. * @method static static since($date = null, $inclusive = null) Alias for start(). * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. * @method static static until($date = null, $inclusive = null) Alias for end(). * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. * @method static static times($recurrences = null) Alias for recurrences(). * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance. * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. * @method static static push($callback, $name = null) Alias for filter(). * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance. * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. * @method static static year($years = 1) Alias for years(). * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. * @method static static month($months = 1) Alias for months(). * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. * @method static static week($weeks = 1) Alias for weeks(). * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. * @method static static dayz($days = 1) Alias for days(). * @method static static day($days = 1) Alias for days(). * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. * @method static static hour($hours = 1) Alias for hours(). * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. * @method static static minute($minutes = 1) Alias for minutes(). * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. * @method static static second($seconds = 1) Alias for seconds(). * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * * @mixin DeprecatedPeriodProperties * * @SuppressWarnings(TooManyFields) * @SuppressWarnings(CamelCasePropertyName) * @SuppressWarnings(CouplingBetweenObjects) */ class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue { use LocalFactory; use IntervalRounding; use Mixin { Mixin::mixin as baseMixin; } use Options { Options::__debugInfo as baseDebugInfo; } use ToStringFormat; /** * Built-in filter for limit by recurrences. * * @var callable */ public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; /** * Built-in filter for limit to an end. * * @var callable */ public const END_DATE_FILTER = [self::class, 'filterEndDate']; /** * Special value which can be returned by filters to end iteration. Also a filter. * * @var callable */ public const END_ITERATION = [self::class, 'endIteration']; /** * Exclude end date from iteration. * * @var int */ public const EXCLUDE_END_DATE = 8; /** * Yield CarbonImmutable instances. * * @var int */ public const IMMUTABLE = 4; /** * Number of maximum attempts before giving up on finding next valid date. * * @var int */ public const NEXT_MAX_ATTEMPTS = 1000; /** * Number of maximum attempts before giving up on finding end date. * * @var int */ public const END_MAX_ATTEMPTS = 10000; /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = Carbon::class; /** * The registered macros. */ protected static array $macros = []; /** * Date class of iteration items. */ protected string $dateClass = Carbon::class; /** * Underlying date interval instance. Always present, one day by default. */ protected ?CarbonInterval $dateInterval = null; /** * True once __construct is finished. */ protected bool $constructed = false; /** * Whether current date interval was set by default. */ protected bool $isDefaultInterval = false; /** * The filters stack. */ protected array $filters = []; /** * Period start date. Applied on rewind. Always present, now by default. */ protected ?CarbonInterface $startDate = null; /** * Period end date. For inverted interval should be before the start date. Applied via a filter. */ protected ?CarbonInterface $endDate = null; /** * Limit for number of recurrences. Applied via a filter. */ protected int|float|null $carbonRecurrences = null; /** * Iteration options. */ protected ?int $options = null; /** * Index of current date. Always sequential, even if some dates are skipped by filters. * Equal to null only before the first iteration. */ protected int $key = 0; /** * Current date. May temporarily hold unaccepted value when looking for a next valid date. * Equal to null only before the first iteration. */ protected ?CarbonInterface $carbonCurrent = null; /** * Timezone of current date. Taken from the start date. */ protected ?DateTimeZone $timezone = null; /** * The cached validation result for current date. */ protected array|string|bool|null $validationResult = null; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; public function getIterator(): Generator { $this->rewind(); while ($this->valid()) { $key = $this->key(); $value = $this->current(); yield $key => $value; $this->next(); } } /** * Make a CarbonPeriod instance from given variable if possible. */ public static function make(mixed $var): ?static { try { return static::instance($var); } catch (NotAPeriodException) { return static::create($var); } } /** * Create a new instance from a DatePeriod or CarbonPeriod object. */ public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); } /** * Create a new instance. */ public static function create(...$params): static { return static::createFromArray($params); } /** * Create a new instance from an array of parameters. */ public static function createFromArray(array $params): static { return new static(...$params); } /** * Create CarbonPeriod from ISO 8601 string. */ public static function createFromIso(string $iso, ?int $options = null): static { $params = static::parseIso8601($iso); $instance = static::createFromArray($params); $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options; $instance->handleChangedParameters(); return $instance; } public static function createFromISO8601String(string $iso, ?int $options = null): static { return self::createFromIso($iso, $options); } /** * Return whether the given interval contains non-zero value of any time unit. */ protected static function intervalHasTime(DateInterval $interval): bool { return $interval->h || $interval->i || $interval->s || $interval->f; } /** * Return whether given variable is an ISO 8601 specification. * * Note: Check is very basic, as actual validation will be done later when parsing. * We just want to ensure that variable is not any other type of valid parameter. */ protected static function isIso8601(mixed $var): bool { if (!\is_string($var)) { return false; } // Match slash but not within a timezone name. $part = '[a-z]+(?:[_-][a-z]+)*'; preg_match("#\b$part/$part\b|(/)#i", $var, $match); return isset($match[1]); } /** * Parse given ISO 8601 string into an array of arguments. * * @SuppressWarnings(ElseExpression) */ protected static function parseIso8601(string $iso): array { $result = []; $interval = null; $start = null; $end = null; $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = self::makeInterval($part)) { $interval = $part; } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); } $result[] = $parsed; } return $result; } /** * Add missing parts of the target date from the source date. */ protected static function addMissingParts(string $source, string $target): string { $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); return $count ? $result : $target; } private static function makeInterval(mixed $input): ?CarbonInterval { try { return CarbonInterval::make($input); } catch (Throwable) { return null; } } private static function makeTimezone(mixed $input): ?CarbonTimeZone { if (!\is_string($input)) { return null; } try { return CarbonTimeZone::create($input); } catch (Throwable) { return null; } } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonPeriod::macro('middle', function () { * return $this->getStartDate()->average($this->getEndDate()); * }); * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonPeriod::mixin(new class { * public function addDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->addDays($count) * )->setEndDate( * $this->getEndDate()->addDays($count) * ); * }; * } * public function subDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->subDays($count) * )->setEndDate( * $this->getEndDate()->subDays($count) * ); * }; * } * }); * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); * ``` * * @throws ReflectionException */ public static function mixin(object|string $mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Provide static proxy for instance aliases. */ public static function __callStatic(string $method, array $parameters): mixed { $date = new static(); if (static::hasMacro($method)) { return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters)); } return $date->$method(...$parameters); } /** * CarbonPeriod constructor. * * @SuppressWarnings(ElseExpression) * * @throws InvalidArgumentException */ public function __construct(...$arguments) { $raw = null; if (isset($arguments['raw'])) { $raw = $arguments['raw']; $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false; if (isset($arguments['dateClass'])) { $this->dateClass = $arguments['dateClass']; } $arguments = $raw; } // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. $argumentsCount = \count($arguments); if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { array_splice($arguments, 0, 1, static::parseIso8601($iso)); } if ($argumentsCount === 1) { if ($arguments[0] instanceof self) { $arguments = [ $arguments[0]->getStartDate(), $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(), $arguments[0]->getDateInterval(), $arguments[0]->getOptions(), ]; } elseif ($arguments[0] instanceof DatePeriod) { $arguments = [ $arguments[0]->start, $arguments[0]->end ?: ($arguments[0]->recurrences - 1), $arguments[0]->interval, $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, ]; } } if (is_a($this->dateClass, DateTimeImmutable::class, true)) { $this->options = static::IMMUTABLE; } $optionsSet = false; $originalArguments = []; $sortedArguments = []; foreach ($arguments as $argument) { $parsedDate = null; if ($argument instanceof DateTimeZone) { $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments); } elseif (!isset($sortedArguments['interval']) && ( (\is_string($argument) && preg_match( '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument, )) || $argument instanceof DateInterval || $argument instanceof Closure || $argument instanceof Unit ) && $parsedInterval = self::makeInterval($argument) ) { $sortedArguments['interval'] = $parsedInterval; } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) { $sortedArguments['start'] = $parsedDate; $originalArguments['start'] = $argument; } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { $sortedArguments['end'] = $parsedDate; $originalArguments['end'] = $argument; } elseif (!isset($sortedArguments['recurrences']) && !isset($sortedArguments['end']) && (\is_int($argument) || \is_float($argument)) && $argument >= 0 ) { $sortedArguments['recurrences'] = $argument; } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { $optionsSet = true; $sortedArguments['options'] = (((int) $this->options) | ((int) $argument)); } elseif ($parsedTimezone = self::makeTimezone($argument)) { $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($raw === null && isset($sortedArguments['start'])) { $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1); if (\is_float($end)) { $end = $end === INF ? PHP_INT_MAX : (int) round($end); } $raw = [ $sortedArguments['start'], $sortedArguments['interval'] ?? CarbonInterval::day(), $end, ]; } $this->setFromAssociativeArray($sortedArguments); if ($this->startDate === null) { $dateClass = $this->dateClass; $this->setStartDate($dateClass::now()); } if ($this->dateInterval === null) { $this->setDateInterval(CarbonInterval::day()); $this->isDefaultInterval = true; } if ($this->options === null) { $this->setOptions(0); } parent::__construct( $this->startDate, $this->dateInterval, $this->endDate ?? max(1, min(2147483639, $this->recurrences ?? 1)), $this->options, ); $this->constructed = true; } /** * Get a copy of the instance. */ public function copy(): static { return clone $this; } /** * Prepare the instance to be set (self if mutable to be mutated, * copy if immutable to generate a new instance). */ protected function copyIfImmutable(): static { return $this; } /** * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. */ protected function getGetter(string $name): ?callable { return match (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) { 'start', 'start_date' => [$this, 'getStartDate'], 'end', 'end_date' => [$this, 'getEndDate'], 'interval', 'date_interval' => [$this, 'getDateInterval'], 'recurrences' => [$this, 'getRecurrences'], 'include_start_date' => [$this, 'isStartIncluded'], 'include_end_date' => [$this, 'isEndIncluded'], 'current' => [$this, 'current'], 'locale' => [$this, 'locale'], 'tzname', 'tz_name' => fn () => match (true) { $this->timezoneSetting === null => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, $this->timezoneSetting instanceof DateTimeZone => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, default => null, }; } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function get(string $name) { $getter = $this->getGetter($name); if ($getter) { return $getter(); } throw new UnknownGetterException($name); } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function __get(string $name) { return $this->get($name); } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset(string $name): bool { return $this->getGetter($name) !== null; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Set the iteration item class. * * @param string $dateClass * * @return static */ public function setDateClass(string $dateClass) { if (!is_a($dateClass, CarbonInterface::class, true)) { throw new NotACarbonClassException($dateClass); } $self = $this->copyIfImmutable(); $self->dateClass = $dateClass; if (is_a($dateClass, Carbon::class, true)) { $self->options = $self->options & ~static::IMMUTABLE; } elseif (is_a($dateClass, CarbonImmutable::class, true)) { $self->options = $self->options | static::IMMUTABLE; } return $self; } /** * Returns iteration item date class. * * @return string */ public function getDateClass(): string { return $this->dateClass; } /** * Change the period date interval. * * @param DateInterval|Unit|string|int $interval * @param Unit|string $unit the unit of $interval if it's a number * * @throws InvalidIntervalException * * @return static */ public function setDateInterval(mixed $interval, Unit|string|null $unit = null): static { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->name; } if (!$interval = CarbonInterval::make($interval, $unit)) { throw new InvalidIntervalException('Invalid interval.'); } if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) { throw new InvalidIntervalException('Empty interval is not accepted.'); } $self = $this->copyIfImmutable(); $self->dateInterval = $interval; $self->isDefaultInterval = false; $self->handleChangedParameters(); return $self; } /** * Reset the date interval to the default value. * * Difference with simply setting interval to 1-day is that P1D will not appear when calling toIso8601String() * and also next adding to the interval won't include the default 1-day. */ public function resetDateInterval(): static { $self = $this->copyIfImmutable(); $self->setDateInterval(CarbonInterval::day()); $self->isDefaultInterval = true; return $self; } /** * Invert the period date interval. */ public function invertDateInterval(): static { return $this->setDateInterval($this->dateInterval->invert()); } /** * Set start and end date. * * @param DateTime|DateTimeInterface|string $start * @param DateTime|DateTimeInterface|string|null $end * * @return static */ public function setDates(mixed $start, mixed $end): static { return $this->setStartDate($start)->setEndDate($end); } /** * Change the period options. * * @param int|null $options * * @return static */ public function setOptions(?int $options): static { $self = $this->copyIfImmutable(); $self->options = $options ?? 0; $self->handleChangedParameters(); return $self; } /** * Get the period options. */ public function getOptions(): int { return $this->options ?? 0; } /** * Toggle given options on or off. * * @param int $options * @param bool|null $state * * @throws InvalidArgumentException * * @return static */ public function toggleOptions(int $options, ?bool $state = null): static { $self = $this->copyIfImmutable(); if ($state === null) { $state = ($this->options & $options) !== $options; } return $self->setOptions( $state ? $this->options | $options : $this->options & ~$options, ); } /** * Toggle EXCLUDE_START_DATE option. */ public function excludeStartDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_START_DATE, $state); } /** * Toggle EXCLUDE_END_DATE option. */ public function excludeEndDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_END_DATE, $state); } /** * Get the underlying date interval. */ public function getDateInterval(): CarbonInterval { return $this->dateInterval->copy(); } /** * Get start date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getStartDate(?string $rounding = null): CarbonInterface { $date = $this->startDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get end date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getEndDate(?string $rounding = null): ?CarbonInterface { if (!$this->endDate) { return null; } $date = $this->endDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get number of recurrences. */ #[ReturnTypeWillChange] public function getRecurrences(): int|float|null { return $this->carbonRecurrences; } /** * Returns true if the start date should be excluded. */ public function isStartExcluded(): bool { return ($this->options & static::EXCLUDE_START_DATE) !== 0; } /** * Returns true if the end date should be excluded. */ public function isEndExcluded(): bool { return ($this->options & static::EXCLUDE_END_DATE) !== 0; } /** * Returns true if the start date should be included. */ public function isStartIncluded(): bool { return !$this->isStartExcluded(); } /** * Returns true if the end date should be included. */ public function isEndIncluded(): bool { return !$this->isEndExcluded(); } /** * Return the start if it's included by option, else return the start + 1 period interval. */ public function getIncludedStartDate(): CarbonInterface { $start = $this->getStartDate(); if ($this->isStartExcluded()) { return $start->add($this->getDateInterval()); } return $start; } /** * Return the end if it's included by option, else return the end - 1 period interval. * Warning: if the period has no fixed end, this method will iterate the period to calculate it. */ public function getIncludedEndDate(): CarbonInterface { $end = $this->getEndDate(); if (!$end) { return $this->calculateEnd(); } if ($this->isEndExcluded()) { return $end->sub($this->getDateInterval()); } return $end; } /** * Add a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function addFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); $self->filters[] = $tuple; $self->handleChangedParameters(); return $self; } /** * Prepend a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function prependFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); array_unshift($self->filters, $tuple); $self->handleChangedParameters(); return $self; } /** * Remove a filter by instance or name. */ public function removeFilter(callable|string $filter): static { $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; $self->filters = array_values(array_filter( $this->filters, static fn ($tuple) => $tuple[$key] !== $filter, )); $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Return whether given instance or name is in the filter stack. */ public function hasFilter(callable|string $filter): bool { $key = \is_callable($filter) ? 0 : 1; foreach ($this->filters as $tuple) { if ($tuple[$key] === $filter) { return true; } } return false; } /** * Get filters stack. */ public function getFilters(): array { return $this->filters; } /** * Set filters stack. */ public function setFilters(array $filters): static { $self = $this->copyIfImmutable(); $self->filters = $filters; $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Reset filters stack. */ public function resetFilters(): static { $self = $this->copyIfImmutable(); $self->filters = []; if ($self->endDate !== null) { $self->filters[] = [static::END_DATE_FILTER, null]; } if ($self->carbonRecurrences !== null) { $self->filters[] = [static::RECURRENCES_FILTER, null]; } $self->handleChangedParameters(); return $self; } /** * Add a recurrences filter (set maximum number of recurrences). * * @throws InvalidArgumentException */ public function setRecurrences(int|float|null $recurrences): static { if ($recurrences === null) { return $this->removeFilter(static::RECURRENCES_FILTER); } if ($recurrences < 0) { throw new InvalidPeriodParameterException('Invalid number of recurrences.'); } /** @var self $self */ $self = $this->copyIfImmutable(); $self->carbonRecurrences = $recurrences === INF ? INF : (int) $recurrences; if (!$self->hasFilter(static::RECURRENCES_FILTER)) { return $self->addFilter(static::RECURRENCES_FILTER); } $self->handleChangedParameters(); return $self; } /** * Change the period start date. * * @param DateTime|DateTimeInterface|string $date * @param bool|null $inclusive * * @throws InvalidPeriodDateException * * @return static */ public function setStartDate(mixed $date, ?bool $inclusive = null): static { if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date, $this->timezone))) { throw new InvalidPeriodDateException('Invalid start date.'); } $self = $this->copyIfImmutable(); $self->startDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); } return $self; } /** * Change the period end date. * * @param DateTime|DateTimeInterface|string|null $date * @param bool|null $inclusive * * @throws \InvalidArgumentException * * @return static */ public function setEndDate(mixed $date, ?bool $inclusive = null): static { if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date, $this->timezone)) { throw new InvalidPeriodDateException('Invalid end date.'); } if (!$date) { return $this->removeFilter(static::END_DATE_FILTER); } $self = $this->copyIfImmutable(); $self->endDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); } if (!$self->hasFilter(static::END_DATE_FILTER)) { return $self->addFilter(static::END_DATE_FILTER); } $self->handleChangedParameters(); return $self; } /** * Check if the current position is valid. */ public function valid(): bool { return $this->validateCurrentDate() === true; } /** * Return the current key. */ public function key(): ?int { return $this->valid() ? $this->key : null; } /** * Return the current date. */ public function current(): ?CarbonInterface { return $this->valid() ? $this->prepareForReturn($this->carbonCurrent) : null; } /** * Move forward to the next date. * * @throws RuntimeException */ public function next(): void { if ($this->carbonCurrent === null) { $this->rewind(); } if ($this->validationResult !== static::END_ITERATION) { $this->key++; $this->incrementCurrentDateUntilValid(); } } /** * Rewind to the start date. * * Iterating over a date in the UTC timezone avoids bug during backward DST change. * * @see https://bugs.php.net/bug.php?id=72255 * @see https://bugs.php.net/bug.php?id=74274 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time * * @throws RuntimeException */ public function rewind(): void { $this->key = 0; $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate); $settings = $this->getSettings(); if ($this->hasLocalTranslator()) { $settings['locale'] = $this->getTranslatorLocale(); } $this->carbonCurrent->settings($settings); $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null; if ($this->timezone) { $this->carbonCurrent = $this->carbonCurrent->utc(); } $this->validationResult = null; if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { $this->incrementCurrentDateUntilValid(); } } /** * Skip iterations and returns iteration state (false if ended, true if still valid). * * @param int $count steps number to skip (1 by default) * * @return bool */ public function skip(int $count = 1): bool { for ($i = $count; $this->valid() && $i > 0; $i--) { $this->next(); } return $this->valid(); } /** * Format the date period as ISO 8601. */ public function toIso8601String(): string { $parts = []; if ($this->carbonRecurrences !== null) { $parts[] = 'R'.$this->carbonRecurrences; } $parts[] = $this->startDate->toIso8601String(); if (!$this->isDefaultInterval) { $parts[] = $this->dateInterval->spec(); } if ($this->endDate !== null) { $parts[] = $this->endDate->toIso8601String(); } return implode('/', $parts); } /** * Convert the date period into a string. */ public function toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if ($format instanceof Closure) { return $format($this); } $translator = ([$this->dateClass, 'getTranslator'])(); $parts = []; $format = $format ?? ( !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) ? 'Y-m-d H:i:s' : 'Y-m-d' ); if ($this->carbonRecurrences !== null) { $parts[] = $this->translate('period_recurrences', [], $this->carbonRecurrences, $translator); } $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([ 'join' => true, ])], null, $translator); $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator); if ($this->endDate !== null) { $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator); } $result = implode(' ', $parts); return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1); } /** * Format the date period as ISO 8601. */ public function spec(): string { return $this->toIso8601String(); } /** * Cast the current instance into the given class. * * @param string $className The $className::instance() method will be called to cast the current object. * * @return DatePeriod|object */ public function cast(string $className): object { if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( $this->rawDate($this->getStartDate()), $this->getDateInterval(), $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0, ); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Return native DatePeriod PHP object matching the current instance. * * @example * ``` * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod()); * ``` */ public function toDatePeriod(): DatePeriod { return $this->cast(DatePeriod::class); } /** * Return `true` if the period has no custom filter and is guaranteed to be endless. * * Note that we can't check if a period is endless as soon as it has custom filters * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in * a way we can't predict without actually iterating the period. */ public function isUnfilteredAndEndLess(): bool { foreach ($this->filters as $filter) { switch ($filter) { case [static::RECURRENCES_FILTER, null]: if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) { return false; } break; case [static::END_DATE_FILTER, null]: if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { return false; } break; default: return false; } } return true; } /** * Convert the date period into an array without changing current iteration state. * * @return CarbonInterface[] */ public function toArray(): array { if ($this->isUnfilteredAndEndLess()) { throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); } $state = [ $this->key, $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null, $this->validationResult, ]; $result = iterator_to_array($this); [$this->key, $this->carbonCurrent, $this->validationResult] = $state; return $result; } /** * Count dates in the date period. */ public function count(): int { return \count($this->toArray()); } /** * Return the first date in the date period. */ public function first(): ?CarbonInterface { if ($this->isUnfilteredAndEndLess()) { foreach ($this as $date) { $this->rewind(); return $date; } return null; } return ($this->toArray() ?: [])[0] ?? null; } /** * Return the last date in the date period. */ public function last(): ?CarbonInterface { $array = $this->toArray(); return $array ? $array[\count($array) - 1] : null; } /** * Convert the date period into a string. */ public function __toString(): string { return $this->toString(); } /** * Add aliases for setters. * * CarbonPeriod::days(3)->hours(5)->invert() * ->sinceNow()->until('2010-01-10') * ->filter(...) * ->count() * * Note: We use magic method to let static and instance aliases with the same names. */ public function __call(string $method, array $parameters): mixed { if (static::hasMacro($method)) { return static::bindMacroContext($this, fn () => $this->callMacro($method, $parameters)); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } $count = \count($parameters); switch ($method) { case 'start': case 'since': if ($count === 0) { return $this->getStartDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setStartDate(...$parameters); case 'sinceNow': return $this->setStartDate(new Carbon(), ...$parameters); case 'end': case 'until': if ($count === 0) { return $this->getEndDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setEndDate(...$parameters); case 'untilNow': return $this->setEndDate(new Carbon(), ...$parameters); case 'dates': case 'between': self::setDefaultParameters($parameters, [ [0, 'start', null], [1, 'end', null], ]); return $this->setDates(...$parameters); case 'recurrences': case 'times': if ($count === 0) { return $this->getRecurrences(); } self::setDefaultParameters($parameters, [ [0, 'recurrences', null], ]); return $this->setRecurrences(...$parameters); case 'options': if ($count === 0) { return $this->getOptions(); } self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->setOptions(...$parameters); case 'toggle': self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->toggleOptions(...$parameters); case 'filter': case 'push': return $this->addFilter(...$parameters); case 'prepend': return $this->prependFilter(...$parameters); case 'filters': if ($count === 0) { return $this->getFilters(); } self::setDefaultParameters($parameters, [ [0, 'filters', []], ]); return $this->setFilters(...$parameters); case 'interval': case 'each': case 'every': case 'step': case 'stepBy': if ($count === 0) { return $this->getDateInterval(); } return $this->setDateInterval(...$parameters); case 'invert': return $this->invertDateInterval(); case 'years': case 'year': case 'months': case 'month': case 'weeks': case 'week': case 'days': case 'dayz': case 'day': case 'hours': case 'hour': case 'minutes': case 'minute': case 'seconds': case 'second': case 'milliseconds': case 'millisecond': case 'microseconds': case 'microsecond': return $this->setDateInterval(( // Override default P1D when instantiating via fluent setters. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] )(...$parameters)); } $dateClass = $this->dateClass; if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { throw new UnknownMethodException($method); } return $this; } /** * Set the instance's timezone from a string or object and apply it to start/end. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->setTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->setTimezone($timezone)); } return $self; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } return $self; } /** * Returns the end is set, else calculated from start and recurrences. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. * * @return CarbonInterface */ public function calculateEnd(?string $rounding = null): CarbonInterface { if ($end = $this->getEndDate($rounding)) { return $end; } if ($this->dateInterval->isEmpty()) { return $this->getStartDate($rounding); } $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); if ($date && $rounding) { $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); } return $date; } private function getEndFromRecurrences(): ?CarbonInterface { if ($this->carbonRecurrences === null) { throw new UnreachableException( "Could not calculate period end without either explicit end or recurrences.\n". "If you're looking for a forever-period, use ->setRecurrences(INF).", ); } if ($this->carbonRecurrences === INF) { $start = $this->getStartDate(); return $start < $start->avoidMutation()->add($this->getDateInterval()) ? CarbonImmutable::endOfTime() : CarbonImmutable::startOfTime(); } if ($this->filters === [[static::RECURRENCES_FILTER, null]]) { return $this->getStartDate()->avoidMutation()->add( $this->getDateInterval()->times( $this->carbonRecurrences - ($this->isStartExcluded() ? 0 : 1), ), ); } return null; } private function iterateUntilEnd(): ?CarbonInterface { $attempts = 0; $date = null; foreach ($this as $date) { if (++$attempts > static::END_MAX_ATTEMPTS) { throw new UnreachableException( 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.', ); } } return $date; } /** * Returns true if the current period overlaps the given one (if 1 parameter passed) * or the period between 2 dates (if 2 parameters passed). * * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd * * @return bool */ public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool { $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; if (!($range instanceof self)) { $range = static::create($range); } [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); return $end > $rangeStart && $rangeEnd > $start; } /** * Execute a given function on each date of the period. * * @example * ``` * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) { * echo $date->diffInDays('2020-12-25')." days before Christmas!\n"; * }); * ``` */ public function forEach(callable $callback): void { foreach ($this as $date) { $callback($date); } } /** * Execute a given function on each date of the period and yield the result of this function. * * @example * ``` * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24'); * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) { * return $date->diffInDays('2020-12-25').' days before Christmas!'; * }))); * ``` */ public function map(callable $callback): Generator { foreach ($this as $date) { yield $callback($date); } } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. * * @see equalTo() */ public function eq(mixed $period): bool { return $this->equalTo($period); } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. */ public function equalTo(mixed $period): bool { if (!($period instanceof self)) { $period = self::make($period); } $end = $this->getEndDate(); return $period !== null && $this->getDateInterval()->eq($period->getDateInterval()) && $this->getStartDate()->eq($period->getStartDate()) && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. * * @see notEqualTo() */ public function ne(mixed $period): bool { return $this->notEqualTo($period); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. */ public function notEqualTo(mixed $period): bool { return !$this->eq($period); } /** * Determines if the start date is before another given date. * (Rather start/end are included by options is ignored.) */ public function startsBefore(mixed $date = null): bool { return $this->getStartDate()->lessThan($this->resolveCarbon($date)); } /** * Determines if the start date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsBeforeOrAt(mixed $date = null): bool { return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is after another given date. * (Rather start/end are included by options is ignored.) */ public function startsAfter(mixed $date = null): bool { return $this->getStartDate()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the start date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAfterOrAt(mixed $date = null): bool { return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAt(mixed $date = null): bool { return $this->getStartDate()->equalTo($this->resolveCarbon($date)); } /** * Determines if the end date is before another given date. * (Rather start/end are included by options is ignored.) */ public function endsBefore(mixed $date = null): bool { return $this->calculateEnd()->lessThan($this->resolveCarbon($date)); } /** * Determines if the end date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsBeforeOrAt(mixed $date = null): bool { return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is after another given date. * (Rather start/end are included by options is ignored.) */ public function endsAfter(mixed $date = null): bool { return $this->calculateEnd()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the end date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAfterOrAt(mixed $date = null): bool { return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAt(mixed $date = null): bool { return $this->calculateEnd()->equalTo($this->resolveCarbon($date)); } /** * Return true if start date is now or later. * (Rather start/end are included by options is ignored.) */ public function isStarted(): bool { return $this->startsBeforeOrAt(); } /** * Return true if end date is now or later. * (Rather start/end are included by options is ignored.) */ public function isEnded(): bool { return $this->endsBeforeOrAt(); } /** * Return true if now is between start date (included) and end date (excluded). * (Rather start/end are included by options is ignored.) */ public function isInProgress(): bool { return $this->isStarted() && !$this->isEnded(); } /** * Round the current instance at the given unit with given precision if specified and the given function. */ public function roundUnit( string $unit, DateInterval|float|int|string|null $precision = 1, callable|string $function = 'round', ): static { $self = $this->copyIfImmutable(); $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); if ($self->endDate) { $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); } /** * Truncate the current instance at the given unit with given precision if specified. */ public function floorUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. */ public function ceilUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function round( DateInterval|float|int|string|null $precision = null, callable|string $function = 'round', ): static { return $this->roundWith( $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(), $function ); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function floor(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified (else period interval is used). */ public function ceil(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'ceil'); } /** * Specify data which should be serialized to JSON. * * @link https://php.net/manual/en/jsonserializable.jsonserialize.php * * @return CarbonInterface[] */ public function jsonSerialize(): array { return $this->toArray(); } /** * Return true if the given date is between start and end. */ public function contains(mixed $date = null): bool { $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : ''); $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : ''); return $this->$startMethod($date) && $this->$endMethod($date); } /** * Return true if the current period follows a given other period (with no overlap). * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31] * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function follows(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval())); } /** * Return true if the given other period follows the current one (with no overlap). * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12] * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function isFollowedBy(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $period->follows($this); } /** * Return true if the given period either follows or is followed by the current one. * * @see follows() * @see isFollowedBy() */ public function isConsecutiveWith(mixed $period, mixed ...$arguments): bool { return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments); } public function __debugInfo(): array { $info = $this->baseDebugInfo(); unset( $info['start'], $info['end'], $info['interval'], $info['include_start_date'], $info['include_end_date'], $info['constructed'], $info["\0*\0constructed"], ); return $info; } public function __unserialize(array $data): void { try { $values = array_combine( array_map( static fn (string $key): string => preg_replace('/^\0\*\0/', '', $key), array_keys($data), ), $data, ); $this->initializeSerialization($values); foreach ($values as $key => $value) { if ($value === null) { continue; } $property = match ($key) { 'tzName' => $this->setTimezone(...), 'options' => $this->setOptions(...), 'recurrences' => $this->setRecurrences(...), 'current' => function (mixed $current): void { if (!($current instanceof CarbonInterface)) { $current = $this->resolveCarbon($current); } $this->carbonCurrent = $current; }, 'start' => 'startDate', 'interval' => $this->setDateInterval(...), 'end' => 'endDate', 'key' => null, 'include_start_date' => function (bool $included): void { $this->excludeStartDate(!$included); }, 'include_end_date' => function (bool $included): void { $this->excludeEndDate(!$included); }, default => $key, }; if ($property === null) { continue; } if (\is_callable($property)) { $property($value); continue; } if ($value instanceof DateTimeInterface && !($value instanceof CarbonInterface)) { $value = ($value instanceof DateTime) ? Carbon::instance($value) : CarbonImmutable::instance($value); } try { $this->$property = $value; } catch (Throwable) { // Must be ignored for backward-compatibility } } if (\array_key_exists('carbonRecurrences', $values)) { $this->carbonRecurrences = $values['carbonRecurrences']; } elseif (((int) ($values['recurrences'] ?? 0)) <= 1 && $this->endDate !== null) { $this->carbonRecurrences = null; } } catch (Throwable $e) { // @codeCoverageIgnoreStart if (!method_exists(parent::class, '__unserialize')) { throw $e; } parent::__unserialize($data); // @codeCoverageIgnoreEnd } } /** * Update properties after removing built-in filters. */ protected function updateInternalState(): void { if (!$this->hasFilter(static::END_DATE_FILTER)) { $this->endDate = null; } if (!$this->hasFilter(static::RECURRENCES_FILTER)) { $this->carbonRecurrences = null; } } /** * Create a filter tuple from raw parameters. * * Will create an automatic filter callback for one of Carbon's is* methods. */ protected function createFilterTuple(array $parameters): array { $method = array_shift($parameters); if (!$this->isCarbonPredicateMethod($method)) { return [$method, array_shift($parameters)]; } return [static fn ($date) => ([$date, $method])(...$parameters), $method]; } /** * Return whether given callable is a string pointing to one of Carbon's is* methods * and should be automatically converted to a filter callback. */ protected function isCarbonPredicateMethod(callable|string $callable): bool { return \is_string($callable) && str_starts_with($callable, 'is') && (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable)); } /** * Recurrences filter callback (limits number of recurrences). * * @SuppressWarnings(UnusedFormalParameter) */ protected function filterRecurrences(CarbonInterface $current, int $key): bool|callable { if ($key < $this->carbonRecurrences) { return true; } return static::END_ITERATION; } /** * End date filter callback. * * @return bool|static::END_ITERATION */ protected function filterEndDate(CarbonInterface $current): bool|callable { if (!$this->isEndExcluded() && $current == $this->endDate) { return true; } if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) { return true; } return static::END_ITERATION; } /** * End iteration filter callback. * * @return static::END_ITERATION */ protected function endIteration(): callable { return static::END_ITERATION; } /** * Handle change of the parameters. */ protected function handleChangedParameters(): void { if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { $this->dateClass = CarbonImmutable::class; } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { $this->dateClass = Carbon::class; } $this->validationResult = null; } /** * Validate current date and stop iteration when necessary. * * Returns true when current date is valid, false if it is not, or static::END_ITERATION * when iteration should be stopped. * * @return bool|static::END_ITERATION */ protected function validateCurrentDate(): bool|callable { if ($this->carbonCurrent === null) { $this->rewind(); } // Check after the first rewind to avoid repeating the initial validation. return $this->validationResult ?? ($this->validationResult = $this->checkFilters()); } /** * Check whether current value and key pass all the filters. * * @return bool|static::END_ITERATION */ protected function checkFilters(): bool|callable { $current = $this->prepareForReturn($this->carbonCurrent); foreach ($this->filters as $tuple) { $result = \call_user_func($tuple[0], $current->avoidMutation(), $this->key, $this); if ($result === static::END_ITERATION) { return static::END_ITERATION; } if (!$result) { return false; } } return true; } /** * Prepare given date to be returned to the external logic. * * @param CarbonInterface $date * * @return CarbonInterface */ protected function prepareForReturn(CarbonInterface $date) { $date = ([$this->dateClass, 'make'])($date); if ($this->timezone) { return $date->setTimezone($this->timezone); } return $date; } /** * Keep incrementing the current date until a valid date is found or the iteration is ended. * * @throws RuntimeException */ protected function incrementCurrentDateUntilValid(): void { $attempts = 0; do { $this->carbonCurrent = $this->carbonCurrent->add($this->dateInterval); $this->validationResult = null; if (++$attempts > static::NEXT_MAX_ATTEMPTS) { throw new UnreachableException('Could not find next valid date.'); } } while ($this->validateCurrentDate() === false); } /** * Call given macro. */ protected function callMacro(string $name, array $parameters): mixed { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date * * @return \Carbon\CarbonInterface */ protected function resolveCarbon($date = null) { return $this->getStartDate()->nowWithSameTz()->carbonize($date); } /** * Resolve passed arguments or DatePeriod to a CarbonPeriod object. */ protected function resolveCarbonPeriod(mixed $period, mixed ...$arguments): self { if ($period instanceof self) { return $period; } return $period instanceof DatePeriod ? static::instance($period) : static::create($period, ...$arguments); } private function orderCouple($first, $second): array { return $first > $second ? [$second, $first] : [$first, $second]; } private function makeDateTime($value): ?DateTimeInterface { if ($value instanceof DateTimeInterface) { return $value; } if ($value instanceof WeekDay || $value instanceof Month) { $dateClass = $this->dateClass; return new $dateClass($value, $this->timezoneSetting); } if (\is_string($value)) { $value = trim($value); if (!preg_match('/^P[\dT]/', $value) && !preg_match('/^R\d/', $value) && preg_match('/[a-z\d]/i', $value) ) { $dateClass = $this->dateClass; return $dateClass::parse($value, $this->timezoneSetting); } } return null; } private function isInfiniteDate($date): bool { return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); } private function rawDate($date): ?DateTimeInterface { if ($date === false || $date === null) { return null; } if ($date instanceof CarbonInterface) { return $date->isMutable() ? $date->toDateTime() : $date->toDateTimeImmutable(); } if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { return $date; } $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); } private static function setDefaultParameters(array &$parameters, array $defaults): void { foreach ($defaults as [$index, $name, $value]) { if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { $parameters[$index] = $value; } } } private function setFromAssociativeArray(array $parameters): void { if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['end'])) { $this->setEndDate($parameters['end']); } if (isset($parameters['recurrences'])) { $this->setRecurrences($parameters['recurrences']); } if (isset($parameters['interval'])) { $this->setDateInterval($parameters['interval']); } if (isset($parameters['options'])) { $this->setOptions($parameters['options']); } } private function configureTimezone(DateTimeZone $timezone, array $sortedArguments, array $originalArguments): array { $this->setTimezone($timezone); if (\is_string($originalArguments['start'] ?? null)) { $sortedArguments['start'] = $this->makeDateTime($originalArguments['start']); } if (\is_string($originalArguments['end'] ?? null)) { $sortedArguments['end'] = $this->makeDateTime($originalArguments['end']); } return $sortedArguments; } private function initializeSerialization(array $values): void { $serializationBase = [ 'start' => $values['start'] ?? $values['startDate'] ?? null, 'current' => $values['current'] ?? $values['carbonCurrent'] ?? null, 'end' => $values['end'] ?? $values['endDate'] ?? null, 'interval' => $values['interval'] ?? $values['dateInterval'] ?? null, 'recurrences' => max(1, (int) ($values['recurrences'] ?? $values['carbonRecurrences'] ?? 1)), 'include_start_date' => $values['include_start_date'] ?? true, 'include_end_date' => $values['include_end_date'] ?? false, ]; foreach (['start', 'current', 'end'] as $dateProperty) { if ($serializationBase[$dateProperty] instanceof Carbon) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTime(); } elseif ($serializationBase[$dateProperty] instanceof CarbonInterface) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTimeImmutable(); } } if ($serializationBase['interval'] instanceof CarbonInterval) { $serializationBase['interval'] = $serializationBase['interval']->toDateInterval(); } // @codeCoverageIgnoreStart if (method_exists(parent::class, '__unserialize')) { parent::__unserialize($serializationBase); return; } $excludeStart = !($values['include_start_date'] ?? true); $includeEnd = $values['include_end_date'] ?? true; parent::__construct( $serializationBase['start'], $serializationBase['interval'], $serializationBase['end'] ?? $serializationBase['recurrences'], ($excludeStart ? self::EXCLUDE_START_DATE : 0) | ($includeEnd && \defined('DatePeriod::INCLUDE_END_DATE') ? self::INCLUDE_END_DATE : 0), ); // @codeCoverageIgnoreEnd } }
PHP
{ "end_line": 1443, "name": "toIso8601String", "signature": "public function toIso8601String(): string", "start_line": 1424 }
{ "class_name": "CarbonPeriod", "class_signature": "class CarbonPeriod implements Countable, JsonSerializable, UnitValue", "namespace": "Carbon" }
cast
Carbon/src/Carbon/CarbonPeriod.php
public function cast(string $className): object { if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( $this->rawDate($this->getStartDate()), $this->getDateInterval(), $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0, ); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotACarbonClassException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnreachableException; use Carbon\Traits\DeprecatedPeriodProperties; use Carbon\Traits\IntervalRounding; use Carbon\Traits\LocalFactory; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Throwable; // @codeCoverageIgnoreStart require PHP_VERSION < 8.2 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php' : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php'; // @codeCoverageIgnoreEnd /** * Substitution of DatePeriod with some modifications and many more features. * * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. * @method static static since($date = null, $inclusive = null) Alias for start(). * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. * @method static static until($date = null, $inclusive = null) Alias for end(). * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. * @method static static times($recurrences = null) Alias for recurrences(). * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance. * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. * @method static static push($callback, $name = null) Alias for filter(). * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance. * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. * @method static static year($years = 1) Alias for years(). * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. * @method static static month($months = 1) Alias for months(). * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. * @method static static week($weeks = 1) Alias for weeks(). * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. * @method static static dayz($days = 1) Alias for days(). * @method static static day($days = 1) Alias for days(). * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. * @method static static hour($hours = 1) Alias for hours(). * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. * @method static static minute($minutes = 1) Alias for minutes(). * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. * @method static static second($seconds = 1) Alias for seconds(). * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * * @mixin DeprecatedPeriodProperties * * @SuppressWarnings(TooManyFields) * @SuppressWarnings(CamelCasePropertyName) * @SuppressWarnings(CouplingBetweenObjects) */ class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue { use LocalFactory; use IntervalRounding; use Mixin { Mixin::mixin as baseMixin; } use Options { Options::__debugInfo as baseDebugInfo; } use ToStringFormat; /** * Built-in filter for limit by recurrences. * * @var callable */ public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; /** * Built-in filter for limit to an end. * * @var callable */ public const END_DATE_FILTER = [self::class, 'filterEndDate']; /** * Special value which can be returned by filters to end iteration. Also a filter. * * @var callable */ public const END_ITERATION = [self::class, 'endIteration']; /** * Exclude end date from iteration. * * @var int */ public const EXCLUDE_END_DATE = 8; /** * Yield CarbonImmutable instances. * * @var int */ public const IMMUTABLE = 4; /** * Number of maximum attempts before giving up on finding next valid date. * * @var int */ public const NEXT_MAX_ATTEMPTS = 1000; /** * Number of maximum attempts before giving up on finding end date. * * @var int */ public const END_MAX_ATTEMPTS = 10000; /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = Carbon::class; /** * The registered macros. */ protected static array $macros = []; /** * Date class of iteration items. */ protected string $dateClass = Carbon::class; /** * Underlying date interval instance. Always present, one day by default. */ protected ?CarbonInterval $dateInterval = null; /** * True once __construct is finished. */ protected bool $constructed = false; /** * Whether current date interval was set by default. */ protected bool $isDefaultInterval = false; /** * The filters stack. */ protected array $filters = []; /** * Period start date. Applied on rewind. Always present, now by default. */ protected ?CarbonInterface $startDate = null; /** * Period end date. For inverted interval should be before the start date. Applied via a filter. */ protected ?CarbonInterface $endDate = null; /** * Limit for number of recurrences. Applied via a filter. */ protected int|float|null $carbonRecurrences = null; /** * Iteration options. */ protected ?int $options = null; /** * Index of current date. Always sequential, even if some dates are skipped by filters. * Equal to null only before the first iteration. */ protected int $key = 0; /** * Current date. May temporarily hold unaccepted value when looking for a next valid date. * Equal to null only before the first iteration. */ protected ?CarbonInterface $carbonCurrent = null; /** * Timezone of current date. Taken from the start date. */ protected ?DateTimeZone $timezone = null; /** * The cached validation result for current date. */ protected array|string|bool|null $validationResult = null; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; public function getIterator(): Generator { $this->rewind(); while ($this->valid()) { $key = $this->key(); $value = $this->current(); yield $key => $value; $this->next(); } } /** * Make a CarbonPeriod instance from given variable if possible. */ public static function make(mixed $var): ?static { try { return static::instance($var); } catch (NotAPeriodException) { return static::create($var); } } /** * Create a new instance from a DatePeriod or CarbonPeriod object. */ public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); } /** * Create a new instance. */ public static function create(...$params): static { return static::createFromArray($params); } /** * Create a new instance from an array of parameters. */ public static function createFromArray(array $params): static { return new static(...$params); } /** * Create CarbonPeriod from ISO 8601 string. */ public static function createFromIso(string $iso, ?int $options = null): static { $params = static::parseIso8601($iso); $instance = static::createFromArray($params); $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options; $instance->handleChangedParameters(); return $instance; } public static function createFromISO8601String(string $iso, ?int $options = null): static { return self::createFromIso($iso, $options); } /** * Return whether the given interval contains non-zero value of any time unit. */ protected static function intervalHasTime(DateInterval $interval): bool { return $interval->h || $interval->i || $interval->s || $interval->f; } /** * Return whether given variable is an ISO 8601 specification. * * Note: Check is very basic, as actual validation will be done later when parsing. * We just want to ensure that variable is not any other type of valid parameter. */ protected static function isIso8601(mixed $var): bool { if (!\is_string($var)) { return false; } // Match slash but not within a timezone name. $part = '[a-z]+(?:[_-][a-z]+)*'; preg_match("#\b$part/$part\b|(/)#i", $var, $match); return isset($match[1]); } /** * Parse given ISO 8601 string into an array of arguments. * * @SuppressWarnings(ElseExpression) */ protected static function parseIso8601(string $iso): array { $result = []; $interval = null; $start = null; $end = null; $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = self::makeInterval($part)) { $interval = $part; } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); } $result[] = $parsed; } return $result; } /** * Add missing parts of the target date from the source date. */ protected static function addMissingParts(string $source, string $target): string { $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); return $count ? $result : $target; } private static function makeInterval(mixed $input): ?CarbonInterval { try { return CarbonInterval::make($input); } catch (Throwable) { return null; } } private static function makeTimezone(mixed $input): ?CarbonTimeZone { if (!\is_string($input)) { return null; } try { return CarbonTimeZone::create($input); } catch (Throwable) { return null; } } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonPeriod::macro('middle', function () { * return $this->getStartDate()->average($this->getEndDate()); * }); * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonPeriod::mixin(new class { * public function addDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->addDays($count) * )->setEndDate( * $this->getEndDate()->addDays($count) * ); * }; * } * public function subDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->subDays($count) * )->setEndDate( * $this->getEndDate()->subDays($count) * ); * }; * } * }); * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); * ``` * * @throws ReflectionException */ public static function mixin(object|string $mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Provide static proxy for instance aliases. */ public static function __callStatic(string $method, array $parameters): mixed { $date = new static(); if (static::hasMacro($method)) { return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters)); } return $date->$method(...$parameters); } /** * CarbonPeriod constructor. * * @SuppressWarnings(ElseExpression) * * @throws InvalidArgumentException */ public function __construct(...$arguments) { $raw = null; if (isset($arguments['raw'])) { $raw = $arguments['raw']; $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false; if (isset($arguments['dateClass'])) { $this->dateClass = $arguments['dateClass']; } $arguments = $raw; } // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. $argumentsCount = \count($arguments); if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { array_splice($arguments, 0, 1, static::parseIso8601($iso)); } if ($argumentsCount === 1) { if ($arguments[0] instanceof self) { $arguments = [ $arguments[0]->getStartDate(), $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(), $arguments[0]->getDateInterval(), $arguments[0]->getOptions(), ]; } elseif ($arguments[0] instanceof DatePeriod) { $arguments = [ $arguments[0]->start, $arguments[0]->end ?: ($arguments[0]->recurrences - 1), $arguments[0]->interval, $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, ]; } } if (is_a($this->dateClass, DateTimeImmutable::class, true)) { $this->options = static::IMMUTABLE; } $optionsSet = false; $originalArguments = []; $sortedArguments = []; foreach ($arguments as $argument) { $parsedDate = null; if ($argument instanceof DateTimeZone) { $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments); } elseif (!isset($sortedArguments['interval']) && ( (\is_string($argument) && preg_match( '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument, )) || $argument instanceof DateInterval || $argument instanceof Closure || $argument instanceof Unit ) && $parsedInterval = self::makeInterval($argument) ) { $sortedArguments['interval'] = $parsedInterval; } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) { $sortedArguments['start'] = $parsedDate; $originalArguments['start'] = $argument; } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { $sortedArguments['end'] = $parsedDate; $originalArguments['end'] = $argument; } elseif (!isset($sortedArguments['recurrences']) && !isset($sortedArguments['end']) && (\is_int($argument) || \is_float($argument)) && $argument >= 0 ) { $sortedArguments['recurrences'] = $argument; } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { $optionsSet = true; $sortedArguments['options'] = (((int) $this->options) | ((int) $argument)); } elseif ($parsedTimezone = self::makeTimezone($argument)) { $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($raw === null && isset($sortedArguments['start'])) { $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1); if (\is_float($end)) { $end = $end === INF ? PHP_INT_MAX : (int) round($end); } $raw = [ $sortedArguments['start'], $sortedArguments['interval'] ?? CarbonInterval::day(), $end, ]; } $this->setFromAssociativeArray($sortedArguments); if ($this->startDate === null) { $dateClass = $this->dateClass; $this->setStartDate($dateClass::now()); } if ($this->dateInterval === null) { $this->setDateInterval(CarbonInterval::day()); $this->isDefaultInterval = true; } if ($this->options === null) { $this->setOptions(0); } parent::__construct( $this->startDate, $this->dateInterval, $this->endDate ?? max(1, min(2147483639, $this->recurrences ?? 1)), $this->options, ); $this->constructed = true; } /** * Get a copy of the instance. */ public function copy(): static { return clone $this; } /** * Prepare the instance to be set (self if mutable to be mutated, * copy if immutable to generate a new instance). */ protected function copyIfImmutable(): static { return $this; } /** * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. */ protected function getGetter(string $name): ?callable { return match (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) { 'start', 'start_date' => [$this, 'getStartDate'], 'end', 'end_date' => [$this, 'getEndDate'], 'interval', 'date_interval' => [$this, 'getDateInterval'], 'recurrences' => [$this, 'getRecurrences'], 'include_start_date' => [$this, 'isStartIncluded'], 'include_end_date' => [$this, 'isEndIncluded'], 'current' => [$this, 'current'], 'locale' => [$this, 'locale'], 'tzname', 'tz_name' => fn () => match (true) { $this->timezoneSetting === null => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, $this->timezoneSetting instanceof DateTimeZone => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, default => null, }; } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function get(string $name) { $getter = $this->getGetter($name); if ($getter) { return $getter(); } throw new UnknownGetterException($name); } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function __get(string $name) { return $this->get($name); } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset(string $name): bool { return $this->getGetter($name) !== null; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Set the iteration item class. * * @param string $dateClass * * @return static */ public function setDateClass(string $dateClass) { if (!is_a($dateClass, CarbonInterface::class, true)) { throw new NotACarbonClassException($dateClass); } $self = $this->copyIfImmutable(); $self->dateClass = $dateClass; if (is_a($dateClass, Carbon::class, true)) { $self->options = $self->options & ~static::IMMUTABLE; } elseif (is_a($dateClass, CarbonImmutable::class, true)) { $self->options = $self->options | static::IMMUTABLE; } return $self; } /** * Returns iteration item date class. * * @return string */ public function getDateClass(): string { return $this->dateClass; } /** * Change the period date interval. * * @param DateInterval|Unit|string|int $interval * @param Unit|string $unit the unit of $interval if it's a number * * @throws InvalidIntervalException * * @return static */ public function setDateInterval(mixed $interval, Unit|string|null $unit = null): static { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->name; } if (!$interval = CarbonInterval::make($interval, $unit)) { throw new InvalidIntervalException('Invalid interval.'); } if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) { throw new InvalidIntervalException('Empty interval is not accepted.'); } $self = $this->copyIfImmutable(); $self->dateInterval = $interval; $self->isDefaultInterval = false; $self->handleChangedParameters(); return $self; } /** * Reset the date interval to the default value. * * Difference with simply setting interval to 1-day is that P1D will not appear when calling toIso8601String() * and also next adding to the interval won't include the default 1-day. */ public function resetDateInterval(): static { $self = $this->copyIfImmutable(); $self->setDateInterval(CarbonInterval::day()); $self->isDefaultInterval = true; return $self; } /** * Invert the period date interval. */ public function invertDateInterval(): static { return $this->setDateInterval($this->dateInterval->invert()); } /** * Set start and end date. * * @param DateTime|DateTimeInterface|string $start * @param DateTime|DateTimeInterface|string|null $end * * @return static */ public function setDates(mixed $start, mixed $end): static { return $this->setStartDate($start)->setEndDate($end); } /** * Change the period options. * * @param int|null $options * * @return static */ public function setOptions(?int $options): static { $self = $this->copyIfImmutable(); $self->options = $options ?? 0; $self->handleChangedParameters(); return $self; } /** * Get the period options. */ public function getOptions(): int { return $this->options ?? 0; } /** * Toggle given options on or off. * * @param int $options * @param bool|null $state * * @throws InvalidArgumentException * * @return static */ public function toggleOptions(int $options, ?bool $state = null): static { $self = $this->copyIfImmutable(); if ($state === null) { $state = ($this->options & $options) !== $options; } return $self->setOptions( $state ? $this->options | $options : $this->options & ~$options, ); } /** * Toggle EXCLUDE_START_DATE option. */ public function excludeStartDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_START_DATE, $state); } /** * Toggle EXCLUDE_END_DATE option. */ public function excludeEndDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_END_DATE, $state); } /** * Get the underlying date interval. */ public function getDateInterval(): CarbonInterval { return $this->dateInterval->copy(); } /** * Get start date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getStartDate(?string $rounding = null): CarbonInterface { $date = $this->startDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get end date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getEndDate(?string $rounding = null): ?CarbonInterface { if (!$this->endDate) { return null; } $date = $this->endDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get number of recurrences. */ #[ReturnTypeWillChange] public function getRecurrences(): int|float|null { return $this->carbonRecurrences; } /** * Returns true if the start date should be excluded. */ public function isStartExcluded(): bool { return ($this->options & static::EXCLUDE_START_DATE) !== 0; } /** * Returns true if the end date should be excluded. */ public function isEndExcluded(): bool { return ($this->options & static::EXCLUDE_END_DATE) !== 0; } /** * Returns true if the start date should be included. */ public function isStartIncluded(): bool { return !$this->isStartExcluded(); } /** * Returns true if the end date should be included. */ public function isEndIncluded(): bool { return !$this->isEndExcluded(); } /** * Return the start if it's included by option, else return the start + 1 period interval. */ public function getIncludedStartDate(): CarbonInterface { $start = $this->getStartDate(); if ($this->isStartExcluded()) { return $start->add($this->getDateInterval()); } return $start; } /** * Return the end if it's included by option, else return the end - 1 period interval. * Warning: if the period has no fixed end, this method will iterate the period to calculate it. */ public function getIncludedEndDate(): CarbonInterface { $end = $this->getEndDate(); if (!$end) { return $this->calculateEnd(); } if ($this->isEndExcluded()) { return $end->sub($this->getDateInterval()); } return $end; } /** * Add a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function addFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); $self->filters[] = $tuple; $self->handleChangedParameters(); return $self; } /** * Prepend a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function prependFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); array_unshift($self->filters, $tuple); $self->handleChangedParameters(); return $self; } /** * Remove a filter by instance or name. */ public function removeFilter(callable|string $filter): static { $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; $self->filters = array_values(array_filter( $this->filters, static fn ($tuple) => $tuple[$key] !== $filter, )); $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Return whether given instance or name is in the filter stack. */ public function hasFilter(callable|string $filter): bool { $key = \is_callable($filter) ? 0 : 1; foreach ($this->filters as $tuple) { if ($tuple[$key] === $filter) { return true; } } return false; } /** * Get filters stack. */ public function getFilters(): array { return $this->filters; } /** * Set filters stack. */ public function setFilters(array $filters): static { $self = $this->copyIfImmutable(); $self->filters = $filters; $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Reset filters stack. */ public function resetFilters(): static { $self = $this->copyIfImmutable(); $self->filters = []; if ($self->endDate !== null) { $self->filters[] = [static::END_DATE_FILTER, null]; } if ($self->carbonRecurrences !== null) { $self->filters[] = [static::RECURRENCES_FILTER, null]; } $self->handleChangedParameters(); return $self; } /** * Add a recurrences filter (set maximum number of recurrences). * * @throws InvalidArgumentException */ public function setRecurrences(int|float|null $recurrences): static { if ($recurrences === null) { return $this->removeFilter(static::RECURRENCES_FILTER); } if ($recurrences < 0) { throw new InvalidPeriodParameterException('Invalid number of recurrences.'); } /** @var self $self */ $self = $this->copyIfImmutable(); $self->carbonRecurrences = $recurrences === INF ? INF : (int) $recurrences; if (!$self->hasFilter(static::RECURRENCES_FILTER)) { return $self->addFilter(static::RECURRENCES_FILTER); } $self->handleChangedParameters(); return $self; } /** * Change the period start date. * * @param DateTime|DateTimeInterface|string $date * @param bool|null $inclusive * * @throws InvalidPeriodDateException * * @return static */ public function setStartDate(mixed $date, ?bool $inclusive = null): static { if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date, $this->timezone))) { throw new InvalidPeriodDateException('Invalid start date.'); } $self = $this->copyIfImmutable(); $self->startDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); } return $self; } /** * Change the period end date. * * @param DateTime|DateTimeInterface|string|null $date * @param bool|null $inclusive * * @throws \InvalidArgumentException * * @return static */ public function setEndDate(mixed $date, ?bool $inclusive = null): static { if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date, $this->timezone)) { throw new InvalidPeriodDateException('Invalid end date.'); } if (!$date) { return $this->removeFilter(static::END_DATE_FILTER); } $self = $this->copyIfImmutable(); $self->endDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); } if (!$self->hasFilter(static::END_DATE_FILTER)) { return $self->addFilter(static::END_DATE_FILTER); } $self->handleChangedParameters(); return $self; } /** * Check if the current position is valid. */ public function valid(): bool { return $this->validateCurrentDate() === true; } /** * Return the current key. */ public function key(): ?int { return $this->valid() ? $this->key : null; } /** * Return the current date. */ public function current(): ?CarbonInterface { return $this->valid() ? $this->prepareForReturn($this->carbonCurrent) : null; } /** * Move forward to the next date. * * @throws RuntimeException */ public function next(): void { if ($this->carbonCurrent === null) { $this->rewind(); } if ($this->validationResult !== static::END_ITERATION) { $this->key++; $this->incrementCurrentDateUntilValid(); } } /** * Rewind to the start date. * * Iterating over a date in the UTC timezone avoids bug during backward DST change. * * @see https://bugs.php.net/bug.php?id=72255 * @see https://bugs.php.net/bug.php?id=74274 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time * * @throws RuntimeException */ public function rewind(): void { $this->key = 0; $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate); $settings = $this->getSettings(); if ($this->hasLocalTranslator()) { $settings['locale'] = $this->getTranslatorLocale(); } $this->carbonCurrent->settings($settings); $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null; if ($this->timezone) { $this->carbonCurrent = $this->carbonCurrent->utc(); } $this->validationResult = null; if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { $this->incrementCurrentDateUntilValid(); } } /** * Skip iterations and returns iteration state (false if ended, true if still valid). * * @param int $count steps number to skip (1 by default) * * @return bool */ public function skip(int $count = 1): bool { for ($i = $count; $this->valid() && $i > 0; $i--) { $this->next(); } return $this->valid(); } /** * Format the date period as ISO 8601. */ public function toIso8601String(): string { $parts = []; if ($this->carbonRecurrences !== null) { $parts[] = 'R'.$this->carbonRecurrences; } $parts[] = $this->startDate->toIso8601String(); if (!$this->isDefaultInterval) { $parts[] = $this->dateInterval->spec(); } if ($this->endDate !== null) { $parts[] = $this->endDate->toIso8601String(); } return implode('/', $parts); } /** * Convert the date period into a string. */ public function toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if ($format instanceof Closure) { return $format($this); } $translator = ([$this->dateClass, 'getTranslator'])(); $parts = []; $format = $format ?? ( !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) ? 'Y-m-d H:i:s' : 'Y-m-d' ); if ($this->carbonRecurrences !== null) { $parts[] = $this->translate('period_recurrences', [], $this->carbonRecurrences, $translator); } $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([ 'join' => true, ])], null, $translator); $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator); if ($this->endDate !== null) { $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator); } $result = implode(' ', $parts); return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1); } /** * Format the date period as ISO 8601. */ public function spec(): string { return $this->toIso8601String(); } /** * Cast the current instance into the given class. * * @param string $className The $className::instance() method will be called to cast the current object. * * @return DatePeriod|object */ public function cast(string $className): object { if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( $this->rawDate($this->getStartDate()), $this->getDateInterval(), $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0, ); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Return native DatePeriod PHP object matching the current instance. * * @example * ``` * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod()); * ``` */ public function toDatePeriod(): DatePeriod { return $this->cast(DatePeriod::class); } /** * Return `true` if the period has no custom filter and is guaranteed to be endless. * * Note that we can't check if a period is endless as soon as it has custom filters * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in * a way we can't predict without actually iterating the period. */ public function isUnfilteredAndEndLess(): bool { foreach ($this->filters as $filter) { switch ($filter) { case [static::RECURRENCES_FILTER, null]: if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) { return false; } break; case [static::END_DATE_FILTER, null]: if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { return false; } break; default: return false; } } return true; } /** * Convert the date period into an array without changing current iteration state. * * @return CarbonInterface[] */ public function toArray(): array { if ($this->isUnfilteredAndEndLess()) { throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); } $state = [ $this->key, $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null, $this->validationResult, ]; $result = iterator_to_array($this); [$this->key, $this->carbonCurrent, $this->validationResult] = $state; return $result; } /** * Count dates in the date period. */ public function count(): int { return \count($this->toArray()); } /** * Return the first date in the date period. */ public function first(): ?CarbonInterface { if ($this->isUnfilteredAndEndLess()) { foreach ($this as $date) { $this->rewind(); return $date; } return null; } return ($this->toArray() ?: [])[0] ?? null; } /** * Return the last date in the date period. */ public function last(): ?CarbonInterface { $array = $this->toArray(); return $array ? $array[\count($array) - 1] : null; } /** * Convert the date period into a string. */ public function __toString(): string { return $this->toString(); } /** * Add aliases for setters. * * CarbonPeriod::days(3)->hours(5)->invert() * ->sinceNow()->until('2010-01-10') * ->filter(...) * ->count() * * Note: We use magic method to let static and instance aliases with the same names. */ public function __call(string $method, array $parameters): mixed { if (static::hasMacro($method)) { return static::bindMacroContext($this, fn () => $this->callMacro($method, $parameters)); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } $count = \count($parameters); switch ($method) { case 'start': case 'since': if ($count === 0) { return $this->getStartDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setStartDate(...$parameters); case 'sinceNow': return $this->setStartDate(new Carbon(), ...$parameters); case 'end': case 'until': if ($count === 0) { return $this->getEndDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setEndDate(...$parameters); case 'untilNow': return $this->setEndDate(new Carbon(), ...$parameters); case 'dates': case 'between': self::setDefaultParameters($parameters, [ [0, 'start', null], [1, 'end', null], ]); return $this->setDates(...$parameters); case 'recurrences': case 'times': if ($count === 0) { return $this->getRecurrences(); } self::setDefaultParameters($parameters, [ [0, 'recurrences', null], ]); return $this->setRecurrences(...$parameters); case 'options': if ($count === 0) { return $this->getOptions(); } self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->setOptions(...$parameters); case 'toggle': self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->toggleOptions(...$parameters); case 'filter': case 'push': return $this->addFilter(...$parameters); case 'prepend': return $this->prependFilter(...$parameters); case 'filters': if ($count === 0) { return $this->getFilters(); } self::setDefaultParameters($parameters, [ [0, 'filters', []], ]); return $this->setFilters(...$parameters); case 'interval': case 'each': case 'every': case 'step': case 'stepBy': if ($count === 0) { return $this->getDateInterval(); } return $this->setDateInterval(...$parameters); case 'invert': return $this->invertDateInterval(); case 'years': case 'year': case 'months': case 'month': case 'weeks': case 'week': case 'days': case 'dayz': case 'day': case 'hours': case 'hour': case 'minutes': case 'minute': case 'seconds': case 'second': case 'milliseconds': case 'millisecond': case 'microseconds': case 'microsecond': return $this->setDateInterval(( // Override default P1D when instantiating via fluent setters. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] )(...$parameters)); } $dateClass = $this->dateClass; if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { throw new UnknownMethodException($method); } return $this; } /** * Set the instance's timezone from a string or object and apply it to start/end. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->setTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->setTimezone($timezone)); } return $self; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } return $self; } /** * Returns the end is set, else calculated from start and recurrences. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. * * @return CarbonInterface */ public function calculateEnd(?string $rounding = null): CarbonInterface { if ($end = $this->getEndDate($rounding)) { return $end; } if ($this->dateInterval->isEmpty()) { return $this->getStartDate($rounding); } $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); if ($date && $rounding) { $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); } return $date; } private function getEndFromRecurrences(): ?CarbonInterface { if ($this->carbonRecurrences === null) { throw new UnreachableException( "Could not calculate period end without either explicit end or recurrences.\n". "If you're looking for a forever-period, use ->setRecurrences(INF).", ); } if ($this->carbonRecurrences === INF) { $start = $this->getStartDate(); return $start < $start->avoidMutation()->add($this->getDateInterval()) ? CarbonImmutable::endOfTime() : CarbonImmutable::startOfTime(); } if ($this->filters === [[static::RECURRENCES_FILTER, null]]) { return $this->getStartDate()->avoidMutation()->add( $this->getDateInterval()->times( $this->carbonRecurrences - ($this->isStartExcluded() ? 0 : 1), ), ); } return null; } private function iterateUntilEnd(): ?CarbonInterface { $attempts = 0; $date = null; foreach ($this as $date) { if (++$attempts > static::END_MAX_ATTEMPTS) { throw new UnreachableException( 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.', ); } } return $date; } /** * Returns true if the current period overlaps the given one (if 1 parameter passed) * or the period between 2 dates (if 2 parameters passed). * * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd * * @return bool */ public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool { $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; if (!($range instanceof self)) { $range = static::create($range); } [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); return $end > $rangeStart && $rangeEnd > $start; } /** * Execute a given function on each date of the period. * * @example * ``` * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) { * echo $date->diffInDays('2020-12-25')." days before Christmas!\n"; * }); * ``` */ public function forEach(callable $callback): void { foreach ($this as $date) { $callback($date); } } /** * Execute a given function on each date of the period and yield the result of this function. * * @example * ``` * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24'); * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) { * return $date->diffInDays('2020-12-25').' days before Christmas!'; * }))); * ``` */ public function map(callable $callback): Generator { foreach ($this as $date) { yield $callback($date); } } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. * * @see equalTo() */ public function eq(mixed $period): bool { return $this->equalTo($period); } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. */ public function equalTo(mixed $period): bool { if (!($period instanceof self)) { $period = self::make($period); } $end = $this->getEndDate(); return $period !== null && $this->getDateInterval()->eq($period->getDateInterval()) && $this->getStartDate()->eq($period->getStartDate()) && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. * * @see notEqualTo() */ public function ne(mixed $period): bool { return $this->notEqualTo($period); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. */ public function notEqualTo(mixed $period): bool { return !$this->eq($period); } /** * Determines if the start date is before another given date. * (Rather start/end are included by options is ignored.) */ public function startsBefore(mixed $date = null): bool { return $this->getStartDate()->lessThan($this->resolveCarbon($date)); } /** * Determines if the start date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsBeforeOrAt(mixed $date = null): bool { return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is after another given date. * (Rather start/end are included by options is ignored.) */ public function startsAfter(mixed $date = null): bool { return $this->getStartDate()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the start date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAfterOrAt(mixed $date = null): bool { return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAt(mixed $date = null): bool { return $this->getStartDate()->equalTo($this->resolveCarbon($date)); } /** * Determines if the end date is before another given date. * (Rather start/end are included by options is ignored.) */ public function endsBefore(mixed $date = null): bool { return $this->calculateEnd()->lessThan($this->resolveCarbon($date)); } /** * Determines if the end date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsBeforeOrAt(mixed $date = null): bool { return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is after another given date. * (Rather start/end are included by options is ignored.) */ public function endsAfter(mixed $date = null): bool { return $this->calculateEnd()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the end date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAfterOrAt(mixed $date = null): bool { return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAt(mixed $date = null): bool { return $this->calculateEnd()->equalTo($this->resolveCarbon($date)); } /** * Return true if start date is now or later. * (Rather start/end are included by options is ignored.) */ public function isStarted(): bool { return $this->startsBeforeOrAt(); } /** * Return true if end date is now or later. * (Rather start/end are included by options is ignored.) */ public function isEnded(): bool { return $this->endsBeforeOrAt(); } /** * Return true if now is between start date (included) and end date (excluded). * (Rather start/end are included by options is ignored.) */ public function isInProgress(): bool { return $this->isStarted() && !$this->isEnded(); } /** * Round the current instance at the given unit with given precision if specified and the given function. */ public function roundUnit( string $unit, DateInterval|float|int|string|null $precision = 1, callable|string $function = 'round', ): static { $self = $this->copyIfImmutable(); $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); if ($self->endDate) { $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); } /** * Truncate the current instance at the given unit with given precision if specified. */ public function floorUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. */ public function ceilUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function round( DateInterval|float|int|string|null $precision = null, callable|string $function = 'round', ): static { return $this->roundWith( $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(), $function ); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function floor(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified (else period interval is used). */ public function ceil(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'ceil'); } /** * Specify data which should be serialized to JSON. * * @link https://php.net/manual/en/jsonserializable.jsonserialize.php * * @return CarbonInterface[] */ public function jsonSerialize(): array { return $this->toArray(); } /** * Return true if the given date is between start and end. */ public function contains(mixed $date = null): bool { $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : ''); $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : ''); return $this->$startMethod($date) && $this->$endMethod($date); } /** * Return true if the current period follows a given other period (with no overlap). * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31] * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function follows(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval())); } /** * Return true if the given other period follows the current one (with no overlap). * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12] * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function isFollowedBy(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $period->follows($this); } /** * Return true if the given period either follows or is followed by the current one. * * @see follows() * @see isFollowedBy() */ public function isConsecutiveWith(mixed $period, mixed ...$arguments): bool { return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments); } public function __debugInfo(): array { $info = $this->baseDebugInfo(); unset( $info['start'], $info['end'], $info['interval'], $info['include_start_date'], $info['include_end_date'], $info['constructed'], $info["\0*\0constructed"], ); return $info; } public function __unserialize(array $data): void { try { $values = array_combine( array_map( static fn (string $key): string => preg_replace('/^\0\*\0/', '', $key), array_keys($data), ), $data, ); $this->initializeSerialization($values); foreach ($values as $key => $value) { if ($value === null) { continue; } $property = match ($key) { 'tzName' => $this->setTimezone(...), 'options' => $this->setOptions(...), 'recurrences' => $this->setRecurrences(...), 'current' => function (mixed $current): void { if (!($current instanceof CarbonInterface)) { $current = $this->resolveCarbon($current); } $this->carbonCurrent = $current; }, 'start' => 'startDate', 'interval' => $this->setDateInterval(...), 'end' => 'endDate', 'key' => null, 'include_start_date' => function (bool $included): void { $this->excludeStartDate(!$included); }, 'include_end_date' => function (bool $included): void { $this->excludeEndDate(!$included); }, default => $key, }; if ($property === null) { continue; } if (\is_callable($property)) { $property($value); continue; } if ($value instanceof DateTimeInterface && !($value instanceof CarbonInterface)) { $value = ($value instanceof DateTime) ? Carbon::instance($value) : CarbonImmutable::instance($value); } try { $this->$property = $value; } catch (Throwable) { // Must be ignored for backward-compatibility } } if (\array_key_exists('carbonRecurrences', $values)) { $this->carbonRecurrences = $values['carbonRecurrences']; } elseif (((int) ($values['recurrences'] ?? 0)) <= 1 && $this->endDate !== null) { $this->carbonRecurrences = null; } } catch (Throwable $e) { // @codeCoverageIgnoreStart if (!method_exists(parent::class, '__unserialize')) { throw $e; } parent::__unserialize($data); // @codeCoverageIgnoreEnd } } /** * Update properties after removing built-in filters. */ protected function updateInternalState(): void { if (!$this->hasFilter(static::END_DATE_FILTER)) { $this->endDate = null; } if (!$this->hasFilter(static::RECURRENCES_FILTER)) { $this->carbonRecurrences = null; } } /** * Create a filter tuple from raw parameters. * * Will create an automatic filter callback for one of Carbon's is* methods. */ protected function createFilterTuple(array $parameters): array { $method = array_shift($parameters); if (!$this->isCarbonPredicateMethod($method)) { return [$method, array_shift($parameters)]; } return [static fn ($date) => ([$date, $method])(...$parameters), $method]; } /** * Return whether given callable is a string pointing to one of Carbon's is* methods * and should be automatically converted to a filter callback. */ protected function isCarbonPredicateMethod(callable|string $callable): bool { return \is_string($callable) && str_starts_with($callable, 'is') && (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable)); } /** * Recurrences filter callback (limits number of recurrences). * * @SuppressWarnings(UnusedFormalParameter) */ protected function filterRecurrences(CarbonInterface $current, int $key): bool|callable { if ($key < $this->carbonRecurrences) { return true; } return static::END_ITERATION; } /** * End date filter callback. * * @return bool|static::END_ITERATION */ protected function filterEndDate(CarbonInterface $current): bool|callable { if (!$this->isEndExcluded() && $current == $this->endDate) { return true; } if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) { return true; } return static::END_ITERATION; } /** * End iteration filter callback. * * @return static::END_ITERATION */ protected function endIteration(): callable { return static::END_ITERATION; } /** * Handle change of the parameters. */ protected function handleChangedParameters(): void { if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { $this->dateClass = CarbonImmutable::class; } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { $this->dateClass = Carbon::class; } $this->validationResult = null; } /** * Validate current date and stop iteration when necessary. * * Returns true when current date is valid, false if it is not, or static::END_ITERATION * when iteration should be stopped. * * @return bool|static::END_ITERATION */ protected function validateCurrentDate(): bool|callable { if ($this->carbonCurrent === null) { $this->rewind(); } // Check after the first rewind to avoid repeating the initial validation. return $this->validationResult ?? ($this->validationResult = $this->checkFilters()); } /** * Check whether current value and key pass all the filters. * * @return bool|static::END_ITERATION */ protected function checkFilters(): bool|callable { $current = $this->prepareForReturn($this->carbonCurrent); foreach ($this->filters as $tuple) { $result = \call_user_func($tuple[0], $current->avoidMutation(), $this->key, $this); if ($result === static::END_ITERATION) { return static::END_ITERATION; } if (!$result) { return false; } } return true; } /** * Prepare given date to be returned to the external logic. * * @param CarbonInterface $date * * @return CarbonInterface */ protected function prepareForReturn(CarbonInterface $date) { $date = ([$this->dateClass, 'make'])($date); if ($this->timezone) { return $date->setTimezone($this->timezone); } return $date; } /** * Keep incrementing the current date until a valid date is found or the iteration is ended. * * @throws RuntimeException */ protected function incrementCurrentDateUntilValid(): void { $attempts = 0; do { $this->carbonCurrent = $this->carbonCurrent->add($this->dateInterval); $this->validationResult = null; if (++$attempts > static::NEXT_MAX_ATTEMPTS) { throw new UnreachableException('Could not find next valid date.'); } } while ($this->validateCurrentDate() === false); } /** * Call given macro. */ protected function callMacro(string $name, array $parameters): mixed { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date * * @return \Carbon\CarbonInterface */ protected function resolveCarbon($date = null) { return $this->getStartDate()->nowWithSameTz()->carbonize($date); } /** * Resolve passed arguments or DatePeriod to a CarbonPeriod object. */ protected function resolveCarbonPeriod(mixed $period, mixed ...$arguments): self { if ($period instanceof self) { return $period; } return $period instanceof DatePeriod ? static::instance($period) : static::create($period, ...$arguments); } private function orderCouple($first, $second): array { return $first > $second ? [$second, $first] : [$first, $second]; } private function makeDateTime($value): ?DateTimeInterface { if ($value instanceof DateTimeInterface) { return $value; } if ($value instanceof WeekDay || $value instanceof Month) { $dateClass = $this->dateClass; return new $dateClass($value, $this->timezoneSetting); } if (\is_string($value)) { $value = trim($value); if (!preg_match('/^P[\dT]/', $value) && !preg_match('/^R\d/', $value) && preg_match('/[a-z\d]/i', $value) ) { $dateClass = $this->dateClass; return $dateClass::parse($value, $this->timezoneSetting); } } return null; } private function isInfiniteDate($date): bool { return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); } private function rawDate($date): ?DateTimeInterface { if ($date === false || $date === null) { return null; } if ($date instanceof CarbonInterface) { return $date->isMutable() ? $date->toDateTime() : $date->toDateTimeImmutable(); } if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { return $date; } $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); } private static function setDefaultParameters(array &$parameters, array $defaults): void { foreach ($defaults as [$index, $name, $value]) { if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { $parameters[$index] = $value; } } } private function setFromAssociativeArray(array $parameters): void { if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['end'])) { $this->setEndDate($parameters['end']); } if (isset($parameters['recurrences'])) { $this->setRecurrences($parameters['recurrences']); } if (isset($parameters['interval'])) { $this->setDateInterval($parameters['interval']); } if (isset($parameters['options'])) { $this->setOptions($parameters['options']); } } private function configureTimezone(DateTimeZone $timezone, array $sortedArguments, array $originalArguments): array { $this->setTimezone($timezone); if (\is_string($originalArguments['start'] ?? null)) { $sortedArguments['start'] = $this->makeDateTime($originalArguments['start']); } if (\is_string($originalArguments['end'] ?? null)) { $sortedArguments['end'] = $this->makeDateTime($originalArguments['end']); } return $sortedArguments; } private function initializeSerialization(array $values): void { $serializationBase = [ 'start' => $values['start'] ?? $values['startDate'] ?? null, 'current' => $values['current'] ?? $values['carbonCurrent'] ?? null, 'end' => $values['end'] ?? $values['endDate'] ?? null, 'interval' => $values['interval'] ?? $values['dateInterval'] ?? null, 'recurrences' => max(1, (int) ($values['recurrences'] ?? $values['carbonRecurrences'] ?? 1)), 'include_start_date' => $values['include_start_date'] ?? true, 'include_end_date' => $values['include_end_date'] ?? false, ]; foreach (['start', 'current', 'end'] as $dateProperty) { if ($serializationBase[$dateProperty] instanceof Carbon) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTime(); } elseif ($serializationBase[$dateProperty] instanceof CarbonInterface) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTimeImmutable(); } } if ($serializationBase['interval'] instanceof CarbonInterval) { $serializationBase['interval'] = $serializationBase['interval']->toDateInterval(); } // @codeCoverageIgnoreStart if (method_exists(parent::class, '__unserialize')) { parent::__unserialize($serializationBase); return; } $excludeStart = !($values['include_start_date'] ?? true); $includeEnd = $values['include_end_date'] ?? true; parent::__construct( $serializationBase['start'], $serializationBase['interval'], $serializationBase['end'] ?? $serializationBase['recurrences'], ($excludeStart ? self::EXCLUDE_START_DATE : 0) | ($includeEnd && \defined('DatePeriod::INCLUDE_END_DATE') ? self::INCLUDE_END_DATE : 0), ); // @codeCoverageIgnoreEnd } }
PHP
{ "end_line": 1518, "name": "cast", "signature": "public function cast(string $className): object", "start_line": 1502 }
{ "class_name": "CarbonPeriod", "class_signature": "class CarbonPeriod implements Countable, JsonSerializable, UnitValue", "namespace": "Carbon" }
isUnfilteredAndEndLess
Carbon/src/Carbon/CarbonPeriod.php
public function isUnfilteredAndEndLess(): bool { foreach ($this->filters as $filter) { switch ($filter) { case [static::RECURRENCES_FILTER, null]: if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) { return false; } break; case [static::END_DATE_FILTER, null]: if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { return false; } break; default: return false; } } return true; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotACarbonClassException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnreachableException; use Carbon\Traits\DeprecatedPeriodProperties; use Carbon\Traits\IntervalRounding; use Carbon\Traits\LocalFactory; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Throwable; // @codeCoverageIgnoreStart require PHP_VERSION < 8.2 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php' : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php'; // @codeCoverageIgnoreEnd /** * Substitution of DatePeriod with some modifications and many more features. * * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. * @method static static since($date = null, $inclusive = null) Alias for start(). * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. * @method static static until($date = null, $inclusive = null) Alias for end(). * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. * @method static static times($recurrences = null) Alias for recurrences(). * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance. * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. * @method static static push($callback, $name = null) Alias for filter(). * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance. * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. * @method static static year($years = 1) Alias for years(). * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. * @method static static month($months = 1) Alias for months(). * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. * @method static static week($weeks = 1) Alias for weeks(). * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. * @method static static dayz($days = 1) Alias for days(). * @method static static day($days = 1) Alias for days(). * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. * @method static static hour($hours = 1) Alias for hours(). * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. * @method static static minute($minutes = 1) Alias for minutes(). * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. * @method static static second($seconds = 1) Alias for seconds(). * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * * @mixin DeprecatedPeriodProperties * * @SuppressWarnings(TooManyFields) * @SuppressWarnings(CamelCasePropertyName) * @SuppressWarnings(CouplingBetweenObjects) */ class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue { use LocalFactory; use IntervalRounding; use Mixin { Mixin::mixin as baseMixin; } use Options { Options::__debugInfo as baseDebugInfo; } use ToStringFormat; /** * Built-in filter for limit by recurrences. * * @var callable */ public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; /** * Built-in filter for limit to an end. * * @var callable */ public const END_DATE_FILTER = [self::class, 'filterEndDate']; /** * Special value which can be returned by filters to end iteration. Also a filter. * * @var callable */ public const END_ITERATION = [self::class, 'endIteration']; /** * Exclude end date from iteration. * * @var int */ public const EXCLUDE_END_DATE = 8; /** * Yield CarbonImmutable instances. * * @var int */ public const IMMUTABLE = 4; /** * Number of maximum attempts before giving up on finding next valid date. * * @var int */ public const NEXT_MAX_ATTEMPTS = 1000; /** * Number of maximum attempts before giving up on finding end date. * * @var int */ public const END_MAX_ATTEMPTS = 10000; /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = Carbon::class; /** * The registered macros. */ protected static array $macros = []; /** * Date class of iteration items. */ protected string $dateClass = Carbon::class; /** * Underlying date interval instance. Always present, one day by default. */ protected ?CarbonInterval $dateInterval = null; /** * True once __construct is finished. */ protected bool $constructed = false; /** * Whether current date interval was set by default. */ protected bool $isDefaultInterval = false; /** * The filters stack. */ protected array $filters = []; /** * Period start date. Applied on rewind. Always present, now by default. */ protected ?CarbonInterface $startDate = null; /** * Period end date. For inverted interval should be before the start date. Applied via a filter. */ protected ?CarbonInterface $endDate = null; /** * Limit for number of recurrences. Applied via a filter. */ protected int|float|null $carbonRecurrences = null; /** * Iteration options. */ protected ?int $options = null; /** * Index of current date. Always sequential, even if some dates are skipped by filters. * Equal to null only before the first iteration. */ protected int $key = 0; /** * Current date. May temporarily hold unaccepted value when looking for a next valid date. * Equal to null only before the first iteration. */ protected ?CarbonInterface $carbonCurrent = null; /** * Timezone of current date. Taken from the start date. */ protected ?DateTimeZone $timezone = null; /** * The cached validation result for current date. */ protected array|string|bool|null $validationResult = null; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; public function getIterator(): Generator { $this->rewind(); while ($this->valid()) { $key = $this->key(); $value = $this->current(); yield $key => $value; $this->next(); } } /** * Make a CarbonPeriod instance from given variable if possible. */ public static function make(mixed $var): ?static { try { return static::instance($var); } catch (NotAPeriodException) { return static::create($var); } } /** * Create a new instance from a DatePeriod or CarbonPeriod object. */ public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); } /** * Create a new instance. */ public static function create(...$params): static { return static::createFromArray($params); } /** * Create a new instance from an array of parameters. */ public static function createFromArray(array $params): static { return new static(...$params); } /** * Create CarbonPeriod from ISO 8601 string. */ public static function createFromIso(string $iso, ?int $options = null): static { $params = static::parseIso8601($iso); $instance = static::createFromArray($params); $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options; $instance->handleChangedParameters(); return $instance; } public static function createFromISO8601String(string $iso, ?int $options = null): static { return self::createFromIso($iso, $options); } /** * Return whether the given interval contains non-zero value of any time unit. */ protected static function intervalHasTime(DateInterval $interval): bool { return $interval->h || $interval->i || $interval->s || $interval->f; } /** * Return whether given variable is an ISO 8601 specification. * * Note: Check is very basic, as actual validation will be done later when parsing. * We just want to ensure that variable is not any other type of valid parameter. */ protected static function isIso8601(mixed $var): bool { if (!\is_string($var)) { return false; } // Match slash but not within a timezone name. $part = '[a-z]+(?:[_-][a-z]+)*'; preg_match("#\b$part/$part\b|(/)#i", $var, $match); return isset($match[1]); } /** * Parse given ISO 8601 string into an array of arguments. * * @SuppressWarnings(ElseExpression) */ protected static function parseIso8601(string $iso): array { $result = []; $interval = null; $start = null; $end = null; $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = self::makeInterval($part)) { $interval = $part; } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); } $result[] = $parsed; } return $result; } /** * Add missing parts of the target date from the source date. */ protected static function addMissingParts(string $source, string $target): string { $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); return $count ? $result : $target; } private static function makeInterval(mixed $input): ?CarbonInterval { try { return CarbonInterval::make($input); } catch (Throwable) { return null; } } private static function makeTimezone(mixed $input): ?CarbonTimeZone { if (!\is_string($input)) { return null; } try { return CarbonTimeZone::create($input); } catch (Throwable) { return null; } } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonPeriod::macro('middle', function () { * return $this->getStartDate()->average($this->getEndDate()); * }); * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonPeriod::mixin(new class { * public function addDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->addDays($count) * )->setEndDate( * $this->getEndDate()->addDays($count) * ); * }; * } * public function subDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->subDays($count) * )->setEndDate( * $this->getEndDate()->subDays($count) * ); * }; * } * }); * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); * ``` * * @throws ReflectionException */ public static function mixin(object|string $mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Provide static proxy for instance aliases. */ public static function __callStatic(string $method, array $parameters): mixed { $date = new static(); if (static::hasMacro($method)) { return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters)); } return $date->$method(...$parameters); } /** * CarbonPeriod constructor. * * @SuppressWarnings(ElseExpression) * * @throws InvalidArgumentException */ public function __construct(...$arguments) { $raw = null; if (isset($arguments['raw'])) { $raw = $arguments['raw']; $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false; if (isset($arguments['dateClass'])) { $this->dateClass = $arguments['dateClass']; } $arguments = $raw; } // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. $argumentsCount = \count($arguments); if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { array_splice($arguments, 0, 1, static::parseIso8601($iso)); } if ($argumentsCount === 1) { if ($arguments[0] instanceof self) { $arguments = [ $arguments[0]->getStartDate(), $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(), $arguments[0]->getDateInterval(), $arguments[0]->getOptions(), ]; } elseif ($arguments[0] instanceof DatePeriod) { $arguments = [ $arguments[0]->start, $arguments[0]->end ?: ($arguments[0]->recurrences - 1), $arguments[0]->interval, $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, ]; } } if (is_a($this->dateClass, DateTimeImmutable::class, true)) { $this->options = static::IMMUTABLE; } $optionsSet = false; $originalArguments = []; $sortedArguments = []; foreach ($arguments as $argument) { $parsedDate = null; if ($argument instanceof DateTimeZone) { $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments); } elseif (!isset($sortedArguments['interval']) && ( (\is_string($argument) && preg_match( '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument, )) || $argument instanceof DateInterval || $argument instanceof Closure || $argument instanceof Unit ) && $parsedInterval = self::makeInterval($argument) ) { $sortedArguments['interval'] = $parsedInterval; } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) { $sortedArguments['start'] = $parsedDate; $originalArguments['start'] = $argument; } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { $sortedArguments['end'] = $parsedDate; $originalArguments['end'] = $argument; } elseif (!isset($sortedArguments['recurrences']) && !isset($sortedArguments['end']) && (\is_int($argument) || \is_float($argument)) && $argument >= 0 ) { $sortedArguments['recurrences'] = $argument; } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { $optionsSet = true; $sortedArguments['options'] = (((int) $this->options) | ((int) $argument)); } elseif ($parsedTimezone = self::makeTimezone($argument)) { $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($raw === null && isset($sortedArguments['start'])) { $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1); if (\is_float($end)) { $end = $end === INF ? PHP_INT_MAX : (int) round($end); } $raw = [ $sortedArguments['start'], $sortedArguments['interval'] ?? CarbonInterval::day(), $end, ]; } $this->setFromAssociativeArray($sortedArguments); if ($this->startDate === null) { $dateClass = $this->dateClass; $this->setStartDate($dateClass::now()); } if ($this->dateInterval === null) { $this->setDateInterval(CarbonInterval::day()); $this->isDefaultInterval = true; } if ($this->options === null) { $this->setOptions(0); } parent::__construct( $this->startDate, $this->dateInterval, $this->endDate ?? max(1, min(2147483639, $this->recurrences ?? 1)), $this->options, ); $this->constructed = true; } /** * Get a copy of the instance. */ public function copy(): static { return clone $this; } /** * Prepare the instance to be set (self if mutable to be mutated, * copy if immutable to generate a new instance). */ protected function copyIfImmutable(): static { return $this; } /** * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. */ protected function getGetter(string $name): ?callable { return match (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) { 'start', 'start_date' => [$this, 'getStartDate'], 'end', 'end_date' => [$this, 'getEndDate'], 'interval', 'date_interval' => [$this, 'getDateInterval'], 'recurrences' => [$this, 'getRecurrences'], 'include_start_date' => [$this, 'isStartIncluded'], 'include_end_date' => [$this, 'isEndIncluded'], 'current' => [$this, 'current'], 'locale' => [$this, 'locale'], 'tzname', 'tz_name' => fn () => match (true) { $this->timezoneSetting === null => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, $this->timezoneSetting instanceof DateTimeZone => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, default => null, }; } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function get(string $name) { $getter = $this->getGetter($name); if ($getter) { return $getter(); } throw new UnknownGetterException($name); } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function __get(string $name) { return $this->get($name); } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset(string $name): bool { return $this->getGetter($name) !== null; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Set the iteration item class. * * @param string $dateClass * * @return static */ public function setDateClass(string $dateClass) { if (!is_a($dateClass, CarbonInterface::class, true)) { throw new NotACarbonClassException($dateClass); } $self = $this->copyIfImmutable(); $self->dateClass = $dateClass; if (is_a($dateClass, Carbon::class, true)) { $self->options = $self->options & ~static::IMMUTABLE; } elseif (is_a($dateClass, CarbonImmutable::class, true)) { $self->options = $self->options | static::IMMUTABLE; } return $self; } /** * Returns iteration item date class. * * @return string */ public function getDateClass(): string { return $this->dateClass; } /** * Change the period date interval. * * @param DateInterval|Unit|string|int $interval * @param Unit|string $unit the unit of $interval if it's a number * * @throws InvalidIntervalException * * @return static */ public function setDateInterval(mixed $interval, Unit|string|null $unit = null): static { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->name; } if (!$interval = CarbonInterval::make($interval, $unit)) { throw new InvalidIntervalException('Invalid interval.'); } if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) { throw new InvalidIntervalException('Empty interval is not accepted.'); } $self = $this->copyIfImmutable(); $self->dateInterval = $interval; $self->isDefaultInterval = false; $self->handleChangedParameters(); return $self; } /** * Reset the date interval to the default value. * * Difference with simply setting interval to 1-day is that P1D will not appear when calling toIso8601String() * and also next adding to the interval won't include the default 1-day. */ public function resetDateInterval(): static { $self = $this->copyIfImmutable(); $self->setDateInterval(CarbonInterval::day()); $self->isDefaultInterval = true; return $self; } /** * Invert the period date interval. */ public function invertDateInterval(): static { return $this->setDateInterval($this->dateInterval->invert()); } /** * Set start and end date. * * @param DateTime|DateTimeInterface|string $start * @param DateTime|DateTimeInterface|string|null $end * * @return static */ public function setDates(mixed $start, mixed $end): static { return $this->setStartDate($start)->setEndDate($end); } /** * Change the period options. * * @param int|null $options * * @return static */ public function setOptions(?int $options): static { $self = $this->copyIfImmutable(); $self->options = $options ?? 0; $self->handleChangedParameters(); return $self; } /** * Get the period options. */ public function getOptions(): int { return $this->options ?? 0; } /** * Toggle given options on or off. * * @param int $options * @param bool|null $state * * @throws InvalidArgumentException * * @return static */ public function toggleOptions(int $options, ?bool $state = null): static { $self = $this->copyIfImmutable(); if ($state === null) { $state = ($this->options & $options) !== $options; } return $self->setOptions( $state ? $this->options | $options : $this->options & ~$options, ); } /** * Toggle EXCLUDE_START_DATE option. */ public function excludeStartDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_START_DATE, $state); } /** * Toggle EXCLUDE_END_DATE option. */ public function excludeEndDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_END_DATE, $state); } /** * Get the underlying date interval. */ public function getDateInterval(): CarbonInterval { return $this->dateInterval->copy(); } /** * Get start date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getStartDate(?string $rounding = null): CarbonInterface { $date = $this->startDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get end date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getEndDate(?string $rounding = null): ?CarbonInterface { if (!$this->endDate) { return null; } $date = $this->endDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get number of recurrences. */ #[ReturnTypeWillChange] public function getRecurrences(): int|float|null { return $this->carbonRecurrences; } /** * Returns true if the start date should be excluded. */ public function isStartExcluded(): bool { return ($this->options & static::EXCLUDE_START_DATE) !== 0; } /** * Returns true if the end date should be excluded. */ public function isEndExcluded(): bool { return ($this->options & static::EXCLUDE_END_DATE) !== 0; } /** * Returns true if the start date should be included. */ public function isStartIncluded(): bool { return !$this->isStartExcluded(); } /** * Returns true if the end date should be included. */ public function isEndIncluded(): bool { return !$this->isEndExcluded(); } /** * Return the start if it's included by option, else return the start + 1 period interval. */ public function getIncludedStartDate(): CarbonInterface { $start = $this->getStartDate(); if ($this->isStartExcluded()) { return $start->add($this->getDateInterval()); } return $start; } /** * Return the end if it's included by option, else return the end - 1 period interval. * Warning: if the period has no fixed end, this method will iterate the period to calculate it. */ public function getIncludedEndDate(): CarbonInterface { $end = $this->getEndDate(); if (!$end) { return $this->calculateEnd(); } if ($this->isEndExcluded()) { return $end->sub($this->getDateInterval()); } return $end; } /** * Add a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function addFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); $self->filters[] = $tuple; $self->handleChangedParameters(); return $self; } /** * Prepend a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function prependFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); array_unshift($self->filters, $tuple); $self->handleChangedParameters(); return $self; } /** * Remove a filter by instance or name. */ public function removeFilter(callable|string $filter): static { $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; $self->filters = array_values(array_filter( $this->filters, static fn ($tuple) => $tuple[$key] !== $filter, )); $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Return whether given instance or name is in the filter stack. */ public function hasFilter(callable|string $filter): bool { $key = \is_callable($filter) ? 0 : 1; foreach ($this->filters as $tuple) { if ($tuple[$key] === $filter) { return true; } } return false; } /** * Get filters stack. */ public function getFilters(): array { return $this->filters; } /** * Set filters stack. */ public function setFilters(array $filters): static { $self = $this->copyIfImmutable(); $self->filters = $filters; $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Reset filters stack. */ public function resetFilters(): static { $self = $this->copyIfImmutable(); $self->filters = []; if ($self->endDate !== null) { $self->filters[] = [static::END_DATE_FILTER, null]; } if ($self->carbonRecurrences !== null) { $self->filters[] = [static::RECURRENCES_FILTER, null]; } $self->handleChangedParameters(); return $self; } /** * Add a recurrences filter (set maximum number of recurrences). * * @throws InvalidArgumentException */ public function setRecurrences(int|float|null $recurrences): static { if ($recurrences === null) { return $this->removeFilter(static::RECURRENCES_FILTER); } if ($recurrences < 0) { throw new InvalidPeriodParameterException('Invalid number of recurrences.'); } /** @var self $self */ $self = $this->copyIfImmutable(); $self->carbonRecurrences = $recurrences === INF ? INF : (int) $recurrences; if (!$self->hasFilter(static::RECURRENCES_FILTER)) { return $self->addFilter(static::RECURRENCES_FILTER); } $self->handleChangedParameters(); return $self; } /** * Change the period start date. * * @param DateTime|DateTimeInterface|string $date * @param bool|null $inclusive * * @throws InvalidPeriodDateException * * @return static */ public function setStartDate(mixed $date, ?bool $inclusive = null): static { if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date, $this->timezone))) { throw new InvalidPeriodDateException('Invalid start date.'); } $self = $this->copyIfImmutable(); $self->startDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); } return $self; } /** * Change the period end date. * * @param DateTime|DateTimeInterface|string|null $date * @param bool|null $inclusive * * @throws \InvalidArgumentException * * @return static */ public function setEndDate(mixed $date, ?bool $inclusive = null): static { if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date, $this->timezone)) { throw new InvalidPeriodDateException('Invalid end date.'); } if (!$date) { return $this->removeFilter(static::END_DATE_FILTER); } $self = $this->copyIfImmutable(); $self->endDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); } if (!$self->hasFilter(static::END_DATE_FILTER)) { return $self->addFilter(static::END_DATE_FILTER); } $self->handleChangedParameters(); return $self; } /** * Check if the current position is valid. */ public function valid(): bool { return $this->validateCurrentDate() === true; } /** * Return the current key. */ public function key(): ?int { return $this->valid() ? $this->key : null; } /** * Return the current date. */ public function current(): ?CarbonInterface { return $this->valid() ? $this->prepareForReturn($this->carbonCurrent) : null; } /** * Move forward to the next date. * * @throws RuntimeException */ public function next(): void { if ($this->carbonCurrent === null) { $this->rewind(); } if ($this->validationResult !== static::END_ITERATION) { $this->key++; $this->incrementCurrentDateUntilValid(); } } /** * Rewind to the start date. * * Iterating over a date in the UTC timezone avoids bug during backward DST change. * * @see https://bugs.php.net/bug.php?id=72255 * @see https://bugs.php.net/bug.php?id=74274 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time * * @throws RuntimeException */ public function rewind(): void { $this->key = 0; $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate); $settings = $this->getSettings(); if ($this->hasLocalTranslator()) { $settings['locale'] = $this->getTranslatorLocale(); } $this->carbonCurrent->settings($settings); $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null; if ($this->timezone) { $this->carbonCurrent = $this->carbonCurrent->utc(); } $this->validationResult = null; if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { $this->incrementCurrentDateUntilValid(); } } /** * Skip iterations and returns iteration state (false if ended, true if still valid). * * @param int $count steps number to skip (1 by default) * * @return bool */ public function skip(int $count = 1): bool { for ($i = $count; $this->valid() && $i > 0; $i--) { $this->next(); } return $this->valid(); } /** * Format the date period as ISO 8601. */ public function toIso8601String(): string { $parts = []; if ($this->carbonRecurrences !== null) { $parts[] = 'R'.$this->carbonRecurrences; } $parts[] = $this->startDate->toIso8601String(); if (!$this->isDefaultInterval) { $parts[] = $this->dateInterval->spec(); } if ($this->endDate !== null) { $parts[] = $this->endDate->toIso8601String(); } return implode('/', $parts); } /** * Convert the date period into a string. */ public function toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if ($format instanceof Closure) { return $format($this); } $translator = ([$this->dateClass, 'getTranslator'])(); $parts = []; $format = $format ?? ( !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) ? 'Y-m-d H:i:s' : 'Y-m-d' ); if ($this->carbonRecurrences !== null) { $parts[] = $this->translate('period_recurrences', [], $this->carbonRecurrences, $translator); } $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([ 'join' => true, ])], null, $translator); $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator); if ($this->endDate !== null) { $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator); } $result = implode(' ', $parts); return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1); } /** * Format the date period as ISO 8601. */ public function spec(): string { return $this->toIso8601String(); } /** * Cast the current instance into the given class. * * @param string $className The $className::instance() method will be called to cast the current object. * * @return DatePeriod|object */ public function cast(string $className): object { if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( $this->rawDate($this->getStartDate()), $this->getDateInterval(), $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0, ); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Return native DatePeriod PHP object matching the current instance. * * @example * ``` * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod()); * ``` */ public function toDatePeriod(): DatePeriod { return $this->cast(DatePeriod::class); } /** * Return `true` if the period has no custom filter and is guaranteed to be endless. * * Note that we can't check if a period is endless as soon as it has custom filters * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in * a way we can't predict without actually iterating the period. */ public function isUnfilteredAndEndLess(): bool { foreach ($this->filters as $filter) { switch ($filter) { case [static::RECURRENCES_FILTER, null]: if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) { return false; } break; case [static::END_DATE_FILTER, null]: if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { return false; } break; default: return false; } } return true; } /** * Convert the date period into an array without changing current iteration state. * * @return CarbonInterface[] */ public function toArray(): array { if ($this->isUnfilteredAndEndLess()) { throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); } $state = [ $this->key, $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null, $this->validationResult, ]; $result = iterator_to_array($this); [$this->key, $this->carbonCurrent, $this->validationResult] = $state; return $result; } /** * Count dates in the date period. */ public function count(): int { return \count($this->toArray()); } /** * Return the first date in the date period. */ public function first(): ?CarbonInterface { if ($this->isUnfilteredAndEndLess()) { foreach ($this as $date) { $this->rewind(); return $date; } return null; } return ($this->toArray() ?: [])[0] ?? null; } /** * Return the last date in the date period. */ public function last(): ?CarbonInterface { $array = $this->toArray(); return $array ? $array[\count($array) - 1] : null; } /** * Convert the date period into a string. */ public function __toString(): string { return $this->toString(); } /** * Add aliases for setters. * * CarbonPeriod::days(3)->hours(5)->invert() * ->sinceNow()->until('2010-01-10') * ->filter(...) * ->count() * * Note: We use magic method to let static and instance aliases with the same names. */ public function __call(string $method, array $parameters): mixed { if (static::hasMacro($method)) { return static::bindMacroContext($this, fn () => $this->callMacro($method, $parameters)); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } $count = \count($parameters); switch ($method) { case 'start': case 'since': if ($count === 0) { return $this->getStartDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setStartDate(...$parameters); case 'sinceNow': return $this->setStartDate(new Carbon(), ...$parameters); case 'end': case 'until': if ($count === 0) { return $this->getEndDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setEndDate(...$parameters); case 'untilNow': return $this->setEndDate(new Carbon(), ...$parameters); case 'dates': case 'between': self::setDefaultParameters($parameters, [ [0, 'start', null], [1, 'end', null], ]); return $this->setDates(...$parameters); case 'recurrences': case 'times': if ($count === 0) { return $this->getRecurrences(); } self::setDefaultParameters($parameters, [ [0, 'recurrences', null], ]); return $this->setRecurrences(...$parameters); case 'options': if ($count === 0) { return $this->getOptions(); } self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->setOptions(...$parameters); case 'toggle': self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->toggleOptions(...$parameters); case 'filter': case 'push': return $this->addFilter(...$parameters); case 'prepend': return $this->prependFilter(...$parameters); case 'filters': if ($count === 0) { return $this->getFilters(); } self::setDefaultParameters($parameters, [ [0, 'filters', []], ]); return $this->setFilters(...$parameters); case 'interval': case 'each': case 'every': case 'step': case 'stepBy': if ($count === 0) { return $this->getDateInterval(); } return $this->setDateInterval(...$parameters); case 'invert': return $this->invertDateInterval(); case 'years': case 'year': case 'months': case 'month': case 'weeks': case 'week': case 'days': case 'dayz': case 'day': case 'hours': case 'hour': case 'minutes': case 'minute': case 'seconds': case 'second': case 'milliseconds': case 'millisecond': case 'microseconds': case 'microsecond': return $this->setDateInterval(( // Override default P1D when instantiating via fluent setters. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] )(...$parameters)); } $dateClass = $this->dateClass; if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { throw new UnknownMethodException($method); } return $this; } /** * Set the instance's timezone from a string or object and apply it to start/end. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->setTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->setTimezone($timezone)); } return $self; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } return $self; } /** * Returns the end is set, else calculated from start and recurrences. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. * * @return CarbonInterface */ public function calculateEnd(?string $rounding = null): CarbonInterface { if ($end = $this->getEndDate($rounding)) { return $end; } if ($this->dateInterval->isEmpty()) { return $this->getStartDate($rounding); } $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); if ($date && $rounding) { $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); } return $date; } private function getEndFromRecurrences(): ?CarbonInterface { if ($this->carbonRecurrences === null) { throw new UnreachableException( "Could not calculate period end without either explicit end or recurrences.\n". "If you're looking for a forever-period, use ->setRecurrences(INF).", ); } if ($this->carbonRecurrences === INF) { $start = $this->getStartDate(); return $start < $start->avoidMutation()->add($this->getDateInterval()) ? CarbonImmutable::endOfTime() : CarbonImmutable::startOfTime(); } if ($this->filters === [[static::RECURRENCES_FILTER, null]]) { return $this->getStartDate()->avoidMutation()->add( $this->getDateInterval()->times( $this->carbonRecurrences - ($this->isStartExcluded() ? 0 : 1), ), ); } return null; } private function iterateUntilEnd(): ?CarbonInterface { $attempts = 0; $date = null; foreach ($this as $date) { if (++$attempts > static::END_MAX_ATTEMPTS) { throw new UnreachableException( 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.', ); } } return $date; } /** * Returns true if the current period overlaps the given one (if 1 parameter passed) * or the period between 2 dates (if 2 parameters passed). * * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd * * @return bool */ public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool { $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; if (!($range instanceof self)) { $range = static::create($range); } [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); return $end > $rangeStart && $rangeEnd > $start; } /** * Execute a given function on each date of the period. * * @example * ``` * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) { * echo $date->diffInDays('2020-12-25')." days before Christmas!\n"; * }); * ``` */ public function forEach(callable $callback): void { foreach ($this as $date) { $callback($date); } } /** * Execute a given function on each date of the period and yield the result of this function. * * @example * ``` * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24'); * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) { * return $date->diffInDays('2020-12-25').' days before Christmas!'; * }))); * ``` */ public function map(callable $callback): Generator { foreach ($this as $date) { yield $callback($date); } } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. * * @see equalTo() */ public function eq(mixed $period): bool { return $this->equalTo($period); } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. */ public function equalTo(mixed $period): bool { if (!($period instanceof self)) { $period = self::make($period); } $end = $this->getEndDate(); return $period !== null && $this->getDateInterval()->eq($period->getDateInterval()) && $this->getStartDate()->eq($period->getStartDate()) && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. * * @see notEqualTo() */ public function ne(mixed $period): bool { return $this->notEqualTo($period); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. */ public function notEqualTo(mixed $period): bool { return !$this->eq($period); } /** * Determines if the start date is before another given date. * (Rather start/end are included by options is ignored.) */ public function startsBefore(mixed $date = null): bool { return $this->getStartDate()->lessThan($this->resolveCarbon($date)); } /** * Determines if the start date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsBeforeOrAt(mixed $date = null): bool { return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is after another given date. * (Rather start/end are included by options is ignored.) */ public function startsAfter(mixed $date = null): bool { return $this->getStartDate()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the start date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAfterOrAt(mixed $date = null): bool { return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAt(mixed $date = null): bool { return $this->getStartDate()->equalTo($this->resolveCarbon($date)); } /** * Determines if the end date is before another given date. * (Rather start/end are included by options is ignored.) */ public function endsBefore(mixed $date = null): bool { return $this->calculateEnd()->lessThan($this->resolveCarbon($date)); } /** * Determines if the end date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsBeforeOrAt(mixed $date = null): bool { return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is after another given date. * (Rather start/end are included by options is ignored.) */ public function endsAfter(mixed $date = null): bool { return $this->calculateEnd()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the end date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAfterOrAt(mixed $date = null): bool { return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAt(mixed $date = null): bool { return $this->calculateEnd()->equalTo($this->resolveCarbon($date)); } /** * Return true if start date is now or later. * (Rather start/end are included by options is ignored.) */ public function isStarted(): bool { return $this->startsBeforeOrAt(); } /** * Return true if end date is now or later. * (Rather start/end are included by options is ignored.) */ public function isEnded(): bool { return $this->endsBeforeOrAt(); } /** * Return true if now is between start date (included) and end date (excluded). * (Rather start/end are included by options is ignored.) */ public function isInProgress(): bool { return $this->isStarted() && !$this->isEnded(); } /** * Round the current instance at the given unit with given precision if specified and the given function. */ public function roundUnit( string $unit, DateInterval|float|int|string|null $precision = 1, callable|string $function = 'round', ): static { $self = $this->copyIfImmutable(); $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); if ($self->endDate) { $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); } /** * Truncate the current instance at the given unit with given precision if specified. */ public function floorUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. */ public function ceilUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function round( DateInterval|float|int|string|null $precision = null, callable|string $function = 'round', ): static { return $this->roundWith( $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(), $function ); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function floor(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified (else period interval is used). */ public function ceil(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'ceil'); } /** * Specify data which should be serialized to JSON. * * @link https://php.net/manual/en/jsonserializable.jsonserialize.php * * @return CarbonInterface[] */ public function jsonSerialize(): array { return $this->toArray(); } /** * Return true if the given date is between start and end. */ public function contains(mixed $date = null): bool { $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : ''); $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : ''); return $this->$startMethod($date) && $this->$endMethod($date); } /** * Return true if the current period follows a given other period (with no overlap). * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31] * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function follows(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval())); } /** * Return true if the given other period follows the current one (with no overlap). * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12] * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function isFollowedBy(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $period->follows($this); } /** * Return true if the given period either follows or is followed by the current one. * * @see follows() * @see isFollowedBy() */ public function isConsecutiveWith(mixed $period, mixed ...$arguments): bool { return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments); } public function __debugInfo(): array { $info = $this->baseDebugInfo(); unset( $info['start'], $info['end'], $info['interval'], $info['include_start_date'], $info['include_end_date'], $info['constructed'], $info["\0*\0constructed"], ); return $info; } public function __unserialize(array $data): void { try { $values = array_combine( array_map( static fn (string $key): string => preg_replace('/^\0\*\0/', '', $key), array_keys($data), ), $data, ); $this->initializeSerialization($values); foreach ($values as $key => $value) { if ($value === null) { continue; } $property = match ($key) { 'tzName' => $this->setTimezone(...), 'options' => $this->setOptions(...), 'recurrences' => $this->setRecurrences(...), 'current' => function (mixed $current): void { if (!($current instanceof CarbonInterface)) { $current = $this->resolveCarbon($current); } $this->carbonCurrent = $current; }, 'start' => 'startDate', 'interval' => $this->setDateInterval(...), 'end' => 'endDate', 'key' => null, 'include_start_date' => function (bool $included): void { $this->excludeStartDate(!$included); }, 'include_end_date' => function (bool $included): void { $this->excludeEndDate(!$included); }, default => $key, }; if ($property === null) { continue; } if (\is_callable($property)) { $property($value); continue; } if ($value instanceof DateTimeInterface && !($value instanceof CarbonInterface)) { $value = ($value instanceof DateTime) ? Carbon::instance($value) : CarbonImmutable::instance($value); } try { $this->$property = $value; } catch (Throwable) { // Must be ignored for backward-compatibility } } if (\array_key_exists('carbonRecurrences', $values)) { $this->carbonRecurrences = $values['carbonRecurrences']; } elseif (((int) ($values['recurrences'] ?? 0)) <= 1 && $this->endDate !== null) { $this->carbonRecurrences = null; } } catch (Throwable $e) { // @codeCoverageIgnoreStart if (!method_exists(parent::class, '__unserialize')) { throw $e; } parent::__unserialize($data); // @codeCoverageIgnoreEnd } } /** * Update properties after removing built-in filters. */ protected function updateInternalState(): void { if (!$this->hasFilter(static::END_DATE_FILTER)) { $this->endDate = null; } if (!$this->hasFilter(static::RECURRENCES_FILTER)) { $this->carbonRecurrences = null; } } /** * Create a filter tuple from raw parameters. * * Will create an automatic filter callback for one of Carbon's is* methods. */ protected function createFilterTuple(array $parameters): array { $method = array_shift($parameters); if (!$this->isCarbonPredicateMethod($method)) { return [$method, array_shift($parameters)]; } return [static fn ($date) => ([$date, $method])(...$parameters), $method]; } /** * Return whether given callable is a string pointing to one of Carbon's is* methods * and should be automatically converted to a filter callback. */ protected function isCarbonPredicateMethod(callable|string $callable): bool { return \is_string($callable) && str_starts_with($callable, 'is') && (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable)); } /** * Recurrences filter callback (limits number of recurrences). * * @SuppressWarnings(UnusedFormalParameter) */ protected function filterRecurrences(CarbonInterface $current, int $key): bool|callable { if ($key < $this->carbonRecurrences) { return true; } return static::END_ITERATION; } /** * End date filter callback. * * @return bool|static::END_ITERATION */ protected function filterEndDate(CarbonInterface $current): bool|callable { if (!$this->isEndExcluded() && $current == $this->endDate) { return true; } if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) { return true; } return static::END_ITERATION; } /** * End iteration filter callback. * * @return static::END_ITERATION */ protected function endIteration(): callable { return static::END_ITERATION; } /** * Handle change of the parameters. */ protected function handleChangedParameters(): void { if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { $this->dateClass = CarbonImmutable::class; } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { $this->dateClass = Carbon::class; } $this->validationResult = null; } /** * Validate current date and stop iteration when necessary. * * Returns true when current date is valid, false if it is not, or static::END_ITERATION * when iteration should be stopped. * * @return bool|static::END_ITERATION */ protected function validateCurrentDate(): bool|callable { if ($this->carbonCurrent === null) { $this->rewind(); } // Check after the first rewind to avoid repeating the initial validation. return $this->validationResult ?? ($this->validationResult = $this->checkFilters()); } /** * Check whether current value and key pass all the filters. * * @return bool|static::END_ITERATION */ protected function checkFilters(): bool|callable { $current = $this->prepareForReturn($this->carbonCurrent); foreach ($this->filters as $tuple) { $result = \call_user_func($tuple[0], $current->avoidMutation(), $this->key, $this); if ($result === static::END_ITERATION) { return static::END_ITERATION; } if (!$result) { return false; } } return true; } /** * Prepare given date to be returned to the external logic. * * @param CarbonInterface $date * * @return CarbonInterface */ protected function prepareForReturn(CarbonInterface $date) { $date = ([$this->dateClass, 'make'])($date); if ($this->timezone) { return $date->setTimezone($this->timezone); } return $date; } /** * Keep incrementing the current date until a valid date is found or the iteration is ended. * * @throws RuntimeException */ protected function incrementCurrentDateUntilValid(): void { $attempts = 0; do { $this->carbonCurrent = $this->carbonCurrent->add($this->dateInterval); $this->validationResult = null; if (++$attempts > static::NEXT_MAX_ATTEMPTS) { throw new UnreachableException('Could not find next valid date.'); } } while ($this->validateCurrentDate() === false); } /** * Call given macro. */ protected function callMacro(string $name, array $parameters): mixed { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date * * @return \Carbon\CarbonInterface */ protected function resolveCarbon($date = null) { return $this->getStartDate()->nowWithSameTz()->carbonize($date); } /** * Resolve passed arguments or DatePeriod to a CarbonPeriod object. */ protected function resolveCarbonPeriod(mixed $period, mixed ...$arguments): self { if ($period instanceof self) { return $period; } return $period instanceof DatePeriod ? static::instance($period) : static::create($period, ...$arguments); } private function orderCouple($first, $second): array { return $first > $second ? [$second, $first] : [$first, $second]; } private function makeDateTime($value): ?DateTimeInterface { if ($value instanceof DateTimeInterface) { return $value; } if ($value instanceof WeekDay || $value instanceof Month) { $dateClass = $this->dateClass; return new $dateClass($value, $this->timezoneSetting); } if (\is_string($value)) { $value = trim($value); if (!preg_match('/^P[\dT]/', $value) && !preg_match('/^R\d/', $value) && preg_match('/[a-z\d]/i', $value) ) { $dateClass = $this->dateClass; return $dateClass::parse($value, $this->timezoneSetting); } } return null; } private function isInfiniteDate($date): bool { return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); } private function rawDate($date): ?DateTimeInterface { if ($date === false || $date === null) { return null; } if ($date instanceof CarbonInterface) { return $date->isMutable() ? $date->toDateTime() : $date->toDateTimeImmutable(); } if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { return $date; } $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); } private static function setDefaultParameters(array &$parameters, array $defaults): void { foreach ($defaults as [$index, $name, $value]) { if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { $parameters[$index] = $value; } } } private function setFromAssociativeArray(array $parameters): void { if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['end'])) { $this->setEndDate($parameters['end']); } if (isset($parameters['recurrences'])) { $this->setRecurrences($parameters['recurrences']); } if (isset($parameters['interval'])) { $this->setDateInterval($parameters['interval']); } if (isset($parameters['options'])) { $this->setOptions($parameters['options']); } } private function configureTimezone(DateTimeZone $timezone, array $sortedArguments, array $originalArguments): array { $this->setTimezone($timezone); if (\is_string($originalArguments['start'] ?? null)) { $sortedArguments['start'] = $this->makeDateTime($originalArguments['start']); } if (\is_string($originalArguments['end'] ?? null)) { $sortedArguments['end'] = $this->makeDateTime($originalArguments['end']); } return $sortedArguments; } private function initializeSerialization(array $values): void { $serializationBase = [ 'start' => $values['start'] ?? $values['startDate'] ?? null, 'current' => $values['current'] ?? $values['carbonCurrent'] ?? null, 'end' => $values['end'] ?? $values['endDate'] ?? null, 'interval' => $values['interval'] ?? $values['dateInterval'] ?? null, 'recurrences' => max(1, (int) ($values['recurrences'] ?? $values['carbonRecurrences'] ?? 1)), 'include_start_date' => $values['include_start_date'] ?? true, 'include_end_date' => $values['include_end_date'] ?? false, ]; foreach (['start', 'current', 'end'] as $dateProperty) { if ($serializationBase[$dateProperty] instanceof Carbon) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTime(); } elseif ($serializationBase[$dateProperty] instanceof CarbonInterface) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTimeImmutable(); } } if ($serializationBase['interval'] instanceof CarbonInterval) { $serializationBase['interval'] = $serializationBase['interval']->toDateInterval(); } // @codeCoverageIgnoreStart if (method_exists(parent::class, '__unserialize')) { parent::__unserialize($serializationBase); return; } $excludeStart = !($values['include_start_date'] ?? true); $includeEnd = $values['include_end_date'] ?? true; parent::__construct( $serializationBase['start'], $serializationBase['interval'], $serializationBase['end'] ?? $serializationBase['recurrences'], ($excludeStart ? self::EXCLUDE_START_DATE : 0) | ($includeEnd && \defined('DatePeriod::INCLUDE_END_DATE') ? self::INCLUDE_END_DATE : 0), ); // @codeCoverageIgnoreEnd } }
PHP
{ "end_line": 1564, "name": "isUnfilteredAndEndLess", "signature": "public function isUnfilteredAndEndLess(): bool", "start_line": 1540 }
{ "class_name": "CarbonPeriod", "class_signature": "class CarbonPeriod implements Countable, JsonSerializable, UnitValue", "namespace": "Carbon" }
toArray
Carbon/src/Carbon/CarbonPeriod.php
public function toArray(): array { if ($this->isUnfilteredAndEndLess()) { throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); } $state = [ $this->key, $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null, $this->validationResult, ]; $result = iterator_to_array($this); [$this->key, $this->carbonCurrent, $this->validationResult] = $state; return $result; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotACarbonClassException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnreachableException; use Carbon\Traits\DeprecatedPeriodProperties; use Carbon\Traits\IntervalRounding; use Carbon\Traits\LocalFactory; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Throwable; // @codeCoverageIgnoreStart require PHP_VERSION < 8.2 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php' : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php'; // @codeCoverageIgnoreEnd /** * Substitution of DatePeriod with some modifications and many more features. * * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. * @method static static since($date = null, $inclusive = null) Alias for start(). * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. * @method static static until($date = null, $inclusive = null) Alias for end(). * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. * @method static static times($recurrences = null) Alias for recurrences(). * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance. * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. * @method static static push($callback, $name = null) Alias for filter(). * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance. * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. * @method static static year($years = 1) Alias for years(). * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. * @method static static month($months = 1) Alias for months(). * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. * @method static static week($weeks = 1) Alias for weeks(). * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. * @method static static dayz($days = 1) Alias for days(). * @method static static day($days = 1) Alias for days(). * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. * @method static static hour($hours = 1) Alias for hours(). * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. * @method static static minute($minutes = 1) Alias for minutes(). * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. * @method static static second($seconds = 1) Alias for seconds(). * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * * @mixin DeprecatedPeriodProperties * * @SuppressWarnings(TooManyFields) * @SuppressWarnings(CamelCasePropertyName) * @SuppressWarnings(CouplingBetweenObjects) */ class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue { use LocalFactory; use IntervalRounding; use Mixin { Mixin::mixin as baseMixin; } use Options { Options::__debugInfo as baseDebugInfo; } use ToStringFormat; /** * Built-in filter for limit by recurrences. * * @var callable */ public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; /** * Built-in filter for limit to an end. * * @var callable */ public const END_DATE_FILTER = [self::class, 'filterEndDate']; /** * Special value which can be returned by filters to end iteration. Also a filter. * * @var callable */ public const END_ITERATION = [self::class, 'endIteration']; /** * Exclude end date from iteration. * * @var int */ public const EXCLUDE_END_DATE = 8; /** * Yield CarbonImmutable instances. * * @var int */ public const IMMUTABLE = 4; /** * Number of maximum attempts before giving up on finding next valid date. * * @var int */ public const NEXT_MAX_ATTEMPTS = 1000; /** * Number of maximum attempts before giving up on finding end date. * * @var int */ public const END_MAX_ATTEMPTS = 10000; /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = Carbon::class; /** * The registered macros. */ protected static array $macros = []; /** * Date class of iteration items. */ protected string $dateClass = Carbon::class; /** * Underlying date interval instance. Always present, one day by default. */ protected ?CarbonInterval $dateInterval = null; /** * True once __construct is finished. */ protected bool $constructed = false; /** * Whether current date interval was set by default. */ protected bool $isDefaultInterval = false; /** * The filters stack. */ protected array $filters = []; /** * Period start date. Applied on rewind. Always present, now by default. */ protected ?CarbonInterface $startDate = null; /** * Period end date. For inverted interval should be before the start date. Applied via a filter. */ protected ?CarbonInterface $endDate = null; /** * Limit for number of recurrences. Applied via a filter. */ protected int|float|null $carbonRecurrences = null; /** * Iteration options. */ protected ?int $options = null; /** * Index of current date. Always sequential, even if some dates are skipped by filters. * Equal to null only before the first iteration. */ protected int $key = 0; /** * Current date. May temporarily hold unaccepted value when looking for a next valid date. * Equal to null only before the first iteration. */ protected ?CarbonInterface $carbonCurrent = null; /** * Timezone of current date. Taken from the start date. */ protected ?DateTimeZone $timezone = null; /** * The cached validation result for current date. */ protected array|string|bool|null $validationResult = null; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; public function getIterator(): Generator { $this->rewind(); while ($this->valid()) { $key = $this->key(); $value = $this->current(); yield $key => $value; $this->next(); } } /** * Make a CarbonPeriod instance from given variable if possible. */ public static function make(mixed $var): ?static { try { return static::instance($var); } catch (NotAPeriodException) { return static::create($var); } } /** * Create a new instance from a DatePeriod or CarbonPeriod object. */ public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); } /** * Create a new instance. */ public static function create(...$params): static { return static::createFromArray($params); } /** * Create a new instance from an array of parameters. */ public static function createFromArray(array $params): static { return new static(...$params); } /** * Create CarbonPeriod from ISO 8601 string. */ public static function createFromIso(string $iso, ?int $options = null): static { $params = static::parseIso8601($iso); $instance = static::createFromArray($params); $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options; $instance->handleChangedParameters(); return $instance; } public static function createFromISO8601String(string $iso, ?int $options = null): static { return self::createFromIso($iso, $options); } /** * Return whether the given interval contains non-zero value of any time unit. */ protected static function intervalHasTime(DateInterval $interval): bool { return $interval->h || $interval->i || $interval->s || $interval->f; } /** * Return whether given variable is an ISO 8601 specification. * * Note: Check is very basic, as actual validation will be done later when parsing. * We just want to ensure that variable is not any other type of valid parameter. */ protected static function isIso8601(mixed $var): bool { if (!\is_string($var)) { return false; } // Match slash but not within a timezone name. $part = '[a-z]+(?:[_-][a-z]+)*'; preg_match("#\b$part/$part\b|(/)#i", $var, $match); return isset($match[1]); } /** * Parse given ISO 8601 string into an array of arguments. * * @SuppressWarnings(ElseExpression) */ protected static function parseIso8601(string $iso): array { $result = []; $interval = null; $start = null; $end = null; $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = self::makeInterval($part)) { $interval = $part; } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); } $result[] = $parsed; } return $result; } /** * Add missing parts of the target date from the source date. */ protected static function addMissingParts(string $source, string $target): string { $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); return $count ? $result : $target; } private static function makeInterval(mixed $input): ?CarbonInterval { try { return CarbonInterval::make($input); } catch (Throwable) { return null; } } private static function makeTimezone(mixed $input): ?CarbonTimeZone { if (!\is_string($input)) { return null; } try { return CarbonTimeZone::create($input); } catch (Throwable) { return null; } } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonPeriod::macro('middle', function () { * return $this->getStartDate()->average($this->getEndDate()); * }); * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonPeriod::mixin(new class { * public function addDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->addDays($count) * )->setEndDate( * $this->getEndDate()->addDays($count) * ); * }; * } * public function subDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->subDays($count) * )->setEndDate( * $this->getEndDate()->subDays($count) * ); * }; * } * }); * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); * ``` * * @throws ReflectionException */ public static function mixin(object|string $mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Provide static proxy for instance aliases. */ public static function __callStatic(string $method, array $parameters): mixed { $date = new static(); if (static::hasMacro($method)) { return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters)); } return $date->$method(...$parameters); } /** * CarbonPeriod constructor. * * @SuppressWarnings(ElseExpression) * * @throws InvalidArgumentException */ public function __construct(...$arguments) { $raw = null; if (isset($arguments['raw'])) { $raw = $arguments['raw']; $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false; if (isset($arguments['dateClass'])) { $this->dateClass = $arguments['dateClass']; } $arguments = $raw; } // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. $argumentsCount = \count($arguments); if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { array_splice($arguments, 0, 1, static::parseIso8601($iso)); } if ($argumentsCount === 1) { if ($arguments[0] instanceof self) { $arguments = [ $arguments[0]->getStartDate(), $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(), $arguments[0]->getDateInterval(), $arguments[0]->getOptions(), ]; } elseif ($arguments[0] instanceof DatePeriod) { $arguments = [ $arguments[0]->start, $arguments[0]->end ?: ($arguments[0]->recurrences - 1), $arguments[0]->interval, $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, ]; } } if (is_a($this->dateClass, DateTimeImmutable::class, true)) { $this->options = static::IMMUTABLE; } $optionsSet = false; $originalArguments = []; $sortedArguments = []; foreach ($arguments as $argument) { $parsedDate = null; if ($argument instanceof DateTimeZone) { $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments); } elseif (!isset($sortedArguments['interval']) && ( (\is_string($argument) && preg_match( '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument, )) || $argument instanceof DateInterval || $argument instanceof Closure || $argument instanceof Unit ) && $parsedInterval = self::makeInterval($argument) ) { $sortedArguments['interval'] = $parsedInterval; } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) { $sortedArguments['start'] = $parsedDate; $originalArguments['start'] = $argument; } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { $sortedArguments['end'] = $parsedDate; $originalArguments['end'] = $argument; } elseif (!isset($sortedArguments['recurrences']) && !isset($sortedArguments['end']) && (\is_int($argument) || \is_float($argument)) && $argument >= 0 ) { $sortedArguments['recurrences'] = $argument; } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { $optionsSet = true; $sortedArguments['options'] = (((int) $this->options) | ((int) $argument)); } elseif ($parsedTimezone = self::makeTimezone($argument)) { $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($raw === null && isset($sortedArguments['start'])) { $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1); if (\is_float($end)) { $end = $end === INF ? PHP_INT_MAX : (int) round($end); } $raw = [ $sortedArguments['start'], $sortedArguments['interval'] ?? CarbonInterval::day(), $end, ]; } $this->setFromAssociativeArray($sortedArguments); if ($this->startDate === null) { $dateClass = $this->dateClass; $this->setStartDate($dateClass::now()); } if ($this->dateInterval === null) { $this->setDateInterval(CarbonInterval::day()); $this->isDefaultInterval = true; } if ($this->options === null) { $this->setOptions(0); } parent::__construct( $this->startDate, $this->dateInterval, $this->endDate ?? max(1, min(2147483639, $this->recurrences ?? 1)), $this->options, ); $this->constructed = true; } /** * Get a copy of the instance. */ public function copy(): static { return clone $this; } /** * Prepare the instance to be set (self if mutable to be mutated, * copy if immutable to generate a new instance). */ protected function copyIfImmutable(): static { return $this; } /** * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. */ protected function getGetter(string $name): ?callable { return match (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) { 'start', 'start_date' => [$this, 'getStartDate'], 'end', 'end_date' => [$this, 'getEndDate'], 'interval', 'date_interval' => [$this, 'getDateInterval'], 'recurrences' => [$this, 'getRecurrences'], 'include_start_date' => [$this, 'isStartIncluded'], 'include_end_date' => [$this, 'isEndIncluded'], 'current' => [$this, 'current'], 'locale' => [$this, 'locale'], 'tzname', 'tz_name' => fn () => match (true) { $this->timezoneSetting === null => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, $this->timezoneSetting instanceof DateTimeZone => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, default => null, }; } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function get(string $name) { $getter = $this->getGetter($name); if ($getter) { return $getter(); } throw new UnknownGetterException($name); } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function __get(string $name) { return $this->get($name); } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset(string $name): bool { return $this->getGetter($name) !== null; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Set the iteration item class. * * @param string $dateClass * * @return static */ public function setDateClass(string $dateClass) { if (!is_a($dateClass, CarbonInterface::class, true)) { throw new NotACarbonClassException($dateClass); } $self = $this->copyIfImmutable(); $self->dateClass = $dateClass; if (is_a($dateClass, Carbon::class, true)) { $self->options = $self->options & ~static::IMMUTABLE; } elseif (is_a($dateClass, CarbonImmutable::class, true)) { $self->options = $self->options | static::IMMUTABLE; } return $self; } /** * Returns iteration item date class. * * @return string */ public function getDateClass(): string { return $this->dateClass; } /** * Change the period date interval. * * @param DateInterval|Unit|string|int $interval * @param Unit|string $unit the unit of $interval if it's a number * * @throws InvalidIntervalException * * @return static */ public function setDateInterval(mixed $interval, Unit|string|null $unit = null): static { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->name; } if (!$interval = CarbonInterval::make($interval, $unit)) { throw new InvalidIntervalException('Invalid interval.'); } if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) { throw new InvalidIntervalException('Empty interval is not accepted.'); } $self = $this->copyIfImmutable(); $self->dateInterval = $interval; $self->isDefaultInterval = false; $self->handleChangedParameters(); return $self; } /** * Reset the date interval to the default value. * * Difference with simply setting interval to 1-day is that P1D will not appear when calling toIso8601String() * and also next adding to the interval won't include the default 1-day. */ public function resetDateInterval(): static { $self = $this->copyIfImmutable(); $self->setDateInterval(CarbonInterval::day()); $self->isDefaultInterval = true; return $self; } /** * Invert the period date interval. */ public function invertDateInterval(): static { return $this->setDateInterval($this->dateInterval->invert()); } /** * Set start and end date. * * @param DateTime|DateTimeInterface|string $start * @param DateTime|DateTimeInterface|string|null $end * * @return static */ public function setDates(mixed $start, mixed $end): static { return $this->setStartDate($start)->setEndDate($end); } /** * Change the period options. * * @param int|null $options * * @return static */ public function setOptions(?int $options): static { $self = $this->copyIfImmutable(); $self->options = $options ?? 0; $self->handleChangedParameters(); return $self; } /** * Get the period options. */ public function getOptions(): int { return $this->options ?? 0; } /** * Toggle given options on or off. * * @param int $options * @param bool|null $state * * @throws InvalidArgumentException * * @return static */ public function toggleOptions(int $options, ?bool $state = null): static { $self = $this->copyIfImmutable(); if ($state === null) { $state = ($this->options & $options) !== $options; } return $self->setOptions( $state ? $this->options | $options : $this->options & ~$options, ); } /** * Toggle EXCLUDE_START_DATE option. */ public function excludeStartDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_START_DATE, $state); } /** * Toggle EXCLUDE_END_DATE option. */ public function excludeEndDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_END_DATE, $state); } /** * Get the underlying date interval. */ public function getDateInterval(): CarbonInterval { return $this->dateInterval->copy(); } /** * Get start date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getStartDate(?string $rounding = null): CarbonInterface { $date = $this->startDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get end date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getEndDate(?string $rounding = null): ?CarbonInterface { if (!$this->endDate) { return null; } $date = $this->endDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get number of recurrences. */ #[ReturnTypeWillChange] public function getRecurrences(): int|float|null { return $this->carbonRecurrences; } /** * Returns true if the start date should be excluded. */ public function isStartExcluded(): bool { return ($this->options & static::EXCLUDE_START_DATE) !== 0; } /** * Returns true if the end date should be excluded. */ public function isEndExcluded(): bool { return ($this->options & static::EXCLUDE_END_DATE) !== 0; } /** * Returns true if the start date should be included. */ public function isStartIncluded(): bool { return !$this->isStartExcluded(); } /** * Returns true if the end date should be included. */ public function isEndIncluded(): bool { return !$this->isEndExcluded(); } /** * Return the start if it's included by option, else return the start + 1 period interval. */ public function getIncludedStartDate(): CarbonInterface { $start = $this->getStartDate(); if ($this->isStartExcluded()) { return $start->add($this->getDateInterval()); } return $start; } /** * Return the end if it's included by option, else return the end - 1 period interval. * Warning: if the period has no fixed end, this method will iterate the period to calculate it. */ public function getIncludedEndDate(): CarbonInterface { $end = $this->getEndDate(); if (!$end) { return $this->calculateEnd(); } if ($this->isEndExcluded()) { return $end->sub($this->getDateInterval()); } return $end; } /** * Add a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function addFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); $self->filters[] = $tuple; $self->handleChangedParameters(); return $self; } /** * Prepend a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function prependFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); array_unshift($self->filters, $tuple); $self->handleChangedParameters(); return $self; } /** * Remove a filter by instance or name. */ public function removeFilter(callable|string $filter): static { $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; $self->filters = array_values(array_filter( $this->filters, static fn ($tuple) => $tuple[$key] !== $filter, )); $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Return whether given instance or name is in the filter stack. */ public function hasFilter(callable|string $filter): bool { $key = \is_callable($filter) ? 0 : 1; foreach ($this->filters as $tuple) { if ($tuple[$key] === $filter) { return true; } } return false; } /** * Get filters stack. */ public function getFilters(): array { return $this->filters; } /** * Set filters stack. */ public function setFilters(array $filters): static { $self = $this->copyIfImmutable(); $self->filters = $filters; $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Reset filters stack. */ public function resetFilters(): static { $self = $this->copyIfImmutable(); $self->filters = []; if ($self->endDate !== null) { $self->filters[] = [static::END_DATE_FILTER, null]; } if ($self->carbonRecurrences !== null) { $self->filters[] = [static::RECURRENCES_FILTER, null]; } $self->handleChangedParameters(); return $self; } /** * Add a recurrences filter (set maximum number of recurrences). * * @throws InvalidArgumentException */ public function setRecurrences(int|float|null $recurrences): static { if ($recurrences === null) { return $this->removeFilter(static::RECURRENCES_FILTER); } if ($recurrences < 0) { throw new InvalidPeriodParameterException('Invalid number of recurrences.'); } /** @var self $self */ $self = $this->copyIfImmutable(); $self->carbonRecurrences = $recurrences === INF ? INF : (int) $recurrences; if (!$self->hasFilter(static::RECURRENCES_FILTER)) { return $self->addFilter(static::RECURRENCES_FILTER); } $self->handleChangedParameters(); return $self; } /** * Change the period start date. * * @param DateTime|DateTimeInterface|string $date * @param bool|null $inclusive * * @throws InvalidPeriodDateException * * @return static */ public function setStartDate(mixed $date, ?bool $inclusive = null): static { if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date, $this->timezone))) { throw new InvalidPeriodDateException('Invalid start date.'); } $self = $this->copyIfImmutable(); $self->startDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); } return $self; } /** * Change the period end date. * * @param DateTime|DateTimeInterface|string|null $date * @param bool|null $inclusive * * @throws \InvalidArgumentException * * @return static */ public function setEndDate(mixed $date, ?bool $inclusive = null): static { if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date, $this->timezone)) { throw new InvalidPeriodDateException('Invalid end date.'); } if (!$date) { return $this->removeFilter(static::END_DATE_FILTER); } $self = $this->copyIfImmutable(); $self->endDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); } if (!$self->hasFilter(static::END_DATE_FILTER)) { return $self->addFilter(static::END_DATE_FILTER); } $self->handleChangedParameters(); return $self; } /** * Check if the current position is valid. */ public function valid(): bool { return $this->validateCurrentDate() === true; } /** * Return the current key. */ public function key(): ?int { return $this->valid() ? $this->key : null; } /** * Return the current date. */ public function current(): ?CarbonInterface { return $this->valid() ? $this->prepareForReturn($this->carbonCurrent) : null; } /** * Move forward to the next date. * * @throws RuntimeException */ public function next(): void { if ($this->carbonCurrent === null) { $this->rewind(); } if ($this->validationResult !== static::END_ITERATION) { $this->key++; $this->incrementCurrentDateUntilValid(); } } /** * Rewind to the start date. * * Iterating over a date in the UTC timezone avoids bug during backward DST change. * * @see https://bugs.php.net/bug.php?id=72255 * @see https://bugs.php.net/bug.php?id=74274 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time * * @throws RuntimeException */ public function rewind(): void { $this->key = 0; $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate); $settings = $this->getSettings(); if ($this->hasLocalTranslator()) { $settings['locale'] = $this->getTranslatorLocale(); } $this->carbonCurrent->settings($settings); $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null; if ($this->timezone) { $this->carbonCurrent = $this->carbonCurrent->utc(); } $this->validationResult = null; if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { $this->incrementCurrentDateUntilValid(); } } /** * Skip iterations and returns iteration state (false if ended, true if still valid). * * @param int $count steps number to skip (1 by default) * * @return bool */ public function skip(int $count = 1): bool { for ($i = $count; $this->valid() && $i > 0; $i--) { $this->next(); } return $this->valid(); } /** * Format the date period as ISO 8601. */ public function toIso8601String(): string { $parts = []; if ($this->carbonRecurrences !== null) { $parts[] = 'R'.$this->carbonRecurrences; } $parts[] = $this->startDate->toIso8601String(); if (!$this->isDefaultInterval) { $parts[] = $this->dateInterval->spec(); } if ($this->endDate !== null) { $parts[] = $this->endDate->toIso8601String(); } return implode('/', $parts); } /** * Convert the date period into a string. */ public function toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if ($format instanceof Closure) { return $format($this); } $translator = ([$this->dateClass, 'getTranslator'])(); $parts = []; $format = $format ?? ( !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) ? 'Y-m-d H:i:s' : 'Y-m-d' ); if ($this->carbonRecurrences !== null) { $parts[] = $this->translate('period_recurrences', [], $this->carbonRecurrences, $translator); } $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([ 'join' => true, ])], null, $translator); $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator); if ($this->endDate !== null) { $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator); } $result = implode(' ', $parts); return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1); } /** * Format the date period as ISO 8601. */ public function spec(): string { return $this->toIso8601String(); } /** * Cast the current instance into the given class. * * @param string $className The $className::instance() method will be called to cast the current object. * * @return DatePeriod|object */ public function cast(string $className): object { if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( $this->rawDate($this->getStartDate()), $this->getDateInterval(), $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0, ); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Return native DatePeriod PHP object matching the current instance. * * @example * ``` * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod()); * ``` */ public function toDatePeriod(): DatePeriod { return $this->cast(DatePeriod::class); } /** * Return `true` if the period has no custom filter and is guaranteed to be endless. * * Note that we can't check if a period is endless as soon as it has custom filters * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in * a way we can't predict without actually iterating the period. */ public function isUnfilteredAndEndLess(): bool { foreach ($this->filters as $filter) { switch ($filter) { case [static::RECURRENCES_FILTER, null]: if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) { return false; } break; case [static::END_DATE_FILTER, null]: if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { return false; } break; default: return false; } } return true; } /** * Convert the date period into an array without changing current iteration state. * * @return CarbonInterface[] */ public function toArray(): array { if ($this->isUnfilteredAndEndLess()) { throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); } $state = [ $this->key, $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null, $this->validationResult, ]; $result = iterator_to_array($this); [$this->key, $this->carbonCurrent, $this->validationResult] = $state; return $result; } /** * Count dates in the date period. */ public function count(): int { return \count($this->toArray()); } /** * Return the first date in the date period. */ public function first(): ?CarbonInterface { if ($this->isUnfilteredAndEndLess()) { foreach ($this as $date) { $this->rewind(); return $date; } return null; } return ($this->toArray() ?: [])[0] ?? null; } /** * Return the last date in the date period. */ public function last(): ?CarbonInterface { $array = $this->toArray(); return $array ? $array[\count($array) - 1] : null; } /** * Convert the date period into a string. */ public function __toString(): string { return $this->toString(); } /** * Add aliases for setters. * * CarbonPeriod::days(3)->hours(5)->invert() * ->sinceNow()->until('2010-01-10') * ->filter(...) * ->count() * * Note: We use magic method to let static and instance aliases with the same names. */ public function __call(string $method, array $parameters): mixed { if (static::hasMacro($method)) { return static::bindMacroContext($this, fn () => $this->callMacro($method, $parameters)); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } $count = \count($parameters); switch ($method) { case 'start': case 'since': if ($count === 0) { return $this->getStartDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setStartDate(...$parameters); case 'sinceNow': return $this->setStartDate(new Carbon(), ...$parameters); case 'end': case 'until': if ($count === 0) { return $this->getEndDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setEndDate(...$parameters); case 'untilNow': return $this->setEndDate(new Carbon(), ...$parameters); case 'dates': case 'between': self::setDefaultParameters($parameters, [ [0, 'start', null], [1, 'end', null], ]); return $this->setDates(...$parameters); case 'recurrences': case 'times': if ($count === 0) { return $this->getRecurrences(); } self::setDefaultParameters($parameters, [ [0, 'recurrences', null], ]); return $this->setRecurrences(...$parameters); case 'options': if ($count === 0) { return $this->getOptions(); } self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->setOptions(...$parameters); case 'toggle': self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->toggleOptions(...$parameters); case 'filter': case 'push': return $this->addFilter(...$parameters); case 'prepend': return $this->prependFilter(...$parameters); case 'filters': if ($count === 0) { return $this->getFilters(); } self::setDefaultParameters($parameters, [ [0, 'filters', []], ]); return $this->setFilters(...$parameters); case 'interval': case 'each': case 'every': case 'step': case 'stepBy': if ($count === 0) { return $this->getDateInterval(); } return $this->setDateInterval(...$parameters); case 'invert': return $this->invertDateInterval(); case 'years': case 'year': case 'months': case 'month': case 'weeks': case 'week': case 'days': case 'dayz': case 'day': case 'hours': case 'hour': case 'minutes': case 'minute': case 'seconds': case 'second': case 'milliseconds': case 'millisecond': case 'microseconds': case 'microsecond': return $this->setDateInterval(( // Override default P1D when instantiating via fluent setters. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] )(...$parameters)); } $dateClass = $this->dateClass; if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { throw new UnknownMethodException($method); } return $this; } /** * Set the instance's timezone from a string or object and apply it to start/end. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->setTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->setTimezone($timezone)); } return $self; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } return $self; } /** * Returns the end is set, else calculated from start and recurrences. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. * * @return CarbonInterface */ public function calculateEnd(?string $rounding = null): CarbonInterface { if ($end = $this->getEndDate($rounding)) { return $end; } if ($this->dateInterval->isEmpty()) { return $this->getStartDate($rounding); } $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); if ($date && $rounding) { $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); } return $date; } private function getEndFromRecurrences(): ?CarbonInterface { if ($this->carbonRecurrences === null) { throw new UnreachableException( "Could not calculate period end without either explicit end or recurrences.\n". "If you're looking for a forever-period, use ->setRecurrences(INF).", ); } if ($this->carbonRecurrences === INF) { $start = $this->getStartDate(); return $start < $start->avoidMutation()->add($this->getDateInterval()) ? CarbonImmutable::endOfTime() : CarbonImmutable::startOfTime(); } if ($this->filters === [[static::RECURRENCES_FILTER, null]]) { return $this->getStartDate()->avoidMutation()->add( $this->getDateInterval()->times( $this->carbonRecurrences - ($this->isStartExcluded() ? 0 : 1), ), ); } return null; } private function iterateUntilEnd(): ?CarbonInterface { $attempts = 0; $date = null; foreach ($this as $date) { if (++$attempts > static::END_MAX_ATTEMPTS) { throw new UnreachableException( 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.', ); } } return $date; } /** * Returns true if the current period overlaps the given one (if 1 parameter passed) * or the period between 2 dates (if 2 parameters passed). * * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd * * @return bool */ public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool { $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; if (!($range instanceof self)) { $range = static::create($range); } [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); return $end > $rangeStart && $rangeEnd > $start; } /** * Execute a given function on each date of the period. * * @example * ``` * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) { * echo $date->diffInDays('2020-12-25')." days before Christmas!\n"; * }); * ``` */ public function forEach(callable $callback): void { foreach ($this as $date) { $callback($date); } } /** * Execute a given function on each date of the period and yield the result of this function. * * @example * ``` * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24'); * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) { * return $date->diffInDays('2020-12-25').' days before Christmas!'; * }))); * ``` */ public function map(callable $callback): Generator { foreach ($this as $date) { yield $callback($date); } } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. * * @see equalTo() */ public function eq(mixed $period): bool { return $this->equalTo($period); } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. */ public function equalTo(mixed $period): bool { if (!($period instanceof self)) { $period = self::make($period); } $end = $this->getEndDate(); return $period !== null && $this->getDateInterval()->eq($period->getDateInterval()) && $this->getStartDate()->eq($period->getStartDate()) && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. * * @see notEqualTo() */ public function ne(mixed $period): bool { return $this->notEqualTo($period); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. */ public function notEqualTo(mixed $period): bool { return !$this->eq($period); } /** * Determines if the start date is before another given date. * (Rather start/end are included by options is ignored.) */ public function startsBefore(mixed $date = null): bool { return $this->getStartDate()->lessThan($this->resolveCarbon($date)); } /** * Determines if the start date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsBeforeOrAt(mixed $date = null): bool { return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is after another given date. * (Rather start/end are included by options is ignored.) */ public function startsAfter(mixed $date = null): bool { return $this->getStartDate()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the start date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAfterOrAt(mixed $date = null): bool { return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAt(mixed $date = null): bool { return $this->getStartDate()->equalTo($this->resolveCarbon($date)); } /** * Determines if the end date is before another given date. * (Rather start/end are included by options is ignored.) */ public function endsBefore(mixed $date = null): bool { return $this->calculateEnd()->lessThan($this->resolveCarbon($date)); } /** * Determines if the end date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsBeforeOrAt(mixed $date = null): bool { return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is after another given date. * (Rather start/end are included by options is ignored.) */ public function endsAfter(mixed $date = null): bool { return $this->calculateEnd()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the end date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAfterOrAt(mixed $date = null): bool { return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAt(mixed $date = null): bool { return $this->calculateEnd()->equalTo($this->resolveCarbon($date)); } /** * Return true if start date is now or later. * (Rather start/end are included by options is ignored.) */ public function isStarted(): bool { return $this->startsBeforeOrAt(); } /** * Return true if end date is now or later. * (Rather start/end are included by options is ignored.) */ public function isEnded(): bool { return $this->endsBeforeOrAt(); } /** * Return true if now is between start date (included) and end date (excluded). * (Rather start/end are included by options is ignored.) */ public function isInProgress(): bool { return $this->isStarted() && !$this->isEnded(); } /** * Round the current instance at the given unit with given precision if specified and the given function. */ public function roundUnit( string $unit, DateInterval|float|int|string|null $precision = 1, callable|string $function = 'round', ): static { $self = $this->copyIfImmutable(); $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); if ($self->endDate) { $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); } /** * Truncate the current instance at the given unit with given precision if specified. */ public function floorUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. */ public function ceilUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function round( DateInterval|float|int|string|null $precision = null, callable|string $function = 'round', ): static { return $this->roundWith( $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(), $function ); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function floor(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified (else period interval is used). */ public function ceil(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'ceil'); } /** * Specify data which should be serialized to JSON. * * @link https://php.net/manual/en/jsonserializable.jsonserialize.php * * @return CarbonInterface[] */ public function jsonSerialize(): array { return $this->toArray(); } /** * Return true if the given date is between start and end. */ public function contains(mixed $date = null): bool { $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : ''); $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : ''); return $this->$startMethod($date) && $this->$endMethod($date); } /** * Return true if the current period follows a given other period (with no overlap). * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31] * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function follows(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval())); } /** * Return true if the given other period follows the current one (with no overlap). * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12] * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function isFollowedBy(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $period->follows($this); } /** * Return true if the given period either follows or is followed by the current one. * * @see follows() * @see isFollowedBy() */ public function isConsecutiveWith(mixed $period, mixed ...$arguments): bool { return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments); } public function __debugInfo(): array { $info = $this->baseDebugInfo(); unset( $info['start'], $info['end'], $info['interval'], $info['include_start_date'], $info['include_end_date'], $info['constructed'], $info["\0*\0constructed"], ); return $info; } public function __unserialize(array $data): void { try { $values = array_combine( array_map( static fn (string $key): string => preg_replace('/^\0\*\0/', '', $key), array_keys($data), ), $data, ); $this->initializeSerialization($values); foreach ($values as $key => $value) { if ($value === null) { continue; } $property = match ($key) { 'tzName' => $this->setTimezone(...), 'options' => $this->setOptions(...), 'recurrences' => $this->setRecurrences(...), 'current' => function (mixed $current): void { if (!($current instanceof CarbonInterface)) { $current = $this->resolveCarbon($current); } $this->carbonCurrent = $current; }, 'start' => 'startDate', 'interval' => $this->setDateInterval(...), 'end' => 'endDate', 'key' => null, 'include_start_date' => function (bool $included): void { $this->excludeStartDate(!$included); }, 'include_end_date' => function (bool $included): void { $this->excludeEndDate(!$included); }, default => $key, }; if ($property === null) { continue; } if (\is_callable($property)) { $property($value); continue; } if ($value instanceof DateTimeInterface && !($value instanceof CarbonInterface)) { $value = ($value instanceof DateTime) ? Carbon::instance($value) : CarbonImmutable::instance($value); } try { $this->$property = $value; } catch (Throwable) { // Must be ignored for backward-compatibility } } if (\array_key_exists('carbonRecurrences', $values)) { $this->carbonRecurrences = $values['carbonRecurrences']; } elseif (((int) ($values['recurrences'] ?? 0)) <= 1 && $this->endDate !== null) { $this->carbonRecurrences = null; } } catch (Throwable $e) { // @codeCoverageIgnoreStart if (!method_exists(parent::class, '__unserialize')) { throw $e; } parent::__unserialize($data); // @codeCoverageIgnoreEnd } } /** * Update properties after removing built-in filters. */ protected function updateInternalState(): void { if (!$this->hasFilter(static::END_DATE_FILTER)) { $this->endDate = null; } if (!$this->hasFilter(static::RECURRENCES_FILTER)) { $this->carbonRecurrences = null; } } /** * Create a filter tuple from raw parameters. * * Will create an automatic filter callback for one of Carbon's is* methods. */ protected function createFilterTuple(array $parameters): array { $method = array_shift($parameters); if (!$this->isCarbonPredicateMethod($method)) { return [$method, array_shift($parameters)]; } return [static fn ($date) => ([$date, $method])(...$parameters), $method]; } /** * Return whether given callable is a string pointing to one of Carbon's is* methods * and should be automatically converted to a filter callback. */ protected function isCarbonPredicateMethod(callable|string $callable): bool { return \is_string($callable) && str_starts_with($callable, 'is') && (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable)); } /** * Recurrences filter callback (limits number of recurrences). * * @SuppressWarnings(UnusedFormalParameter) */ protected function filterRecurrences(CarbonInterface $current, int $key): bool|callable { if ($key < $this->carbonRecurrences) { return true; } return static::END_ITERATION; } /** * End date filter callback. * * @return bool|static::END_ITERATION */ protected function filterEndDate(CarbonInterface $current): bool|callable { if (!$this->isEndExcluded() && $current == $this->endDate) { return true; } if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) { return true; } return static::END_ITERATION; } /** * End iteration filter callback. * * @return static::END_ITERATION */ protected function endIteration(): callable { return static::END_ITERATION; } /** * Handle change of the parameters. */ protected function handleChangedParameters(): void { if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { $this->dateClass = CarbonImmutable::class; } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { $this->dateClass = Carbon::class; } $this->validationResult = null; } /** * Validate current date and stop iteration when necessary. * * Returns true when current date is valid, false if it is not, or static::END_ITERATION * when iteration should be stopped. * * @return bool|static::END_ITERATION */ protected function validateCurrentDate(): bool|callable { if ($this->carbonCurrent === null) { $this->rewind(); } // Check after the first rewind to avoid repeating the initial validation. return $this->validationResult ?? ($this->validationResult = $this->checkFilters()); } /** * Check whether current value and key pass all the filters. * * @return bool|static::END_ITERATION */ protected function checkFilters(): bool|callable { $current = $this->prepareForReturn($this->carbonCurrent); foreach ($this->filters as $tuple) { $result = \call_user_func($tuple[0], $current->avoidMutation(), $this->key, $this); if ($result === static::END_ITERATION) { return static::END_ITERATION; } if (!$result) { return false; } } return true; } /** * Prepare given date to be returned to the external logic. * * @param CarbonInterface $date * * @return CarbonInterface */ protected function prepareForReturn(CarbonInterface $date) { $date = ([$this->dateClass, 'make'])($date); if ($this->timezone) { return $date->setTimezone($this->timezone); } return $date; } /** * Keep incrementing the current date until a valid date is found or the iteration is ended. * * @throws RuntimeException */ protected function incrementCurrentDateUntilValid(): void { $attempts = 0; do { $this->carbonCurrent = $this->carbonCurrent->add($this->dateInterval); $this->validationResult = null; if (++$attempts > static::NEXT_MAX_ATTEMPTS) { throw new UnreachableException('Could not find next valid date.'); } } while ($this->validateCurrentDate() === false); } /** * Call given macro. */ protected function callMacro(string $name, array $parameters): mixed { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date * * @return \Carbon\CarbonInterface */ protected function resolveCarbon($date = null) { return $this->getStartDate()->nowWithSameTz()->carbonize($date); } /** * Resolve passed arguments or DatePeriod to a CarbonPeriod object. */ protected function resolveCarbonPeriod(mixed $period, mixed ...$arguments): self { if ($period instanceof self) { return $period; } return $period instanceof DatePeriod ? static::instance($period) : static::create($period, ...$arguments); } private function orderCouple($first, $second): array { return $first > $second ? [$second, $first] : [$first, $second]; } private function makeDateTime($value): ?DateTimeInterface { if ($value instanceof DateTimeInterface) { return $value; } if ($value instanceof WeekDay || $value instanceof Month) { $dateClass = $this->dateClass; return new $dateClass($value, $this->timezoneSetting); } if (\is_string($value)) { $value = trim($value); if (!preg_match('/^P[\dT]/', $value) && !preg_match('/^R\d/', $value) && preg_match('/[a-z\d]/i', $value) ) { $dateClass = $this->dateClass; return $dateClass::parse($value, $this->timezoneSetting); } } return null; } private function isInfiniteDate($date): bool { return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); } private function rawDate($date): ?DateTimeInterface { if ($date === false || $date === null) { return null; } if ($date instanceof CarbonInterface) { return $date->isMutable() ? $date->toDateTime() : $date->toDateTimeImmutable(); } if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { return $date; } $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); } private static function setDefaultParameters(array &$parameters, array $defaults): void { foreach ($defaults as [$index, $name, $value]) { if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { $parameters[$index] = $value; } } } private function setFromAssociativeArray(array $parameters): void { if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['end'])) { $this->setEndDate($parameters['end']); } if (isset($parameters['recurrences'])) { $this->setRecurrences($parameters['recurrences']); } if (isset($parameters['interval'])) { $this->setDateInterval($parameters['interval']); } if (isset($parameters['options'])) { $this->setOptions($parameters['options']); } } private function configureTimezone(DateTimeZone $timezone, array $sortedArguments, array $originalArguments): array { $this->setTimezone($timezone); if (\is_string($originalArguments['start'] ?? null)) { $sortedArguments['start'] = $this->makeDateTime($originalArguments['start']); } if (\is_string($originalArguments['end'] ?? null)) { $sortedArguments['end'] = $this->makeDateTime($originalArguments['end']); } return $sortedArguments; } private function initializeSerialization(array $values): void { $serializationBase = [ 'start' => $values['start'] ?? $values['startDate'] ?? null, 'current' => $values['current'] ?? $values['carbonCurrent'] ?? null, 'end' => $values['end'] ?? $values['endDate'] ?? null, 'interval' => $values['interval'] ?? $values['dateInterval'] ?? null, 'recurrences' => max(1, (int) ($values['recurrences'] ?? $values['carbonRecurrences'] ?? 1)), 'include_start_date' => $values['include_start_date'] ?? true, 'include_end_date' => $values['include_end_date'] ?? false, ]; foreach (['start', 'current', 'end'] as $dateProperty) { if ($serializationBase[$dateProperty] instanceof Carbon) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTime(); } elseif ($serializationBase[$dateProperty] instanceof CarbonInterface) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTimeImmutable(); } } if ($serializationBase['interval'] instanceof CarbonInterval) { $serializationBase['interval'] = $serializationBase['interval']->toDateInterval(); } // @codeCoverageIgnoreStart if (method_exists(parent::class, '__unserialize')) { parent::__unserialize($serializationBase); return; } $excludeStart = !($values['include_start_date'] ?? true); $includeEnd = $values['include_end_date'] ?? true; parent::__construct( $serializationBase['start'], $serializationBase['interval'], $serializationBase['end'] ?? $serializationBase['recurrences'], ($excludeStart ? self::EXCLUDE_START_DATE : 0) | ($includeEnd && \defined('DatePeriod::INCLUDE_END_DATE') ? self::INCLUDE_END_DATE : 0), ); // @codeCoverageIgnoreEnd } }
PHP
{ "end_line": 1588, "name": "toArray", "signature": "public function toArray(): array", "start_line": 1571 }
{ "class_name": "CarbonPeriod", "class_signature": "class CarbonPeriod implements Countable, JsonSerializable, UnitValue", "namespace": "Carbon" }
first
Carbon/src/Carbon/CarbonPeriod.php
public function first(): ?CarbonInterface { if ($this->isUnfilteredAndEndLess()) { foreach ($this as $date) { $this->rewind(); return $date; } return null; } return ($this->toArray() ?: [])[0] ?? null; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotACarbonClassException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnreachableException; use Carbon\Traits\DeprecatedPeriodProperties; use Carbon\Traits\IntervalRounding; use Carbon\Traits\LocalFactory; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Throwable; // @codeCoverageIgnoreStart require PHP_VERSION < 8.2 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php' : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php'; // @codeCoverageIgnoreEnd /** * Substitution of DatePeriod with some modifications and many more features. * * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. * @method static static since($date = null, $inclusive = null) Alias for start(). * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. * @method static static until($date = null, $inclusive = null) Alias for end(). * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. * @method static static times($recurrences = null) Alias for recurrences(). * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance. * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. * @method static static push($callback, $name = null) Alias for filter(). * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance. * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. * @method static static year($years = 1) Alias for years(). * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. * @method static static month($months = 1) Alias for months(). * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. * @method static static week($weeks = 1) Alias for weeks(). * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. * @method static static dayz($days = 1) Alias for days(). * @method static static day($days = 1) Alias for days(). * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. * @method static static hour($hours = 1) Alias for hours(). * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. * @method static static minute($minutes = 1) Alias for minutes(). * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. * @method static static second($seconds = 1) Alias for seconds(). * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * * @mixin DeprecatedPeriodProperties * * @SuppressWarnings(TooManyFields) * @SuppressWarnings(CamelCasePropertyName) * @SuppressWarnings(CouplingBetweenObjects) */ class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue { use LocalFactory; use IntervalRounding; use Mixin { Mixin::mixin as baseMixin; } use Options { Options::__debugInfo as baseDebugInfo; } use ToStringFormat; /** * Built-in filter for limit by recurrences. * * @var callable */ public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; /** * Built-in filter for limit to an end. * * @var callable */ public const END_DATE_FILTER = [self::class, 'filterEndDate']; /** * Special value which can be returned by filters to end iteration. Also a filter. * * @var callable */ public const END_ITERATION = [self::class, 'endIteration']; /** * Exclude end date from iteration. * * @var int */ public const EXCLUDE_END_DATE = 8; /** * Yield CarbonImmutable instances. * * @var int */ public const IMMUTABLE = 4; /** * Number of maximum attempts before giving up on finding next valid date. * * @var int */ public const NEXT_MAX_ATTEMPTS = 1000; /** * Number of maximum attempts before giving up on finding end date. * * @var int */ public const END_MAX_ATTEMPTS = 10000; /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = Carbon::class; /** * The registered macros. */ protected static array $macros = []; /** * Date class of iteration items. */ protected string $dateClass = Carbon::class; /** * Underlying date interval instance. Always present, one day by default. */ protected ?CarbonInterval $dateInterval = null; /** * True once __construct is finished. */ protected bool $constructed = false; /** * Whether current date interval was set by default. */ protected bool $isDefaultInterval = false; /** * The filters stack. */ protected array $filters = []; /** * Period start date. Applied on rewind. Always present, now by default. */ protected ?CarbonInterface $startDate = null; /** * Period end date. For inverted interval should be before the start date. Applied via a filter. */ protected ?CarbonInterface $endDate = null; /** * Limit for number of recurrences. Applied via a filter. */ protected int|float|null $carbonRecurrences = null; /** * Iteration options. */ protected ?int $options = null; /** * Index of current date. Always sequential, even if some dates are skipped by filters. * Equal to null only before the first iteration. */ protected int $key = 0; /** * Current date. May temporarily hold unaccepted value when looking for a next valid date. * Equal to null only before the first iteration. */ protected ?CarbonInterface $carbonCurrent = null; /** * Timezone of current date. Taken from the start date. */ protected ?DateTimeZone $timezone = null; /** * The cached validation result for current date. */ protected array|string|bool|null $validationResult = null; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; public function getIterator(): Generator { $this->rewind(); while ($this->valid()) { $key = $this->key(); $value = $this->current(); yield $key => $value; $this->next(); } } /** * Make a CarbonPeriod instance from given variable if possible. */ public static function make(mixed $var): ?static { try { return static::instance($var); } catch (NotAPeriodException) { return static::create($var); } } /** * Create a new instance from a DatePeriod or CarbonPeriod object. */ public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); } /** * Create a new instance. */ public static function create(...$params): static { return static::createFromArray($params); } /** * Create a new instance from an array of parameters. */ public static function createFromArray(array $params): static { return new static(...$params); } /** * Create CarbonPeriod from ISO 8601 string. */ public static function createFromIso(string $iso, ?int $options = null): static { $params = static::parseIso8601($iso); $instance = static::createFromArray($params); $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options; $instance->handleChangedParameters(); return $instance; } public static function createFromISO8601String(string $iso, ?int $options = null): static { return self::createFromIso($iso, $options); } /** * Return whether the given interval contains non-zero value of any time unit. */ protected static function intervalHasTime(DateInterval $interval): bool { return $interval->h || $interval->i || $interval->s || $interval->f; } /** * Return whether given variable is an ISO 8601 specification. * * Note: Check is very basic, as actual validation will be done later when parsing. * We just want to ensure that variable is not any other type of valid parameter. */ protected static function isIso8601(mixed $var): bool { if (!\is_string($var)) { return false; } // Match slash but not within a timezone name. $part = '[a-z]+(?:[_-][a-z]+)*'; preg_match("#\b$part/$part\b|(/)#i", $var, $match); return isset($match[1]); } /** * Parse given ISO 8601 string into an array of arguments. * * @SuppressWarnings(ElseExpression) */ protected static function parseIso8601(string $iso): array { $result = []; $interval = null; $start = null; $end = null; $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = self::makeInterval($part)) { $interval = $part; } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); } $result[] = $parsed; } return $result; } /** * Add missing parts of the target date from the source date. */ protected static function addMissingParts(string $source, string $target): string { $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); return $count ? $result : $target; } private static function makeInterval(mixed $input): ?CarbonInterval { try { return CarbonInterval::make($input); } catch (Throwable) { return null; } } private static function makeTimezone(mixed $input): ?CarbonTimeZone { if (!\is_string($input)) { return null; } try { return CarbonTimeZone::create($input); } catch (Throwable) { return null; } } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonPeriod::macro('middle', function () { * return $this->getStartDate()->average($this->getEndDate()); * }); * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonPeriod::mixin(new class { * public function addDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->addDays($count) * )->setEndDate( * $this->getEndDate()->addDays($count) * ); * }; * } * public function subDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->subDays($count) * )->setEndDate( * $this->getEndDate()->subDays($count) * ); * }; * } * }); * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); * ``` * * @throws ReflectionException */ public static function mixin(object|string $mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Provide static proxy for instance aliases. */ public static function __callStatic(string $method, array $parameters): mixed { $date = new static(); if (static::hasMacro($method)) { return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters)); } return $date->$method(...$parameters); } /** * CarbonPeriod constructor. * * @SuppressWarnings(ElseExpression) * * @throws InvalidArgumentException */ public function __construct(...$arguments) { $raw = null; if (isset($arguments['raw'])) { $raw = $arguments['raw']; $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false; if (isset($arguments['dateClass'])) { $this->dateClass = $arguments['dateClass']; } $arguments = $raw; } // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. $argumentsCount = \count($arguments); if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { array_splice($arguments, 0, 1, static::parseIso8601($iso)); } if ($argumentsCount === 1) { if ($arguments[0] instanceof self) { $arguments = [ $arguments[0]->getStartDate(), $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(), $arguments[0]->getDateInterval(), $arguments[0]->getOptions(), ]; } elseif ($arguments[0] instanceof DatePeriod) { $arguments = [ $arguments[0]->start, $arguments[0]->end ?: ($arguments[0]->recurrences - 1), $arguments[0]->interval, $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, ]; } } if (is_a($this->dateClass, DateTimeImmutable::class, true)) { $this->options = static::IMMUTABLE; } $optionsSet = false; $originalArguments = []; $sortedArguments = []; foreach ($arguments as $argument) { $parsedDate = null; if ($argument instanceof DateTimeZone) { $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments); } elseif (!isset($sortedArguments['interval']) && ( (\is_string($argument) && preg_match( '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument, )) || $argument instanceof DateInterval || $argument instanceof Closure || $argument instanceof Unit ) && $parsedInterval = self::makeInterval($argument) ) { $sortedArguments['interval'] = $parsedInterval; } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) { $sortedArguments['start'] = $parsedDate; $originalArguments['start'] = $argument; } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { $sortedArguments['end'] = $parsedDate; $originalArguments['end'] = $argument; } elseif (!isset($sortedArguments['recurrences']) && !isset($sortedArguments['end']) && (\is_int($argument) || \is_float($argument)) && $argument >= 0 ) { $sortedArguments['recurrences'] = $argument; } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { $optionsSet = true; $sortedArguments['options'] = (((int) $this->options) | ((int) $argument)); } elseif ($parsedTimezone = self::makeTimezone($argument)) { $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($raw === null && isset($sortedArguments['start'])) { $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1); if (\is_float($end)) { $end = $end === INF ? PHP_INT_MAX : (int) round($end); } $raw = [ $sortedArguments['start'], $sortedArguments['interval'] ?? CarbonInterval::day(), $end, ]; } $this->setFromAssociativeArray($sortedArguments); if ($this->startDate === null) { $dateClass = $this->dateClass; $this->setStartDate($dateClass::now()); } if ($this->dateInterval === null) { $this->setDateInterval(CarbonInterval::day()); $this->isDefaultInterval = true; } if ($this->options === null) { $this->setOptions(0); } parent::__construct( $this->startDate, $this->dateInterval, $this->endDate ?? max(1, min(2147483639, $this->recurrences ?? 1)), $this->options, ); $this->constructed = true; } /** * Get a copy of the instance. */ public function copy(): static { return clone $this; } /** * Prepare the instance to be set (self if mutable to be mutated, * copy if immutable to generate a new instance). */ protected function copyIfImmutable(): static { return $this; } /** * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. */ protected function getGetter(string $name): ?callable { return match (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) { 'start', 'start_date' => [$this, 'getStartDate'], 'end', 'end_date' => [$this, 'getEndDate'], 'interval', 'date_interval' => [$this, 'getDateInterval'], 'recurrences' => [$this, 'getRecurrences'], 'include_start_date' => [$this, 'isStartIncluded'], 'include_end_date' => [$this, 'isEndIncluded'], 'current' => [$this, 'current'], 'locale' => [$this, 'locale'], 'tzname', 'tz_name' => fn () => match (true) { $this->timezoneSetting === null => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, $this->timezoneSetting instanceof DateTimeZone => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, default => null, }; } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function get(string $name) { $getter = $this->getGetter($name); if ($getter) { return $getter(); } throw new UnknownGetterException($name); } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function __get(string $name) { return $this->get($name); } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset(string $name): bool { return $this->getGetter($name) !== null; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Set the iteration item class. * * @param string $dateClass * * @return static */ public function setDateClass(string $dateClass) { if (!is_a($dateClass, CarbonInterface::class, true)) { throw new NotACarbonClassException($dateClass); } $self = $this->copyIfImmutable(); $self->dateClass = $dateClass; if (is_a($dateClass, Carbon::class, true)) { $self->options = $self->options & ~static::IMMUTABLE; } elseif (is_a($dateClass, CarbonImmutable::class, true)) { $self->options = $self->options | static::IMMUTABLE; } return $self; } /** * Returns iteration item date class. * * @return string */ public function getDateClass(): string { return $this->dateClass; } /** * Change the period date interval. * * @param DateInterval|Unit|string|int $interval * @param Unit|string $unit the unit of $interval if it's a number * * @throws InvalidIntervalException * * @return static */ public function setDateInterval(mixed $interval, Unit|string|null $unit = null): static { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->name; } if (!$interval = CarbonInterval::make($interval, $unit)) { throw new InvalidIntervalException('Invalid interval.'); } if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) { throw new InvalidIntervalException('Empty interval is not accepted.'); } $self = $this->copyIfImmutable(); $self->dateInterval = $interval; $self->isDefaultInterval = false; $self->handleChangedParameters(); return $self; } /** * Reset the date interval to the default value. * * Difference with simply setting interval to 1-day is that P1D will not appear when calling toIso8601String() * and also next adding to the interval won't include the default 1-day. */ public function resetDateInterval(): static { $self = $this->copyIfImmutable(); $self->setDateInterval(CarbonInterval::day()); $self->isDefaultInterval = true; return $self; } /** * Invert the period date interval. */ public function invertDateInterval(): static { return $this->setDateInterval($this->dateInterval->invert()); } /** * Set start and end date. * * @param DateTime|DateTimeInterface|string $start * @param DateTime|DateTimeInterface|string|null $end * * @return static */ public function setDates(mixed $start, mixed $end): static { return $this->setStartDate($start)->setEndDate($end); } /** * Change the period options. * * @param int|null $options * * @return static */ public function setOptions(?int $options): static { $self = $this->copyIfImmutable(); $self->options = $options ?? 0; $self->handleChangedParameters(); return $self; } /** * Get the period options. */ public function getOptions(): int { return $this->options ?? 0; } /** * Toggle given options on or off. * * @param int $options * @param bool|null $state * * @throws InvalidArgumentException * * @return static */ public function toggleOptions(int $options, ?bool $state = null): static { $self = $this->copyIfImmutable(); if ($state === null) { $state = ($this->options & $options) !== $options; } return $self->setOptions( $state ? $this->options | $options : $this->options & ~$options, ); } /** * Toggle EXCLUDE_START_DATE option. */ public function excludeStartDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_START_DATE, $state); } /** * Toggle EXCLUDE_END_DATE option. */ public function excludeEndDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_END_DATE, $state); } /** * Get the underlying date interval. */ public function getDateInterval(): CarbonInterval { return $this->dateInterval->copy(); } /** * Get start date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getStartDate(?string $rounding = null): CarbonInterface { $date = $this->startDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get end date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getEndDate(?string $rounding = null): ?CarbonInterface { if (!$this->endDate) { return null; } $date = $this->endDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get number of recurrences. */ #[ReturnTypeWillChange] public function getRecurrences(): int|float|null { return $this->carbonRecurrences; } /** * Returns true if the start date should be excluded. */ public function isStartExcluded(): bool { return ($this->options & static::EXCLUDE_START_DATE) !== 0; } /** * Returns true if the end date should be excluded. */ public function isEndExcluded(): bool { return ($this->options & static::EXCLUDE_END_DATE) !== 0; } /** * Returns true if the start date should be included. */ public function isStartIncluded(): bool { return !$this->isStartExcluded(); } /** * Returns true if the end date should be included. */ public function isEndIncluded(): bool { return !$this->isEndExcluded(); } /** * Return the start if it's included by option, else return the start + 1 period interval. */ public function getIncludedStartDate(): CarbonInterface { $start = $this->getStartDate(); if ($this->isStartExcluded()) { return $start->add($this->getDateInterval()); } return $start; } /** * Return the end if it's included by option, else return the end - 1 period interval. * Warning: if the period has no fixed end, this method will iterate the period to calculate it. */ public function getIncludedEndDate(): CarbonInterface { $end = $this->getEndDate(); if (!$end) { return $this->calculateEnd(); } if ($this->isEndExcluded()) { return $end->sub($this->getDateInterval()); } return $end; } /** * Add a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function addFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); $self->filters[] = $tuple; $self->handleChangedParameters(); return $self; } /** * Prepend a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function prependFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); array_unshift($self->filters, $tuple); $self->handleChangedParameters(); return $self; } /** * Remove a filter by instance or name. */ public function removeFilter(callable|string $filter): static { $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; $self->filters = array_values(array_filter( $this->filters, static fn ($tuple) => $tuple[$key] !== $filter, )); $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Return whether given instance or name is in the filter stack. */ public function hasFilter(callable|string $filter): bool { $key = \is_callable($filter) ? 0 : 1; foreach ($this->filters as $tuple) { if ($tuple[$key] === $filter) { return true; } } return false; } /** * Get filters stack. */ public function getFilters(): array { return $this->filters; } /** * Set filters stack. */ public function setFilters(array $filters): static { $self = $this->copyIfImmutable(); $self->filters = $filters; $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Reset filters stack. */ public function resetFilters(): static { $self = $this->copyIfImmutable(); $self->filters = []; if ($self->endDate !== null) { $self->filters[] = [static::END_DATE_FILTER, null]; } if ($self->carbonRecurrences !== null) { $self->filters[] = [static::RECURRENCES_FILTER, null]; } $self->handleChangedParameters(); return $self; } /** * Add a recurrences filter (set maximum number of recurrences). * * @throws InvalidArgumentException */ public function setRecurrences(int|float|null $recurrences): static { if ($recurrences === null) { return $this->removeFilter(static::RECURRENCES_FILTER); } if ($recurrences < 0) { throw new InvalidPeriodParameterException('Invalid number of recurrences.'); } /** @var self $self */ $self = $this->copyIfImmutable(); $self->carbonRecurrences = $recurrences === INF ? INF : (int) $recurrences; if (!$self->hasFilter(static::RECURRENCES_FILTER)) { return $self->addFilter(static::RECURRENCES_FILTER); } $self->handleChangedParameters(); return $self; } /** * Change the period start date. * * @param DateTime|DateTimeInterface|string $date * @param bool|null $inclusive * * @throws InvalidPeriodDateException * * @return static */ public function setStartDate(mixed $date, ?bool $inclusive = null): static { if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date, $this->timezone))) { throw new InvalidPeriodDateException('Invalid start date.'); } $self = $this->copyIfImmutable(); $self->startDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); } return $self; } /** * Change the period end date. * * @param DateTime|DateTimeInterface|string|null $date * @param bool|null $inclusive * * @throws \InvalidArgumentException * * @return static */ public function setEndDate(mixed $date, ?bool $inclusive = null): static { if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date, $this->timezone)) { throw new InvalidPeriodDateException('Invalid end date.'); } if (!$date) { return $this->removeFilter(static::END_DATE_FILTER); } $self = $this->copyIfImmutable(); $self->endDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); } if (!$self->hasFilter(static::END_DATE_FILTER)) { return $self->addFilter(static::END_DATE_FILTER); } $self->handleChangedParameters(); return $self; } /** * Check if the current position is valid. */ public function valid(): bool { return $this->validateCurrentDate() === true; } /** * Return the current key. */ public function key(): ?int { return $this->valid() ? $this->key : null; } /** * Return the current date. */ public function current(): ?CarbonInterface { return $this->valid() ? $this->prepareForReturn($this->carbonCurrent) : null; } /** * Move forward to the next date. * * @throws RuntimeException */ public function next(): void { if ($this->carbonCurrent === null) { $this->rewind(); } if ($this->validationResult !== static::END_ITERATION) { $this->key++; $this->incrementCurrentDateUntilValid(); } } /** * Rewind to the start date. * * Iterating over a date in the UTC timezone avoids bug during backward DST change. * * @see https://bugs.php.net/bug.php?id=72255 * @see https://bugs.php.net/bug.php?id=74274 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time * * @throws RuntimeException */ public function rewind(): void { $this->key = 0; $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate); $settings = $this->getSettings(); if ($this->hasLocalTranslator()) { $settings['locale'] = $this->getTranslatorLocale(); } $this->carbonCurrent->settings($settings); $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null; if ($this->timezone) { $this->carbonCurrent = $this->carbonCurrent->utc(); } $this->validationResult = null; if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { $this->incrementCurrentDateUntilValid(); } } /** * Skip iterations and returns iteration state (false if ended, true if still valid). * * @param int $count steps number to skip (1 by default) * * @return bool */ public function skip(int $count = 1): bool { for ($i = $count; $this->valid() && $i > 0; $i--) { $this->next(); } return $this->valid(); } /** * Format the date period as ISO 8601. */ public function toIso8601String(): string { $parts = []; if ($this->carbonRecurrences !== null) { $parts[] = 'R'.$this->carbonRecurrences; } $parts[] = $this->startDate->toIso8601String(); if (!$this->isDefaultInterval) { $parts[] = $this->dateInterval->spec(); } if ($this->endDate !== null) { $parts[] = $this->endDate->toIso8601String(); } return implode('/', $parts); } /** * Convert the date period into a string. */ public function toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if ($format instanceof Closure) { return $format($this); } $translator = ([$this->dateClass, 'getTranslator'])(); $parts = []; $format = $format ?? ( !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) ? 'Y-m-d H:i:s' : 'Y-m-d' ); if ($this->carbonRecurrences !== null) { $parts[] = $this->translate('period_recurrences', [], $this->carbonRecurrences, $translator); } $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([ 'join' => true, ])], null, $translator); $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator); if ($this->endDate !== null) { $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator); } $result = implode(' ', $parts); return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1); } /** * Format the date period as ISO 8601. */ public function spec(): string { return $this->toIso8601String(); } /** * Cast the current instance into the given class. * * @param string $className The $className::instance() method will be called to cast the current object. * * @return DatePeriod|object */ public function cast(string $className): object { if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( $this->rawDate($this->getStartDate()), $this->getDateInterval(), $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0, ); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Return native DatePeriod PHP object matching the current instance. * * @example * ``` * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod()); * ``` */ public function toDatePeriod(): DatePeriod { return $this->cast(DatePeriod::class); } /** * Return `true` if the period has no custom filter and is guaranteed to be endless. * * Note that we can't check if a period is endless as soon as it has custom filters * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in * a way we can't predict without actually iterating the period. */ public function isUnfilteredAndEndLess(): bool { foreach ($this->filters as $filter) { switch ($filter) { case [static::RECURRENCES_FILTER, null]: if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) { return false; } break; case [static::END_DATE_FILTER, null]: if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { return false; } break; default: return false; } } return true; } /** * Convert the date period into an array without changing current iteration state. * * @return CarbonInterface[] */ public function toArray(): array { if ($this->isUnfilteredAndEndLess()) { throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); } $state = [ $this->key, $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null, $this->validationResult, ]; $result = iterator_to_array($this); [$this->key, $this->carbonCurrent, $this->validationResult] = $state; return $result; } /** * Count dates in the date period. */ public function count(): int { return \count($this->toArray()); } /** * Return the first date in the date period. */ public function first(): ?CarbonInterface { if ($this->isUnfilteredAndEndLess()) { foreach ($this as $date) { $this->rewind(); return $date; } return null; } return ($this->toArray() ?: [])[0] ?? null; } /** * Return the last date in the date period. */ public function last(): ?CarbonInterface { $array = $this->toArray(); return $array ? $array[\count($array) - 1] : null; } /** * Convert the date period into a string. */ public function __toString(): string { return $this->toString(); } /** * Add aliases for setters. * * CarbonPeriod::days(3)->hours(5)->invert() * ->sinceNow()->until('2010-01-10') * ->filter(...) * ->count() * * Note: We use magic method to let static and instance aliases with the same names. */ public function __call(string $method, array $parameters): mixed { if (static::hasMacro($method)) { return static::bindMacroContext($this, fn () => $this->callMacro($method, $parameters)); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } $count = \count($parameters); switch ($method) { case 'start': case 'since': if ($count === 0) { return $this->getStartDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setStartDate(...$parameters); case 'sinceNow': return $this->setStartDate(new Carbon(), ...$parameters); case 'end': case 'until': if ($count === 0) { return $this->getEndDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setEndDate(...$parameters); case 'untilNow': return $this->setEndDate(new Carbon(), ...$parameters); case 'dates': case 'between': self::setDefaultParameters($parameters, [ [0, 'start', null], [1, 'end', null], ]); return $this->setDates(...$parameters); case 'recurrences': case 'times': if ($count === 0) { return $this->getRecurrences(); } self::setDefaultParameters($parameters, [ [0, 'recurrences', null], ]); return $this->setRecurrences(...$parameters); case 'options': if ($count === 0) { return $this->getOptions(); } self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->setOptions(...$parameters); case 'toggle': self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->toggleOptions(...$parameters); case 'filter': case 'push': return $this->addFilter(...$parameters); case 'prepend': return $this->prependFilter(...$parameters); case 'filters': if ($count === 0) { return $this->getFilters(); } self::setDefaultParameters($parameters, [ [0, 'filters', []], ]); return $this->setFilters(...$parameters); case 'interval': case 'each': case 'every': case 'step': case 'stepBy': if ($count === 0) { return $this->getDateInterval(); } return $this->setDateInterval(...$parameters); case 'invert': return $this->invertDateInterval(); case 'years': case 'year': case 'months': case 'month': case 'weeks': case 'week': case 'days': case 'dayz': case 'day': case 'hours': case 'hour': case 'minutes': case 'minute': case 'seconds': case 'second': case 'milliseconds': case 'millisecond': case 'microseconds': case 'microsecond': return $this->setDateInterval(( // Override default P1D when instantiating via fluent setters. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] )(...$parameters)); } $dateClass = $this->dateClass; if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { throw new UnknownMethodException($method); } return $this; } /** * Set the instance's timezone from a string or object and apply it to start/end. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->setTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->setTimezone($timezone)); } return $self; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } return $self; } /** * Returns the end is set, else calculated from start and recurrences. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. * * @return CarbonInterface */ public function calculateEnd(?string $rounding = null): CarbonInterface { if ($end = $this->getEndDate($rounding)) { return $end; } if ($this->dateInterval->isEmpty()) { return $this->getStartDate($rounding); } $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); if ($date && $rounding) { $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); } return $date; } private function getEndFromRecurrences(): ?CarbonInterface { if ($this->carbonRecurrences === null) { throw new UnreachableException( "Could not calculate period end without either explicit end or recurrences.\n". "If you're looking for a forever-period, use ->setRecurrences(INF).", ); } if ($this->carbonRecurrences === INF) { $start = $this->getStartDate(); return $start < $start->avoidMutation()->add($this->getDateInterval()) ? CarbonImmutable::endOfTime() : CarbonImmutable::startOfTime(); } if ($this->filters === [[static::RECURRENCES_FILTER, null]]) { return $this->getStartDate()->avoidMutation()->add( $this->getDateInterval()->times( $this->carbonRecurrences - ($this->isStartExcluded() ? 0 : 1), ), ); } return null; } private function iterateUntilEnd(): ?CarbonInterface { $attempts = 0; $date = null; foreach ($this as $date) { if (++$attempts > static::END_MAX_ATTEMPTS) { throw new UnreachableException( 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.', ); } } return $date; } /** * Returns true if the current period overlaps the given one (if 1 parameter passed) * or the period between 2 dates (if 2 parameters passed). * * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd * * @return bool */ public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool { $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; if (!($range instanceof self)) { $range = static::create($range); } [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); return $end > $rangeStart && $rangeEnd > $start; } /** * Execute a given function on each date of the period. * * @example * ``` * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) { * echo $date->diffInDays('2020-12-25')." days before Christmas!\n"; * }); * ``` */ public function forEach(callable $callback): void { foreach ($this as $date) { $callback($date); } } /** * Execute a given function on each date of the period and yield the result of this function. * * @example * ``` * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24'); * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) { * return $date->diffInDays('2020-12-25').' days before Christmas!'; * }))); * ``` */ public function map(callable $callback): Generator { foreach ($this as $date) { yield $callback($date); } } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. * * @see equalTo() */ public function eq(mixed $period): bool { return $this->equalTo($period); } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. */ public function equalTo(mixed $period): bool { if (!($period instanceof self)) { $period = self::make($period); } $end = $this->getEndDate(); return $period !== null && $this->getDateInterval()->eq($period->getDateInterval()) && $this->getStartDate()->eq($period->getStartDate()) && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. * * @see notEqualTo() */ public function ne(mixed $period): bool { return $this->notEqualTo($period); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. */ public function notEqualTo(mixed $period): bool { return !$this->eq($period); } /** * Determines if the start date is before another given date. * (Rather start/end are included by options is ignored.) */ public function startsBefore(mixed $date = null): bool { return $this->getStartDate()->lessThan($this->resolveCarbon($date)); } /** * Determines if the start date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsBeforeOrAt(mixed $date = null): bool { return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is after another given date. * (Rather start/end are included by options is ignored.) */ public function startsAfter(mixed $date = null): bool { return $this->getStartDate()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the start date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAfterOrAt(mixed $date = null): bool { return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAt(mixed $date = null): bool { return $this->getStartDate()->equalTo($this->resolveCarbon($date)); } /** * Determines if the end date is before another given date. * (Rather start/end are included by options is ignored.) */ public function endsBefore(mixed $date = null): bool { return $this->calculateEnd()->lessThan($this->resolveCarbon($date)); } /** * Determines if the end date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsBeforeOrAt(mixed $date = null): bool { return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is after another given date. * (Rather start/end are included by options is ignored.) */ public function endsAfter(mixed $date = null): bool { return $this->calculateEnd()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the end date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAfterOrAt(mixed $date = null): bool { return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAt(mixed $date = null): bool { return $this->calculateEnd()->equalTo($this->resolveCarbon($date)); } /** * Return true if start date is now or later. * (Rather start/end are included by options is ignored.) */ public function isStarted(): bool { return $this->startsBeforeOrAt(); } /** * Return true if end date is now or later. * (Rather start/end are included by options is ignored.) */ public function isEnded(): bool { return $this->endsBeforeOrAt(); } /** * Return true if now is between start date (included) and end date (excluded). * (Rather start/end are included by options is ignored.) */ public function isInProgress(): bool { return $this->isStarted() && !$this->isEnded(); } /** * Round the current instance at the given unit with given precision if specified and the given function. */ public function roundUnit( string $unit, DateInterval|float|int|string|null $precision = 1, callable|string $function = 'round', ): static { $self = $this->copyIfImmutable(); $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); if ($self->endDate) { $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); } /** * Truncate the current instance at the given unit with given precision if specified. */ public function floorUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. */ public function ceilUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function round( DateInterval|float|int|string|null $precision = null, callable|string $function = 'round', ): static { return $this->roundWith( $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(), $function ); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function floor(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified (else period interval is used). */ public function ceil(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'ceil'); } /** * Specify data which should be serialized to JSON. * * @link https://php.net/manual/en/jsonserializable.jsonserialize.php * * @return CarbonInterface[] */ public function jsonSerialize(): array { return $this->toArray(); } /** * Return true if the given date is between start and end. */ public function contains(mixed $date = null): bool { $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : ''); $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : ''); return $this->$startMethod($date) && $this->$endMethod($date); } /** * Return true if the current period follows a given other period (with no overlap). * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31] * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function follows(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval())); } /** * Return true if the given other period follows the current one (with no overlap). * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12] * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function isFollowedBy(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $period->follows($this); } /** * Return true if the given period either follows or is followed by the current one. * * @see follows() * @see isFollowedBy() */ public function isConsecutiveWith(mixed $period, mixed ...$arguments): bool { return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments); } public function __debugInfo(): array { $info = $this->baseDebugInfo(); unset( $info['start'], $info['end'], $info['interval'], $info['include_start_date'], $info['include_end_date'], $info['constructed'], $info["\0*\0constructed"], ); return $info; } public function __unserialize(array $data): void { try { $values = array_combine( array_map( static fn (string $key): string => preg_replace('/^\0\*\0/', '', $key), array_keys($data), ), $data, ); $this->initializeSerialization($values); foreach ($values as $key => $value) { if ($value === null) { continue; } $property = match ($key) { 'tzName' => $this->setTimezone(...), 'options' => $this->setOptions(...), 'recurrences' => $this->setRecurrences(...), 'current' => function (mixed $current): void { if (!($current instanceof CarbonInterface)) { $current = $this->resolveCarbon($current); } $this->carbonCurrent = $current; }, 'start' => 'startDate', 'interval' => $this->setDateInterval(...), 'end' => 'endDate', 'key' => null, 'include_start_date' => function (bool $included): void { $this->excludeStartDate(!$included); }, 'include_end_date' => function (bool $included): void { $this->excludeEndDate(!$included); }, default => $key, }; if ($property === null) { continue; } if (\is_callable($property)) { $property($value); continue; } if ($value instanceof DateTimeInterface && !($value instanceof CarbonInterface)) { $value = ($value instanceof DateTime) ? Carbon::instance($value) : CarbonImmutable::instance($value); } try { $this->$property = $value; } catch (Throwable) { // Must be ignored for backward-compatibility } } if (\array_key_exists('carbonRecurrences', $values)) { $this->carbonRecurrences = $values['carbonRecurrences']; } elseif (((int) ($values['recurrences'] ?? 0)) <= 1 && $this->endDate !== null) { $this->carbonRecurrences = null; } } catch (Throwable $e) { // @codeCoverageIgnoreStart if (!method_exists(parent::class, '__unserialize')) { throw $e; } parent::__unserialize($data); // @codeCoverageIgnoreEnd } } /** * Update properties after removing built-in filters. */ protected function updateInternalState(): void { if (!$this->hasFilter(static::END_DATE_FILTER)) { $this->endDate = null; } if (!$this->hasFilter(static::RECURRENCES_FILTER)) { $this->carbonRecurrences = null; } } /** * Create a filter tuple from raw parameters. * * Will create an automatic filter callback for one of Carbon's is* methods. */ protected function createFilterTuple(array $parameters): array { $method = array_shift($parameters); if (!$this->isCarbonPredicateMethod($method)) { return [$method, array_shift($parameters)]; } return [static fn ($date) => ([$date, $method])(...$parameters), $method]; } /** * Return whether given callable is a string pointing to one of Carbon's is* methods * and should be automatically converted to a filter callback. */ protected function isCarbonPredicateMethod(callable|string $callable): bool { return \is_string($callable) && str_starts_with($callable, 'is') && (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable)); } /** * Recurrences filter callback (limits number of recurrences). * * @SuppressWarnings(UnusedFormalParameter) */ protected function filterRecurrences(CarbonInterface $current, int $key): bool|callable { if ($key < $this->carbonRecurrences) { return true; } return static::END_ITERATION; } /** * End date filter callback. * * @return bool|static::END_ITERATION */ protected function filterEndDate(CarbonInterface $current): bool|callable { if (!$this->isEndExcluded() && $current == $this->endDate) { return true; } if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) { return true; } return static::END_ITERATION; } /** * End iteration filter callback. * * @return static::END_ITERATION */ protected function endIteration(): callable { return static::END_ITERATION; } /** * Handle change of the parameters. */ protected function handleChangedParameters(): void { if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { $this->dateClass = CarbonImmutable::class; } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { $this->dateClass = Carbon::class; } $this->validationResult = null; } /** * Validate current date and stop iteration when necessary. * * Returns true when current date is valid, false if it is not, or static::END_ITERATION * when iteration should be stopped. * * @return bool|static::END_ITERATION */ protected function validateCurrentDate(): bool|callable { if ($this->carbonCurrent === null) { $this->rewind(); } // Check after the first rewind to avoid repeating the initial validation. return $this->validationResult ?? ($this->validationResult = $this->checkFilters()); } /** * Check whether current value and key pass all the filters. * * @return bool|static::END_ITERATION */ protected function checkFilters(): bool|callable { $current = $this->prepareForReturn($this->carbonCurrent); foreach ($this->filters as $tuple) { $result = \call_user_func($tuple[0], $current->avoidMutation(), $this->key, $this); if ($result === static::END_ITERATION) { return static::END_ITERATION; } if (!$result) { return false; } } return true; } /** * Prepare given date to be returned to the external logic. * * @param CarbonInterface $date * * @return CarbonInterface */ protected function prepareForReturn(CarbonInterface $date) { $date = ([$this->dateClass, 'make'])($date); if ($this->timezone) { return $date->setTimezone($this->timezone); } return $date; } /** * Keep incrementing the current date until a valid date is found or the iteration is ended. * * @throws RuntimeException */ protected function incrementCurrentDateUntilValid(): void { $attempts = 0; do { $this->carbonCurrent = $this->carbonCurrent->add($this->dateInterval); $this->validationResult = null; if (++$attempts > static::NEXT_MAX_ATTEMPTS) { throw new UnreachableException('Could not find next valid date.'); } } while ($this->validateCurrentDate() === false); } /** * Call given macro. */ protected function callMacro(string $name, array $parameters): mixed { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date * * @return \Carbon\CarbonInterface */ protected function resolveCarbon($date = null) { return $this->getStartDate()->nowWithSameTz()->carbonize($date); } /** * Resolve passed arguments or DatePeriod to a CarbonPeriod object. */ protected function resolveCarbonPeriod(mixed $period, mixed ...$arguments): self { if ($period instanceof self) { return $period; } return $period instanceof DatePeriod ? static::instance($period) : static::create($period, ...$arguments); } private function orderCouple($first, $second): array { return $first > $second ? [$second, $first] : [$first, $second]; } private function makeDateTime($value): ?DateTimeInterface { if ($value instanceof DateTimeInterface) { return $value; } if ($value instanceof WeekDay || $value instanceof Month) { $dateClass = $this->dateClass; return new $dateClass($value, $this->timezoneSetting); } if (\is_string($value)) { $value = trim($value); if (!preg_match('/^P[\dT]/', $value) && !preg_match('/^R\d/', $value) && preg_match('/[a-z\d]/i', $value) ) { $dateClass = $this->dateClass; return $dateClass::parse($value, $this->timezoneSetting); } } return null; } private function isInfiniteDate($date): bool { return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); } private function rawDate($date): ?DateTimeInterface { if ($date === false || $date === null) { return null; } if ($date instanceof CarbonInterface) { return $date->isMutable() ? $date->toDateTime() : $date->toDateTimeImmutable(); } if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { return $date; } $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); } private static function setDefaultParameters(array &$parameters, array $defaults): void { foreach ($defaults as [$index, $name, $value]) { if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { $parameters[$index] = $value; } } } private function setFromAssociativeArray(array $parameters): void { if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['end'])) { $this->setEndDate($parameters['end']); } if (isset($parameters['recurrences'])) { $this->setRecurrences($parameters['recurrences']); } if (isset($parameters['interval'])) { $this->setDateInterval($parameters['interval']); } if (isset($parameters['options'])) { $this->setOptions($parameters['options']); } } private function configureTimezone(DateTimeZone $timezone, array $sortedArguments, array $originalArguments): array { $this->setTimezone($timezone); if (\is_string($originalArguments['start'] ?? null)) { $sortedArguments['start'] = $this->makeDateTime($originalArguments['start']); } if (\is_string($originalArguments['end'] ?? null)) { $sortedArguments['end'] = $this->makeDateTime($originalArguments['end']); } return $sortedArguments; } private function initializeSerialization(array $values): void { $serializationBase = [ 'start' => $values['start'] ?? $values['startDate'] ?? null, 'current' => $values['current'] ?? $values['carbonCurrent'] ?? null, 'end' => $values['end'] ?? $values['endDate'] ?? null, 'interval' => $values['interval'] ?? $values['dateInterval'] ?? null, 'recurrences' => max(1, (int) ($values['recurrences'] ?? $values['carbonRecurrences'] ?? 1)), 'include_start_date' => $values['include_start_date'] ?? true, 'include_end_date' => $values['include_end_date'] ?? false, ]; foreach (['start', 'current', 'end'] as $dateProperty) { if ($serializationBase[$dateProperty] instanceof Carbon) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTime(); } elseif ($serializationBase[$dateProperty] instanceof CarbonInterface) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTimeImmutable(); } } if ($serializationBase['interval'] instanceof CarbonInterval) { $serializationBase['interval'] = $serializationBase['interval']->toDateInterval(); } // @codeCoverageIgnoreStart if (method_exists(parent::class, '__unserialize')) { parent::__unserialize($serializationBase); return; } $excludeStart = !($values['include_start_date'] ?? true); $includeEnd = $values['include_end_date'] ?? true; parent::__construct( $serializationBase['start'], $serializationBase['interval'], $serializationBase['end'] ?? $serializationBase['recurrences'], ($excludeStart ? self::EXCLUDE_START_DATE : 0) | ($includeEnd && \defined('DatePeriod::INCLUDE_END_DATE') ? self::INCLUDE_END_DATE : 0), ); // @codeCoverageIgnoreEnd } }
PHP
{ "end_line": 1614, "name": "first", "signature": "public function first(): ?CarbonInterface", "start_line": 1601 }
{ "class_name": "CarbonPeriod", "class_signature": "class CarbonPeriod implements Countable, JsonSerializable, UnitValue", "namespace": "Carbon" }
shiftTimezone
Carbon/src/Carbon/CarbonPeriod.php
public function shiftTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } return $self; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotACarbonClassException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnreachableException; use Carbon\Traits\DeprecatedPeriodProperties; use Carbon\Traits\IntervalRounding; use Carbon\Traits\LocalFactory; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Throwable; // @codeCoverageIgnoreStart require PHP_VERSION < 8.2 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php' : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php'; // @codeCoverageIgnoreEnd /** * Substitution of DatePeriod with some modifications and many more features. * * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. * @method static static since($date = null, $inclusive = null) Alias for start(). * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. * @method static static until($date = null, $inclusive = null) Alias for end(). * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. * @method static static times($recurrences = null) Alias for recurrences(). * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance. * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. * @method static static push($callback, $name = null) Alias for filter(). * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance. * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. * @method static static year($years = 1) Alias for years(). * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. * @method static static month($months = 1) Alias for months(). * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. * @method static static week($weeks = 1) Alias for weeks(). * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. * @method static static dayz($days = 1) Alias for days(). * @method static static day($days = 1) Alias for days(). * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. * @method static static hour($hours = 1) Alias for hours(). * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. * @method static static minute($minutes = 1) Alias for minutes(). * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. * @method static static second($seconds = 1) Alias for seconds(). * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * * @mixin DeprecatedPeriodProperties * * @SuppressWarnings(TooManyFields) * @SuppressWarnings(CamelCasePropertyName) * @SuppressWarnings(CouplingBetweenObjects) */ class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue { use LocalFactory; use IntervalRounding; use Mixin { Mixin::mixin as baseMixin; } use Options { Options::__debugInfo as baseDebugInfo; } use ToStringFormat; /** * Built-in filter for limit by recurrences. * * @var callable */ public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; /** * Built-in filter for limit to an end. * * @var callable */ public const END_DATE_FILTER = [self::class, 'filterEndDate']; /** * Special value which can be returned by filters to end iteration. Also a filter. * * @var callable */ public const END_ITERATION = [self::class, 'endIteration']; /** * Exclude end date from iteration. * * @var int */ public const EXCLUDE_END_DATE = 8; /** * Yield CarbonImmutable instances. * * @var int */ public const IMMUTABLE = 4; /** * Number of maximum attempts before giving up on finding next valid date. * * @var int */ public const NEXT_MAX_ATTEMPTS = 1000; /** * Number of maximum attempts before giving up on finding end date. * * @var int */ public const END_MAX_ATTEMPTS = 10000; /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = Carbon::class; /** * The registered macros. */ protected static array $macros = []; /** * Date class of iteration items. */ protected string $dateClass = Carbon::class; /** * Underlying date interval instance. Always present, one day by default. */ protected ?CarbonInterval $dateInterval = null; /** * True once __construct is finished. */ protected bool $constructed = false; /** * Whether current date interval was set by default. */ protected bool $isDefaultInterval = false; /** * The filters stack. */ protected array $filters = []; /** * Period start date. Applied on rewind. Always present, now by default. */ protected ?CarbonInterface $startDate = null; /** * Period end date. For inverted interval should be before the start date. Applied via a filter. */ protected ?CarbonInterface $endDate = null; /** * Limit for number of recurrences. Applied via a filter. */ protected int|float|null $carbonRecurrences = null; /** * Iteration options. */ protected ?int $options = null; /** * Index of current date. Always sequential, even if some dates are skipped by filters. * Equal to null only before the first iteration. */ protected int $key = 0; /** * Current date. May temporarily hold unaccepted value when looking for a next valid date. * Equal to null only before the first iteration. */ protected ?CarbonInterface $carbonCurrent = null; /** * Timezone of current date. Taken from the start date. */ protected ?DateTimeZone $timezone = null; /** * The cached validation result for current date. */ protected array|string|bool|null $validationResult = null; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; public function getIterator(): Generator { $this->rewind(); while ($this->valid()) { $key = $this->key(); $value = $this->current(); yield $key => $value; $this->next(); } } /** * Make a CarbonPeriod instance from given variable if possible. */ public static function make(mixed $var): ?static { try { return static::instance($var); } catch (NotAPeriodException) { return static::create($var); } } /** * Create a new instance from a DatePeriod or CarbonPeriod object. */ public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); } /** * Create a new instance. */ public static function create(...$params): static { return static::createFromArray($params); } /** * Create a new instance from an array of parameters. */ public static function createFromArray(array $params): static { return new static(...$params); } /** * Create CarbonPeriod from ISO 8601 string. */ public static function createFromIso(string $iso, ?int $options = null): static { $params = static::parseIso8601($iso); $instance = static::createFromArray($params); $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options; $instance->handleChangedParameters(); return $instance; } public static function createFromISO8601String(string $iso, ?int $options = null): static { return self::createFromIso($iso, $options); } /** * Return whether the given interval contains non-zero value of any time unit. */ protected static function intervalHasTime(DateInterval $interval): bool { return $interval->h || $interval->i || $interval->s || $interval->f; } /** * Return whether given variable is an ISO 8601 specification. * * Note: Check is very basic, as actual validation will be done later when parsing. * We just want to ensure that variable is not any other type of valid parameter. */ protected static function isIso8601(mixed $var): bool { if (!\is_string($var)) { return false; } // Match slash but not within a timezone name. $part = '[a-z]+(?:[_-][a-z]+)*'; preg_match("#\b$part/$part\b|(/)#i", $var, $match); return isset($match[1]); } /** * Parse given ISO 8601 string into an array of arguments. * * @SuppressWarnings(ElseExpression) */ protected static function parseIso8601(string $iso): array { $result = []; $interval = null; $start = null; $end = null; $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = self::makeInterval($part)) { $interval = $part; } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); } $result[] = $parsed; } return $result; } /** * Add missing parts of the target date from the source date. */ protected static function addMissingParts(string $source, string $target): string { $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); return $count ? $result : $target; } private static function makeInterval(mixed $input): ?CarbonInterval { try { return CarbonInterval::make($input); } catch (Throwable) { return null; } } private static function makeTimezone(mixed $input): ?CarbonTimeZone { if (!\is_string($input)) { return null; } try { return CarbonTimeZone::create($input); } catch (Throwable) { return null; } } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonPeriod::macro('middle', function () { * return $this->getStartDate()->average($this->getEndDate()); * }); * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonPeriod::mixin(new class { * public function addDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->addDays($count) * )->setEndDate( * $this->getEndDate()->addDays($count) * ); * }; * } * public function subDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->subDays($count) * )->setEndDate( * $this->getEndDate()->subDays($count) * ); * }; * } * }); * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); * ``` * * @throws ReflectionException */ public static function mixin(object|string $mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Provide static proxy for instance aliases. */ public static function __callStatic(string $method, array $parameters): mixed { $date = new static(); if (static::hasMacro($method)) { return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters)); } return $date->$method(...$parameters); } /** * CarbonPeriod constructor. * * @SuppressWarnings(ElseExpression) * * @throws InvalidArgumentException */ public function __construct(...$arguments) { $raw = null; if (isset($arguments['raw'])) { $raw = $arguments['raw']; $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false; if (isset($arguments['dateClass'])) { $this->dateClass = $arguments['dateClass']; } $arguments = $raw; } // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. $argumentsCount = \count($arguments); if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { array_splice($arguments, 0, 1, static::parseIso8601($iso)); } if ($argumentsCount === 1) { if ($arguments[0] instanceof self) { $arguments = [ $arguments[0]->getStartDate(), $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(), $arguments[0]->getDateInterval(), $arguments[0]->getOptions(), ]; } elseif ($arguments[0] instanceof DatePeriod) { $arguments = [ $arguments[0]->start, $arguments[0]->end ?: ($arguments[0]->recurrences - 1), $arguments[0]->interval, $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, ]; } } if (is_a($this->dateClass, DateTimeImmutable::class, true)) { $this->options = static::IMMUTABLE; } $optionsSet = false; $originalArguments = []; $sortedArguments = []; foreach ($arguments as $argument) { $parsedDate = null; if ($argument instanceof DateTimeZone) { $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments); } elseif (!isset($sortedArguments['interval']) && ( (\is_string($argument) && preg_match( '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument, )) || $argument instanceof DateInterval || $argument instanceof Closure || $argument instanceof Unit ) && $parsedInterval = self::makeInterval($argument) ) { $sortedArguments['interval'] = $parsedInterval; } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) { $sortedArguments['start'] = $parsedDate; $originalArguments['start'] = $argument; } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { $sortedArguments['end'] = $parsedDate; $originalArguments['end'] = $argument; } elseif (!isset($sortedArguments['recurrences']) && !isset($sortedArguments['end']) && (\is_int($argument) || \is_float($argument)) && $argument >= 0 ) { $sortedArguments['recurrences'] = $argument; } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { $optionsSet = true; $sortedArguments['options'] = (((int) $this->options) | ((int) $argument)); } elseif ($parsedTimezone = self::makeTimezone($argument)) { $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($raw === null && isset($sortedArguments['start'])) { $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1); if (\is_float($end)) { $end = $end === INF ? PHP_INT_MAX : (int) round($end); } $raw = [ $sortedArguments['start'], $sortedArguments['interval'] ?? CarbonInterval::day(), $end, ]; } $this->setFromAssociativeArray($sortedArguments); if ($this->startDate === null) { $dateClass = $this->dateClass; $this->setStartDate($dateClass::now()); } if ($this->dateInterval === null) { $this->setDateInterval(CarbonInterval::day()); $this->isDefaultInterval = true; } if ($this->options === null) { $this->setOptions(0); } parent::__construct( $this->startDate, $this->dateInterval, $this->endDate ?? max(1, min(2147483639, $this->recurrences ?? 1)), $this->options, ); $this->constructed = true; } /** * Get a copy of the instance. */ public function copy(): static { return clone $this; } /** * Prepare the instance to be set (self if mutable to be mutated, * copy if immutable to generate a new instance). */ protected function copyIfImmutable(): static { return $this; } /** * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. */ protected function getGetter(string $name): ?callable { return match (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) { 'start', 'start_date' => [$this, 'getStartDate'], 'end', 'end_date' => [$this, 'getEndDate'], 'interval', 'date_interval' => [$this, 'getDateInterval'], 'recurrences' => [$this, 'getRecurrences'], 'include_start_date' => [$this, 'isStartIncluded'], 'include_end_date' => [$this, 'isEndIncluded'], 'current' => [$this, 'current'], 'locale' => [$this, 'locale'], 'tzname', 'tz_name' => fn () => match (true) { $this->timezoneSetting === null => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, $this->timezoneSetting instanceof DateTimeZone => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, default => null, }; } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function get(string $name) { $getter = $this->getGetter($name); if ($getter) { return $getter(); } throw new UnknownGetterException($name); } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function __get(string $name) { return $this->get($name); } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset(string $name): bool { return $this->getGetter($name) !== null; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Set the iteration item class. * * @param string $dateClass * * @return static */ public function setDateClass(string $dateClass) { if (!is_a($dateClass, CarbonInterface::class, true)) { throw new NotACarbonClassException($dateClass); } $self = $this->copyIfImmutable(); $self->dateClass = $dateClass; if (is_a($dateClass, Carbon::class, true)) { $self->options = $self->options & ~static::IMMUTABLE; } elseif (is_a($dateClass, CarbonImmutable::class, true)) { $self->options = $self->options | static::IMMUTABLE; } return $self; } /** * Returns iteration item date class. * * @return string */ public function getDateClass(): string { return $this->dateClass; } /** * Change the period date interval. * * @param DateInterval|Unit|string|int $interval * @param Unit|string $unit the unit of $interval if it's a number * * @throws InvalidIntervalException * * @return static */ public function setDateInterval(mixed $interval, Unit|string|null $unit = null): static { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->name; } if (!$interval = CarbonInterval::make($interval, $unit)) { throw new InvalidIntervalException('Invalid interval.'); } if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) { throw new InvalidIntervalException('Empty interval is not accepted.'); } $self = $this->copyIfImmutable(); $self->dateInterval = $interval; $self->isDefaultInterval = false; $self->handleChangedParameters(); return $self; } /** * Reset the date interval to the default value. * * Difference with simply setting interval to 1-day is that P1D will not appear when calling toIso8601String() * and also next adding to the interval won't include the default 1-day. */ public function resetDateInterval(): static { $self = $this->copyIfImmutable(); $self->setDateInterval(CarbonInterval::day()); $self->isDefaultInterval = true; return $self; } /** * Invert the period date interval. */ public function invertDateInterval(): static { return $this->setDateInterval($this->dateInterval->invert()); } /** * Set start and end date. * * @param DateTime|DateTimeInterface|string $start * @param DateTime|DateTimeInterface|string|null $end * * @return static */ public function setDates(mixed $start, mixed $end): static { return $this->setStartDate($start)->setEndDate($end); } /** * Change the period options. * * @param int|null $options * * @return static */ public function setOptions(?int $options): static { $self = $this->copyIfImmutable(); $self->options = $options ?? 0; $self->handleChangedParameters(); return $self; } /** * Get the period options. */ public function getOptions(): int { return $this->options ?? 0; } /** * Toggle given options on or off. * * @param int $options * @param bool|null $state * * @throws InvalidArgumentException * * @return static */ public function toggleOptions(int $options, ?bool $state = null): static { $self = $this->copyIfImmutable(); if ($state === null) { $state = ($this->options & $options) !== $options; } return $self->setOptions( $state ? $this->options | $options : $this->options & ~$options, ); } /** * Toggle EXCLUDE_START_DATE option. */ public function excludeStartDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_START_DATE, $state); } /** * Toggle EXCLUDE_END_DATE option. */ public function excludeEndDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_END_DATE, $state); } /** * Get the underlying date interval. */ public function getDateInterval(): CarbonInterval { return $this->dateInterval->copy(); } /** * Get start date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getStartDate(?string $rounding = null): CarbonInterface { $date = $this->startDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get end date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getEndDate(?string $rounding = null): ?CarbonInterface { if (!$this->endDate) { return null; } $date = $this->endDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get number of recurrences. */ #[ReturnTypeWillChange] public function getRecurrences(): int|float|null { return $this->carbonRecurrences; } /** * Returns true if the start date should be excluded. */ public function isStartExcluded(): bool { return ($this->options & static::EXCLUDE_START_DATE) !== 0; } /** * Returns true if the end date should be excluded. */ public function isEndExcluded(): bool { return ($this->options & static::EXCLUDE_END_DATE) !== 0; } /** * Returns true if the start date should be included. */ public function isStartIncluded(): bool { return !$this->isStartExcluded(); } /** * Returns true if the end date should be included. */ public function isEndIncluded(): bool { return !$this->isEndExcluded(); } /** * Return the start if it's included by option, else return the start + 1 period interval. */ public function getIncludedStartDate(): CarbonInterface { $start = $this->getStartDate(); if ($this->isStartExcluded()) { return $start->add($this->getDateInterval()); } return $start; } /** * Return the end if it's included by option, else return the end - 1 period interval. * Warning: if the period has no fixed end, this method will iterate the period to calculate it. */ public function getIncludedEndDate(): CarbonInterface { $end = $this->getEndDate(); if (!$end) { return $this->calculateEnd(); } if ($this->isEndExcluded()) { return $end->sub($this->getDateInterval()); } return $end; } /** * Add a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function addFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); $self->filters[] = $tuple; $self->handleChangedParameters(); return $self; } /** * Prepend a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function prependFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); array_unshift($self->filters, $tuple); $self->handleChangedParameters(); return $self; } /** * Remove a filter by instance or name. */ public function removeFilter(callable|string $filter): static { $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; $self->filters = array_values(array_filter( $this->filters, static fn ($tuple) => $tuple[$key] !== $filter, )); $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Return whether given instance or name is in the filter stack. */ public function hasFilter(callable|string $filter): bool { $key = \is_callable($filter) ? 0 : 1; foreach ($this->filters as $tuple) { if ($tuple[$key] === $filter) { return true; } } return false; } /** * Get filters stack. */ public function getFilters(): array { return $this->filters; } /** * Set filters stack. */ public function setFilters(array $filters): static { $self = $this->copyIfImmutable(); $self->filters = $filters; $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Reset filters stack. */ public function resetFilters(): static { $self = $this->copyIfImmutable(); $self->filters = []; if ($self->endDate !== null) { $self->filters[] = [static::END_DATE_FILTER, null]; } if ($self->carbonRecurrences !== null) { $self->filters[] = [static::RECURRENCES_FILTER, null]; } $self->handleChangedParameters(); return $self; } /** * Add a recurrences filter (set maximum number of recurrences). * * @throws InvalidArgumentException */ public function setRecurrences(int|float|null $recurrences): static { if ($recurrences === null) { return $this->removeFilter(static::RECURRENCES_FILTER); } if ($recurrences < 0) { throw new InvalidPeriodParameterException('Invalid number of recurrences.'); } /** @var self $self */ $self = $this->copyIfImmutable(); $self->carbonRecurrences = $recurrences === INF ? INF : (int) $recurrences; if (!$self->hasFilter(static::RECURRENCES_FILTER)) { return $self->addFilter(static::RECURRENCES_FILTER); } $self->handleChangedParameters(); return $self; } /** * Change the period start date. * * @param DateTime|DateTimeInterface|string $date * @param bool|null $inclusive * * @throws InvalidPeriodDateException * * @return static */ public function setStartDate(mixed $date, ?bool $inclusive = null): static { if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date, $this->timezone))) { throw new InvalidPeriodDateException('Invalid start date.'); } $self = $this->copyIfImmutable(); $self->startDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); } return $self; } /** * Change the period end date. * * @param DateTime|DateTimeInterface|string|null $date * @param bool|null $inclusive * * @throws \InvalidArgumentException * * @return static */ public function setEndDate(mixed $date, ?bool $inclusive = null): static { if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date, $this->timezone)) { throw new InvalidPeriodDateException('Invalid end date.'); } if (!$date) { return $this->removeFilter(static::END_DATE_FILTER); } $self = $this->copyIfImmutable(); $self->endDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); } if (!$self->hasFilter(static::END_DATE_FILTER)) { return $self->addFilter(static::END_DATE_FILTER); } $self->handleChangedParameters(); return $self; } /** * Check if the current position is valid. */ public function valid(): bool { return $this->validateCurrentDate() === true; } /** * Return the current key. */ public function key(): ?int { return $this->valid() ? $this->key : null; } /** * Return the current date. */ public function current(): ?CarbonInterface { return $this->valid() ? $this->prepareForReturn($this->carbonCurrent) : null; } /** * Move forward to the next date. * * @throws RuntimeException */ public function next(): void { if ($this->carbonCurrent === null) { $this->rewind(); } if ($this->validationResult !== static::END_ITERATION) { $this->key++; $this->incrementCurrentDateUntilValid(); } } /** * Rewind to the start date. * * Iterating over a date in the UTC timezone avoids bug during backward DST change. * * @see https://bugs.php.net/bug.php?id=72255 * @see https://bugs.php.net/bug.php?id=74274 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time * * @throws RuntimeException */ public function rewind(): void { $this->key = 0; $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate); $settings = $this->getSettings(); if ($this->hasLocalTranslator()) { $settings['locale'] = $this->getTranslatorLocale(); } $this->carbonCurrent->settings($settings); $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null; if ($this->timezone) { $this->carbonCurrent = $this->carbonCurrent->utc(); } $this->validationResult = null; if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { $this->incrementCurrentDateUntilValid(); } } /** * Skip iterations and returns iteration state (false if ended, true if still valid). * * @param int $count steps number to skip (1 by default) * * @return bool */ public function skip(int $count = 1): bool { for ($i = $count; $this->valid() && $i > 0; $i--) { $this->next(); } return $this->valid(); } /** * Format the date period as ISO 8601. */ public function toIso8601String(): string { $parts = []; if ($this->carbonRecurrences !== null) { $parts[] = 'R'.$this->carbonRecurrences; } $parts[] = $this->startDate->toIso8601String(); if (!$this->isDefaultInterval) { $parts[] = $this->dateInterval->spec(); } if ($this->endDate !== null) { $parts[] = $this->endDate->toIso8601String(); } return implode('/', $parts); } /** * Convert the date period into a string. */ public function toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if ($format instanceof Closure) { return $format($this); } $translator = ([$this->dateClass, 'getTranslator'])(); $parts = []; $format = $format ?? ( !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) ? 'Y-m-d H:i:s' : 'Y-m-d' ); if ($this->carbonRecurrences !== null) { $parts[] = $this->translate('period_recurrences', [], $this->carbonRecurrences, $translator); } $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([ 'join' => true, ])], null, $translator); $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator); if ($this->endDate !== null) { $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator); } $result = implode(' ', $parts); return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1); } /** * Format the date period as ISO 8601. */ public function spec(): string { return $this->toIso8601String(); } /** * Cast the current instance into the given class. * * @param string $className The $className::instance() method will be called to cast the current object. * * @return DatePeriod|object */ public function cast(string $className): object { if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( $this->rawDate($this->getStartDate()), $this->getDateInterval(), $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0, ); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Return native DatePeriod PHP object matching the current instance. * * @example * ``` * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod()); * ``` */ public function toDatePeriod(): DatePeriod { return $this->cast(DatePeriod::class); } /** * Return `true` if the period has no custom filter and is guaranteed to be endless. * * Note that we can't check if a period is endless as soon as it has custom filters * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in * a way we can't predict without actually iterating the period. */ public function isUnfilteredAndEndLess(): bool { foreach ($this->filters as $filter) { switch ($filter) { case [static::RECURRENCES_FILTER, null]: if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) { return false; } break; case [static::END_DATE_FILTER, null]: if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { return false; } break; default: return false; } } return true; } /** * Convert the date period into an array without changing current iteration state. * * @return CarbonInterface[] */ public function toArray(): array { if ($this->isUnfilteredAndEndLess()) { throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); } $state = [ $this->key, $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null, $this->validationResult, ]; $result = iterator_to_array($this); [$this->key, $this->carbonCurrent, $this->validationResult] = $state; return $result; } /** * Count dates in the date period. */ public function count(): int { return \count($this->toArray()); } /** * Return the first date in the date period. */ public function first(): ?CarbonInterface { if ($this->isUnfilteredAndEndLess()) { foreach ($this as $date) { $this->rewind(); return $date; } return null; } return ($this->toArray() ?: [])[0] ?? null; } /** * Return the last date in the date period. */ public function last(): ?CarbonInterface { $array = $this->toArray(); return $array ? $array[\count($array) - 1] : null; } /** * Convert the date period into a string. */ public function __toString(): string { return $this->toString(); } /** * Add aliases for setters. * * CarbonPeriod::days(3)->hours(5)->invert() * ->sinceNow()->until('2010-01-10') * ->filter(...) * ->count() * * Note: We use magic method to let static and instance aliases with the same names. */ public function __call(string $method, array $parameters): mixed { if (static::hasMacro($method)) { return static::bindMacroContext($this, fn () => $this->callMacro($method, $parameters)); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } $count = \count($parameters); switch ($method) { case 'start': case 'since': if ($count === 0) { return $this->getStartDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setStartDate(...$parameters); case 'sinceNow': return $this->setStartDate(new Carbon(), ...$parameters); case 'end': case 'until': if ($count === 0) { return $this->getEndDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setEndDate(...$parameters); case 'untilNow': return $this->setEndDate(new Carbon(), ...$parameters); case 'dates': case 'between': self::setDefaultParameters($parameters, [ [0, 'start', null], [1, 'end', null], ]); return $this->setDates(...$parameters); case 'recurrences': case 'times': if ($count === 0) { return $this->getRecurrences(); } self::setDefaultParameters($parameters, [ [0, 'recurrences', null], ]); return $this->setRecurrences(...$parameters); case 'options': if ($count === 0) { return $this->getOptions(); } self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->setOptions(...$parameters); case 'toggle': self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->toggleOptions(...$parameters); case 'filter': case 'push': return $this->addFilter(...$parameters); case 'prepend': return $this->prependFilter(...$parameters); case 'filters': if ($count === 0) { return $this->getFilters(); } self::setDefaultParameters($parameters, [ [0, 'filters', []], ]); return $this->setFilters(...$parameters); case 'interval': case 'each': case 'every': case 'step': case 'stepBy': if ($count === 0) { return $this->getDateInterval(); } return $this->setDateInterval(...$parameters); case 'invert': return $this->invertDateInterval(); case 'years': case 'year': case 'months': case 'month': case 'weeks': case 'week': case 'days': case 'dayz': case 'day': case 'hours': case 'hour': case 'minutes': case 'minute': case 'seconds': case 'second': case 'milliseconds': case 'millisecond': case 'microseconds': case 'microsecond': return $this->setDateInterval(( // Override default P1D when instantiating via fluent setters. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] )(...$parameters)); } $dateClass = $this->dateClass; if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { throw new UnknownMethodException($method); } return $this; } /** * Set the instance's timezone from a string or object and apply it to start/end. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->setTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->setTimezone($timezone)); } return $self; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } return $self; } /** * Returns the end is set, else calculated from start and recurrences. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. * * @return CarbonInterface */ public function calculateEnd(?string $rounding = null): CarbonInterface { if ($end = $this->getEndDate($rounding)) { return $end; } if ($this->dateInterval->isEmpty()) { return $this->getStartDate($rounding); } $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); if ($date && $rounding) { $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); } return $date; } private function getEndFromRecurrences(): ?CarbonInterface { if ($this->carbonRecurrences === null) { throw new UnreachableException( "Could not calculate period end without either explicit end or recurrences.\n". "If you're looking for a forever-period, use ->setRecurrences(INF).", ); } if ($this->carbonRecurrences === INF) { $start = $this->getStartDate(); return $start < $start->avoidMutation()->add($this->getDateInterval()) ? CarbonImmutable::endOfTime() : CarbonImmutable::startOfTime(); } if ($this->filters === [[static::RECURRENCES_FILTER, null]]) { return $this->getStartDate()->avoidMutation()->add( $this->getDateInterval()->times( $this->carbonRecurrences - ($this->isStartExcluded() ? 0 : 1), ), ); } return null; } private function iterateUntilEnd(): ?CarbonInterface { $attempts = 0; $date = null; foreach ($this as $date) { if (++$attempts > static::END_MAX_ATTEMPTS) { throw new UnreachableException( 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.', ); } } return $date; } /** * Returns true if the current period overlaps the given one (if 1 parameter passed) * or the period between 2 dates (if 2 parameters passed). * * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd * * @return bool */ public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool { $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; if (!($range instanceof self)) { $range = static::create($range); } [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); return $end > $rangeStart && $rangeEnd > $start; } /** * Execute a given function on each date of the period. * * @example * ``` * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) { * echo $date->diffInDays('2020-12-25')." days before Christmas!\n"; * }); * ``` */ public function forEach(callable $callback): void { foreach ($this as $date) { $callback($date); } } /** * Execute a given function on each date of the period and yield the result of this function. * * @example * ``` * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24'); * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) { * return $date->diffInDays('2020-12-25').' days before Christmas!'; * }))); * ``` */ public function map(callable $callback): Generator { foreach ($this as $date) { yield $callback($date); } } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. * * @see equalTo() */ public function eq(mixed $period): bool { return $this->equalTo($period); } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. */ public function equalTo(mixed $period): bool { if (!($period instanceof self)) { $period = self::make($period); } $end = $this->getEndDate(); return $period !== null && $this->getDateInterval()->eq($period->getDateInterval()) && $this->getStartDate()->eq($period->getStartDate()) && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. * * @see notEqualTo() */ public function ne(mixed $period): bool { return $this->notEqualTo($period); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. */ public function notEqualTo(mixed $period): bool { return !$this->eq($period); } /** * Determines if the start date is before another given date. * (Rather start/end are included by options is ignored.) */ public function startsBefore(mixed $date = null): bool { return $this->getStartDate()->lessThan($this->resolveCarbon($date)); } /** * Determines if the start date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsBeforeOrAt(mixed $date = null): bool { return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is after another given date. * (Rather start/end are included by options is ignored.) */ public function startsAfter(mixed $date = null): bool { return $this->getStartDate()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the start date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAfterOrAt(mixed $date = null): bool { return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAt(mixed $date = null): bool { return $this->getStartDate()->equalTo($this->resolveCarbon($date)); } /** * Determines if the end date is before another given date. * (Rather start/end are included by options is ignored.) */ public function endsBefore(mixed $date = null): bool { return $this->calculateEnd()->lessThan($this->resolveCarbon($date)); } /** * Determines if the end date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsBeforeOrAt(mixed $date = null): bool { return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is after another given date. * (Rather start/end are included by options is ignored.) */ public function endsAfter(mixed $date = null): bool { return $this->calculateEnd()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the end date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAfterOrAt(mixed $date = null): bool { return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAt(mixed $date = null): bool { return $this->calculateEnd()->equalTo($this->resolveCarbon($date)); } /** * Return true if start date is now or later. * (Rather start/end are included by options is ignored.) */ public function isStarted(): bool { return $this->startsBeforeOrAt(); } /** * Return true if end date is now or later. * (Rather start/end are included by options is ignored.) */ public function isEnded(): bool { return $this->endsBeforeOrAt(); } /** * Return true if now is between start date (included) and end date (excluded). * (Rather start/end are included by options is ignored.) */ public function isInProgress(): bool { return $this->isStarted() && !$this->isEnded(); } /** * Round the current instance at the given unit with given precision if specified and the given function. */ public function roundUnit( string $unit, DateInterval|float|int|string|null $precision = 1, callable|string $function = 'round', ): static { $self = $this->copyIfImmutable(); $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); if ($self->endDate) { $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); } /** * Truncate the current instance at the given unit with given precision if specified. */ public function floorUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. */ public function ceilUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function round( DateInterval|float|int|string|null $precision = null, callable|string $function = 'round', ): static { return $this->roundWith( $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(), $function ); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function floor(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified (else period interval is used). */ public function ceil(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'ceil'); } /** * Specify data which should be serialized to JSON. * * @link https://php.net/manual/en/jsonserializable.jsonserialize.php * * @return CarbonInterface[] */ public function jsonSerialize(): array { return $this->toArray(); } /** * Return true if the given date is between start and end. */ public function contains(mixed $date = null): bool { $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : ''); $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : ''); return $this->$startMethod($date) && $this->$endMethod($date); } /** * Return true if the current period follows a given other period (with no overlap). * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31] * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function follows(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval())); } /** * Return true if the given other period follows the current one (with no overlap). * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12] * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function isFollowedBy(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $period->follows($this); } /** * Return true if the given period either follows or is followed by the current one. * * @see follows() * @see isFollowedBy() */ public function isConsecutiveWith(mixed $period, mixed ...$arguments): bool { return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments); } public function __debugInfo(): array { $info = $this->baseDebugInfo(); unset( $info['start'], $info['end'], $info['interval'], $info['include_start_date'], $info['include_end_date'], $info['constructed'], $info["\0*\0constructed"], ); return $info; } public function __unserialize(array $data): void { try { $values = array_combine( array_map( static fn (string $key): string => preg_replace('/^\0\*\0/', '', $key), array_keys($data), ), $data, ); $this->initializeSerialization($values); foreach ($values as $key => $value) { if ($value === null) { continue; } $property = match ($key) { 'tzName' => $this->setTimezone(...), 'options' => $this->setOptions(...), 'recurrences' => $this->setRecurrences(...), 'current' => function (mixed $current): void { if (!($current instanceof CarbonInterface)) { $current = $this->resolveCarbon($current); } $this->carbonCurrent = $current; }, 'start' => 'startDate', 'interval' => $this->setDateInterval(...), 'end' => 'endDate', 'key' => null, 'include_start_date' => function (bool $included): void { $this->excludeStartDate(!$included); }, 'include_end_date' => function (bool $included): void { $this->excludeEndDate(!$included); }, default => $key, }; if ($property === null) { continue; } if (\is_callable($property)) { $property($value); continue; } if ($value instanceof DateTimeInterface && !($value instanceof CarbonInterface)) { $value = ($value instanceof DateTime) ? Carbon::instance($value) : CarbonImmutable::instance($value); } try { $this->$property = $value; } catch (Throwable) { // Must be ignored for backward-compatibility } } if (\array_key_exists('carbonRecurrences', $values)) { $this->carbonRecurrences = $values['carbonRecurrences']; } elseif (((int) ($values['recurrences'] ?? 0)) <= 1 && $this->endDate !== null) { $this->carbonRecurrences = null; } } catch (Throwable $e) { // @codeCoverageIgnoreStart if (!method_exists(parent::class, '__unserialize')) { throw $e; } parent::__unserialize($data); // @codeCoverageIgnoreEnd } } /** * Update properties after removing built-in filters. */ protected function updateInternalState(): void { if (!$this->hasFilter(static::END_DATE_FILTER)) { $this->endDate = null; } if (!$this->hasFilter(static::RECURRENCES_FILTER)) { $this->carbonRecurrences = null; } } /** * Create a filter tuple from raw parameters. * * Will create an automatic filter callback for one of Carbon's is* methods. */ protected function createFilterTuple(array $parameters): array { $method = array_shift($parameters); if (!$this->isCarbonPredicateMethod($method)) { return [$method, array_shift($parameters)]; } return [static fn ($date) => ([$date, $method])(...$parameters), $method]; } /** * Return whether given callable is a string pointing to one of Carbon's is* methods * and should be automatically converted to a filter callback. */ protected function isCarbonPredicateMethod(callable|string $callable): bool { return \is_string($callable) && str_starts_with($callable, 'is') && (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable)); } /** * Recurrences filter callback (limits number of recurrences). * * @SuppressWarnings(UnusedFormalParameter) */ protected function filterRecurrences(CarbonInterface $current, int $key): bool|callable { if ($key < $this->carbonRecurrences) { return true; } return static::END_ITERATION; } /** * End date filter callback. * * @return bool|static::END_ITERATION */ protected function filterEndDate(CarbonInterface $current): bool|callable { if (!$this->isEndExcluded() && $current == $this->endDate) { return true; } if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) { return true; } return static::END_ITERATION; } /** * End iteration filter callback. * * @return static::END_ITERATION */ protected function endIteration(): callable { return static::END_ITERATION; } /** * Handle change of the parameters. */ protected function handleChangedParameters(): void { if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { $this->dateClass = CarbonImmutable::class; } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { $this->dateClass = Carbon::class; } $this->validationResult = null; } /** * Validate current date and stop iteration when necessary. * * Returns true when current date is valid, false if it is not, or static::END_ITERATION * when iteration should be stopped. * * @return bool|static::END_ITERATION */ protected function validateCurrentDate(): bool|callable { if ($this->carbonCurrent === null) { $this->rewind(); } // Check after the first rewind to avoid repeating the initial validation. return $this->validationResult ?? ($this->validationResult = $this->checkFilters()); } /** * Check whether current value and key pass all the filters. * * @return bool|static::END_ITERATION */ protected function checkFilters(): bool|callable { $current = $this->prepareForReturn($this->carbonCurrent); foreach ($this->filters as $tuple) { $result = \call_user_func($tuple[0], $current->avoidMutation(), $this->key, $this); if ($result === static::END_ITERATION) { return static::END_ITERATION; } if (!$result) { return false; } } return true; } /** * Prepare given date to be returned to the external logic. * * @param CarbonInterface $date * * @return CarbonInterface */ protected function prepareForReturn(CarbonInterface $date) { $date = ([$this->dateClass, 'make'])($date); if ($this->timezone) { return $date->setTimezone($this->timezone); } return $date; } /** * Keep incrementing the current date until a valid date is found or the iteration is ended. * * @throws RuntimeException */ protected function incrementCurrentDateUntilValid(): void { $attempts = 0; do { $this->carbonCurrent = $this->carbonCurrent->add($this->dateInterval); $this->validationResult = null; if (++$attempts > static::NEXT_MAX_ATTEMPTS) { throw new UnreachableException('Could not find next valid date.'); } } while ($this->validateCurrentDate() === false); } /** * Call given macro. */ protected function callMacro(string $name, array $parameters): mixed { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date * * @return \Carbon\CarbonInterface */ protected function resolveCarbon($date = null) { return $this->getStartDate()->nowWithSameTz()->carbonize($date); } /** * Resolve passed arguments or DatePeriod to a CarbonPeriod object. */ protected function resolveCarbonPeriod(mixed $period, mixed ...$arguments): self { if ($period instanceof self) { return $period; } return $period instanceof DatePeriod ? static::instance($period) : static::create($period, ...$arguments); } private function orderCouple($first, $second): array { return $first > $second ? [$second, $first] : [$first, $second]; } private function makeDateTime($value): ?DateTimeInterface { if ($value instanceof DateTimeInterface) { return $value; } if ($value instanceof WeekDay || $value instanceof Month) { $dateClass = $this->dateClass; return new $dateClass($value, $this->timezoneSetting); } if (\is_string($value)) { $value = trim($value); if (!preg_match('/^P[\dT]/', $value) && !preg_match('/^R\d/', $value) && preg_match('/[a-z\d]/i', $value) ) { $dateClass = $this->dateClass; return $dateClass::parse($value, $this->timezoneSetting); } } return null; } private function isInfiniteDate($date): bool { return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); } private function rawDate($date): ?DateTimeInterface { if ($date === false || $date === null) { return null; } if ($date instanceof CarbonInterface) { return $date->isMutable() ? $date->toDateTime() : $date->toDateTimeImmutable(); } if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { return $date; } $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); } private static function setDefaultParameters(array &$parameters, array $defaults): void { foreach ($defaults as [$index, $name, $value]) { if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { $parameters[$index] = $value; } } } private function setFromAssociativeArray(array $parameters): void { if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['end'])) { $this->setEndDate($parameters['end']); } if (isset($parameters['recurrences'])) { $this->setRecurrences($parameters['recurrences']); } if (isset($parameters['interval'])) { $this->setDateInterval($parameters['interval']); } if (isset($parameters['options'])) { $this->setOptions($parameters['options']); } } private function configureTimezone(DateTimeZone $timezone, array $sortedArguments, array $originalArguments): array { $this->setTimezone($timezone); if (\is_string($originalArguments['start'] ?? null)) { $sortedArguments['start'] = $this->makeDateTime($originalArguments['start']); } if (\is_string($originalArguments['end'] ?? null)) { $sortedArguments['end'] = $this->makeDateTime($originalArguments['end']); } return $sortedArguments; } private function initializeSerialization(array $values): void { $serializationBase = [ 'start' => $values['start'] ?? $values['startDate'] ?? null, 'current' => $values['current'] ?? $values['carbonCurrent'] ?? null, 'end' => $values['end'] ?? $values['endDate'] ?? null, 'interval' => $values['interval'] ?? $values['dateInterval'] ?? null, 'recurrences' => max(1, (int) ($values['recurrences'] ?? $values['carbonRecurrences'] ?? 1)), 'include_start_date' => $values['include_start_date'] ?? true, 'include_end_date' => $values['include_end_date'] ?? false, ]; foreach (['start', 'current', 'end'] as $dateProperty) { if ($serializationBase[$dateProperty] instanceof Carbon) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTime(); } elseif ($serializationBase[$dateProperty] instanceof CarbonInterface) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTimeImmutable(); } } if ($serializationBase['interval'] instanceof CarbonInterval) { $serializationBase['interval'] = $serializationBase['interval']->toDateInterval(); } // @codeCoverageIgnoreStart if (method_exists(parent::class, '__unserialize')) { parent::__unserialize($serializationBase); return; } $excludeStart = !($values['include_start_date'] ?? true); $includeEnd = $values['include_end_date'] ?? true; parent::__construct( $serializationBase['start'], $serializationBase['interval'], $serializationBase['end'] ?? $serializationBase['recurrences'], ($excludeStart ? self::EXCLUDE_START_DATE : 0) | ($includeEnd && \defined('DatePeriod::INCLUDE_END_DATE') ? self::INCLUDE_END_DATE : 0), ); // @codeCoverageIgnoreEnd } }
PHP
{ "end_line": 1832, "name": "shiftTimezone", "signature": "public function shiftTimezone(DateTimeZone|string|int $timezone): static", "start_line": 1817 }
{ "class_name": "CarbonPeriod", "class_signature": "class CarbonPeriod implements Countable, JsonSerializable, UnitValue", "namespace": "Carbon" }
calculateEnd
Carbon/src/Carbon/CarbonPeriod.php
public function calculateEnd(?string $rounding = null): CarbonInterface { if ($end = $this->getEndDate($rounding)) { return $end; } if ($this->dateInterval->isEmpty()) { return $this->getStartDate($rounding); } $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); if ($date && $rounding) { $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); } return $date; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotACarbonClassException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnreachableException; use Carbon\Traits\DeprecatedPeriodProperties; use Carbon\Traits\IntervalRounding; use Carbon\Traits\LocalFactory; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Throwable; // @codeCoverageIgnoreStart require PHP_VERSION < 8.2 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php' : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php'; // @codeCoverageIgnoreEnd /** * Substitution of DatePeriod with some modifications and many more features. * * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. * @method static static since($date = null, $inclusive = null) Alias for start(). * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. * @method static static until($date = null, $inclusive = null) Alias for end(). * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. * @method static static times($recurrences = null) Alias for recurrences(). * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance. * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. * @method static static push($callback, $name = null) Alias for filter(). * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance. * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. * @method static static year($years = 1) Alias for years(). * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. * @method static static month($months = 1) Alias for months(). * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. * @method static static week($weeks = 1) Alias for weeks(). * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. * @method static static dayz($days = 1) Alias for days(). * @method static static day($days = 1) Alias for days(). * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. * @method static static hour($hours = 1) Alias for hours(). * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. * @method static static minute($minutes = 1) Alias for minutes(). * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. * @method static static second($seconds = 1) Alias for seconds(). * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * * @mixin DeprecatedPeriodProperties * * @SuppressWarnings(TooManyFields) * @SuppressWarnings(CamelCasePropertyName) * @SuppressWarnings(CouplingBetweenObjects) */ class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue { use LocalFactory; use IntervalRounding; use Mixin { Mixin::mixin as baseMixin; } use Options { Options::__debugInfo as baseDebugInfo; } use ToStringFormat; /** * Built-in filter for limit by recurrences. * * @var callable */ public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; /** * Built-in filter for limit to an end. * * @var callable */ public const END_DATE_FILTER = [self::class, 'filterEndDate']; /** * Special value which can be returned by filters to end iteration. Also a filter. * * @var callable */ public const END_ITERATION = [self::class, 'endIteration']; /** * Exclude end date from iteration. * * @var int */ public const EXCLUDE_END_DATE = 8; /** * Yield CarbonImmutable instances. * * @var int */ public const IMMUTABLE = 4; /** * Number of maximum attempts before giving up on finding next valid date. * * @var int */ public const NEXT_MAX_ATTEMPTS = 1000; /** * Number of maximum attempts before giving up on finding end date. * * @var int */ public const END_MAX_ATTEMPTS = 10000; /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = Carbon::class; /** * The registered macros. */ protected static array $macros = []; /** * Date class of iteration items. */ protected string $dateClass = Carbon::class; /** * Underlying date interval instance. Always present, one day by default. */ protected ?CarbonInterval $dateInterval = null; /** * True once __construct is finished. */ protected bool $constructed = false; /** * Whether current date interval was set by default. */ protected bool $isDefaultInterval = false; /** * The filters stack. */ protected array $filters = []; /** * Period start date. Applied on rewind. Always present, now by default. */ protected ?CarbonInterface $startDate = null; /** * Period end date. For inverted interval should be before the start date. Applied via a filter. */ protected ?CarbonInterface $endDate = null; /** * Limit for number of recurrences. Applied via a filter. */ protected int|float|null $carbonRecurrences = null; /** * Iteration options. */ protected ?int $options = null; /** * Index of current date. Always sequential, even if some dates are skipped by filters. * Equal to null only before the first iteration. */ protected int $key = 0; /** * Current date. May temporarily hold unaccepted value when looking for a next valid date. * Equal to null only before the first iteration. */ protected ?CarbonInterface $carbonCurrent = null; /** * Timezone of current date. Taken from the start date. */ protected ?DateTimeZone $timezone = null; /** * The cached validation result for current date. */ protected array|string|bool|null $validationResult = null; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; public function getIterator(): Generator { $this->rewind(); while ($this->valid()) { $key = $this->key(); $value = $this->current(); yield $key => $value; $this->next(); } } /** * Make a CarbonPeriod instance from given variable if possible. */ public static function make(mixed $var): ?static { try { return static::instance($var); } catch (NotAPeriodException) { return static::create($var); } } /** * Create a new instance from a DatePeriod or CarbonPeriod object. */ public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); } /** * Create a new instance. */ public static function create(...$params): static { return static::createFromArray($params); } /** * Create a new instance from an array of parameters. */ public static function createFromArray(array $params): static { return new static(...$params); } /** * Create CarbonPeriod from ISO 8601 string. */ public static function createFromIso(string $iso, ?int $options = null): static { $params = static::parseIso8601($iso); $instance = static::createFromArray($params); $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options; $instance->handleChangedParameters(); return $instance; } public static function createFromISO8601String(string $iso, ?int $options = null): static { return self::createFromIso($iso, $options); } /** * Return whether the given interval contains non-zero value of any time unit. */ protected static function intervalHasTime(DateInterval $interval): bool { return $interval->h || $interval->i || $interval->s || $interval->f; } /** * Return whether given variable is an ISO 8601 specification. * * Note: Check is very basic, as actual validation will be done later when parsing. * We just want to ensure that variable is not any other type of valid parameter. */ protected static function isIso8601(mixed $var): bool { if (!\is_string($var)) { return false; } // Match slash but not within a timezone name. $part = '[a-z]+(?:[_-][a-z]+)*'; preg_match("#\b$part/$part\b|(/)#i", $var, $match); return isset($match[1]); } /** * Parse given ISO 8601 string into an array of arguments. * * @SuppressWarnings(ElseExpression) */ protected static function parseIso8601(string $iso): array { $result = []; $interval = null; $start = null; $end = null; $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = self::makeInterval($part)) { $interval = $part; } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); } $result[] = $parsed; } return $result; } /** * Add missing parts of the target date from the source date. */ protected static function addMissingParts(string $source, string $target): string { $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); return $count ? $result : $target; } private static function makeInterval(mixed $input): ?CarbonInterval { try { return CarbonInterval::make($input); } catch (Throwable) { return null; } } private static function makeTimezone(mixed $input): ?CarbonTimeZone { if (!\is_string($input)) { return null; } try { return CarbonTimeZone::create($input); } catch (Throwable) { return null; } } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonPeriod::macro('middle', function () { * return $this->getStartDate()->average($this->getEndDate()); * }); * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonPeriod::mixin(new class { * public function addDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->addDays($count) * )->setEndDate( * $this->getEndDate()->addDays($count) * ); * }; * } * public function subDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->subDays($count) * )->setEndDate( * $this->getEndDate()->subDays($count) * ); * }; * } * }); * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); * ``` * * @throws ReflectionException */ public static function mixin(object|string $mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Provide static proxy for instance aliases. */ public static function __callStatic(string $method, array $parameters): mixed { $date = new static(); if (static::hasMacro($method)) { return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters)); } return $date->$method(...$parameters); } /** * CarbonPeriod constructor. * * @SuppressWarnings(ElseExpression) * * @throws InvalidArgumentException */ public function __construct(...$arguments) { $raw = null; if (isset($arguments['raw'])) { $raw = $arguments['raw']; $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false; if (isset($arguments['dateClass'])) { $this->dateClass = $arguments['dateClass']; } $arguments = $raw; } // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. $argumentsCount = \count($arguments); if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { array_splice($arguments, 0, 1, static::parseIso8601($iso)); } if ($argumentsCount === 1) { if ($arguments[0] instanceof self) { $arguments = [ $arguments[0]->getStartDate(), $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(), $arguments[0]->getDateInterval(), $arguments[0]->getOptions(), ]; } elseif ($arguments[0] instanceof DatePeriod) { $arguments = [ $arguments[0]->start, $arguments[0]->end ?: ($arguments[0]->recurrences - 1), $arguments[0]->interval, $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, ]; } } if (is_a($this->dateClass, DateTimeImmutable::class, true)) { $this->options = static::IMMUTABLE; } $optionsSet = false; $originalArguments = []; $sortedArguments = []; foreach ($arguments as $argument) { $parsedDate = null; if ($argument instanceof DateTimeZone) { $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments); } elseif (!isset($sortedArguments['interval']) && ( (\is_string($argument) && preg_match( '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument, )) || $argument instanceof DateInterval || $argument instanceof Closure || $argument instanceof Unit ) && $parsedInterval = self::makeInterval($argument) ) { $sortedArguments['interval'] = $parsedInterval; } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) { $sortedArguments['start'] = $parsedDate; $originalArguments['start'] = $argument; } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { $sortedArguments['end'] = $parsedDate; $originalArguments['end'] = $argument; } elseif (!isset($sortedArguments['recurrences']) && !isset($sortedArguments['end']) && (\is_int($argument) || \is_float($argument)) && $argument >= 0 ) { $sortedArguments['recurrences'] = $argument; } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { $optionsSet = true; $sortedArguments['options'] = (((int) $this->options) | ((int) $argument)); } elseif ($parsedTimezone = self::makeTimezone($argument)) { $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($raw === null && isset($sortedArguments['start'])) { $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1); if (\is_float($end)) { $end = $end === INF ? PHP_INT_MAX : (int) round($end); } $raw = [ $sortedArguments['start'], $sortedArguments['interval'] ?? CarbonInterval::day(), $end, ]; } $this->setFromAssociativeArray($sortedArguments); if ($this->startDate === null) { $dateClass = $this->dateClass; $this->setStartDate($dateClass::now()); } if ($this->dateInterval === null) { $this->setDateInterval(CarbonInterval::day()); $this->isDefaultInterval = true; } if ($this->options === null) { $this->setOptions(0); } parent::__construct( $this->startDate, $this->dateInterval, $this->endDate ?? max(1, min(2147483639, $this->recurrences ?? 1)), $this->options, ); $this->constructed = true; } /** * Get a copy of the instance. */ public function copy(): static { return clone $this; } /** * Prepare the instance to be set (self if mutable to be mutated, * copy if immutable to generate a new instance). */ protected function copyIfImmutable(): static { return $this; } /** * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. */ protected function getGetter(string $name): ?callable { return match (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) { 'start', 'start_date' => [$this, 'getStartDate'], 'end', 'end_date' => [$this, 'getEndDate'], 'interval', 'date_interval' => [$this, 'getDateInterval'], 'recurrences' => [$this, 'getRecurrences'], 'include_start_date' => [$this, 'isStartIncluded'], 'include_end_date' => [$this, 'isEndIncluded'], 'current' => [$this, 'current'], 'locale' => [$this, 'locale'], 'tzname', 'tz_name' => fn () => match (true) { $this->timezoneSetting === null => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, $this->timezoneSetting instanceof DateTimeZone => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, default => null, }; } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function get(string $name) { $getter = $this->getGetter($name); if ($getter) { return $getter(); } throw new UnknownGetterException($name); } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function __get(string $name) { return $this->get($name); } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset(string $name): bool { return $this->getGetter($name) !== null; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Set the iteration item class. * * @param string $dateClass * * @return static */ public function setDateClass(string $dateClass) { if (!is_a($dateClass, CarbonInterface::class, true)) { throw new NotACarbonClassException($dateClass); } $self = $this->copyIfImmutable(); $self->dateClass = $dateClass; if (is_a($dateClass, Carbon::class, true)) { $self->options = $self->options & ~static::IMMUTABLE; } elseif (is_a($dateClass, CarbonImmutable::class, true)) { $self->options = $self->options | static::IMMUTABLE; } return $self; } /** * Returns iteration item date class. * * @return string */ public function getDateClass(): string { return $this->dateClass; } /** * Change the period date interval. * * @param DateInterval|Unit|string|int $interval * @param Unit|string $unit the unit of $interval if it's a number * * @throws InvalidIntervalException * * @return static */ public function setDateInterval(mixed $interval, Unit|string|null $unit = null): static { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->name; } if (!$interval = CarbonInterval::make($interval, $unit)) { throw new InvalidIntervalException('Invalid interval.'); } if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) { throw new InvalidIntervalException('Empty interval is not accepted.'); } $self = $this->copyIfImmutable(); $self->dateInterval = $interval; $self->isDefaultInterval = false; $self->handleChangedParameters(); return $self; } /** * Reset the date interval to the default value. * * Difference with simply setting interval to 1-day is that P1D will not appear when calling toIso8601String() * and also next adding to the interval won't include the default 1-day. */ public function resetDateInterval(): static { $self = $this->copyIfImmutable(); $self->setDateInterval(CarbonInterval::day()); $self->isDefaultInterval = true; return $self; } /** * Invert the period date interval. */ public function invertDateInterval(): static { return $this->setDateInterval($this->dateInterval->invert()); } /** * Set start and end date. * * @param DateTime|DateTimeInterface|string $start * @param DateTime|DateTimeInterface|string|null $end * * @return static */ public function setDates(mixed $start, mixed $end): static { return $this->setStartDate($start)->setEndDate($end); } /** * Change the period options. * * @param int|null $options * * @return static */ public function setOptions(?int $options): static { $self = $this->copyIfImmutable(); $self->options = $options ?? 0; $self->handleChangedParameters(); return $self; } /** * Get the period options. */ public function getOptions(): int { return $this->options ?? 0; } /** * Toggle given options on or off. * * @param int $options * @param bool|null $state * * @throws InvalidArgumentException * * @return static */ public function toggleOptions(int $options, ?bool $state = null): static { $self = $this->copyIfImmutable(); if ($state === null) { $state = ($this->options & $options) !== $options; } return $self->setOptions( $state ? $this->options | $options : $this->options & ~$options, ); } /** * Toggle EXCLUDE_START_DATE option. */ public function excludeStartDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_START_DATE, $state); } /** * Toggle EXCLUDE_END_DATE option. */ public function excludeEndDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_END_DATE, $state); } /** * Get the underlying date interval. */ public function getDateInterval(): CarbonInterval { return $this->dateInterval->copy(); } /** * Get start date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getStartDate(?string $rounding = null): CarbonInterface { $date = $this->startDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get end date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getEndDate(?string $rounding = null): ?CarbonInterface { if (!$this->endDate) { return null; } $date = $this->endDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get number of recurrences. */ #[ReturnTypeWillChange] public function getRecurrences(): int|float|null { return $this->carbonRecurrences; } /** * Returns true if the start date should be excluded. */ public function isStartExcluded(): bool { return ($this->options & static::EXCLUDE_START_DATE) !== 0; } /** * Returns true if the end date should be excluded. */ public function isEndExcluded(): bool { return ($this->options & static::EXCLUDE_END_DATE) !== 0; } /** * Returns true if the start date should be included. */ public function isStartIncluded(): bool { return !$this->isStartExcluded(); } /** * Returns true if the end date should be included. */ public function isEndIncluded(): bool { return !$this->isEndExcluded(); } /** * Return the start if it's included by option, else return the start + 1 period interval. */ public function getIncludedStartDate(): CarbonInterface { $start = $this->getStartDate(); if ($this->isStartExcluded()) { return $start->add($this->getDateInterval()); } return $start; } /** * Return the end if it's included by option, else return the end - 1 period interval. * Warning: if the period has no fixed end, this method will iterate the period to calculate it. */ public function getIncludedEndDate(): CarbonInterface { $end = $this->getEndDate(); if (!$end) { return $this->calculateEnd(); } if ($this->isEndExcluded()) { return $end->sub($this->getDateInterval()); } return $end; } /** * Add a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function addFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); $self->filters[] = $tuple; $self->handleChangedParameters(); return $self; } /** * Prepend a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function prependFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); array_unshift($self->filters, $tuple); $self->handleChangedParameters(); return $self; } /** * Remove a filter by instance or name. */ public function removeFilter(callable|string $filter): static { $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; $self->filters = array_values(array_filter( $this->filters, static fn ($tuple) => $tuple[$key] !== $filter, )); $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Return whether given instance or name is in the filter stack. */ public function hasFilter(callable|string $filter): bool { $key = \is_callable($filter) ? 0 : 1; foreach ($this->filters as $tuple) { if ($tuple[$key] === $filter) { return true; } } return false; } /** * Get filters stack. */ public function getFilters(): array { return $this->filters; } /** * Set filters stack. */ public function setFilters(array $filters): static { $self = $this->copyIfImmutable(); $self->filters = $filters; $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Reset filters stack. */ public function resetFilters(): static { $self = $this->copyIfImmutable(); $self->filters = []; if ($self->endDate !== null) { $self->filters[] = [static::END_DATE_FILTER, null]; } if ($self->carbonRecurrences !== null) { $self->filters[] = [static::RECURRENCES_FILTER, null]; } $self->handleChangedParameters(); return $self; } /** * Add a recurrences filter (set maximum number of recurrences). * * @throws InvalidArgumentException */ public function setRecurrences(int|float|null $recurrences): static { if ($recurrences === null) { return $this->removeFilter(static::RECURRENCES_FILTER); } if ($recurrences < 0) { throw new InvalidPeriodParameterException('Invalid number of recurrences.'); } /** @var self $self */ $self = $this->copyIfImmutable(); $self->carbonRecurrences = $recurrences === INF ? INF : (int) $recurrences; if (!$self->hasFilter(static::RECURRENCES_FILTER)) { return $self->addFilter(static::RECURRENCES_FILTER); } $self->handleChangedParameters(); return $self; } /** * Change the period start date. * * @param DateTime|DateTimeInterface|string $date * @param bool|null $inclusive * * @throws InvalidPeriodDateException * * @return static */ public function setStartDate(mixed $date, ?bool $inclusive = null): static { if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date, $this->timezone))) { throw new InvalidPeriodDateException('Invalid start date.'); } $self = $this->copyIfImmutable(); $self->startDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); } return $self; } /** * Change the period end date. * * @param DateTime|DateTimeInterface|string|null $date * @param bool|null $inclusive * * @throws \InvalidArgumentException * * @return static */ public function setEndDate(mixed $date, ?bool $inclusive = null): static { if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date, $this->timezone)) { throw new InvalidPeriodDateException('Invalid end date.'); } if (!$date) { return $this->removeFilter(static::END_DATE_FILTER); } $self = $this->copyIfImmutable(); $self->endDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); } if (!$self->hasFilter(static::END_DATE_FILTER)) { return $self->addFilter(static::END_DATE_FILTER); } $self->handleChangedParameters(); return $self; } /** * Check if the current position is valid. */ public function valid(): bool { return $this->validateCurrentDate() === true; } /** * Return the current key. */ public function key(): ?int { return $this->valid() ? $this->key : null; } /** * Return the current date. */ public function current(): ?CarbonInterface { return $this->valid() ? $this->prepareForReturn($this->carbonCurrent) : null; } /** * Move forward to the next date. * * @throws RuntimeException */ public function next(): void { if ($this->carbonCurrent === null) { $this->rewind(); } if ($this->validationResult !== static::END_ITERATION) { $this->key++; $this->incrementCurrentDateUntilValid(); } } /** * Rewind to the start date. * * Iterating over a date in the UTC timezone avoids bug during backward DST change. * * @see https://bugs.php.net/bug.php?id=72255 * @see https://bugs.php.net/bug.php?id=74274 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time * * @throws RuntimeException */ public function rewind(): void { $this->key = 0; $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate); $settings = $this->getSettings(); if ($this->hasLocalTranslator()) { $settings['locale'] = $this->getTranslatorLocale(); } $this->carbonCurrent->settings($settings); $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null; if ($this->timezone) { $this->carbonCurrent = $this->carbonCurrent->utc(); } $this->validationResult = null; if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { $this->incrementCurrentDateUntilValid(); } } /** * Skip iterations and returns iteration state (false if ended, true if still valid). * * @param int $count steps number to skip (1 by default) * * @return bool */ public function skip(int $count = 1): bool { for ($i = $count; $this->valid() && $i > 0; $i--) { $this->next(); } return $this->valid(); } /** * Format the date period as ISO 8601. */ public function toIso8601String(): string { $parts = []; if ($this->carbonRecurrences !== null) { $parts[] = 'R'.$this->carbonRecurrences; } $parts[] = $this->startDate->toIso8601String(); if (!$this->isDefaultInterval) { $parts[] = $this->dateInterval->spec(); } if ($this->endDate !== null) { $parts[] = $this->endDate->toIso8601String(); } return implode('/', $parts); } /** * Convert the date period into a string. */ public function toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if ($format instanceof Closure) { return $format($this); } $translator = ([$this->dateClass, 'getTranslator'])(); $parts = []; $format = $format ?? ( !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) ? 'Y-m-d H:i:s' : 'Y-m-d' ); if ($this->carbonRecurrences !== null) { $parts[] = $this->translate('period_recurrences', [], $this->carbonRecurrences, $translator); } $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([ 'join' => true, ])], null, $translator); $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator); if ($this->endDate !== null) { $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator); } $result = implode(' ', $parts); return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1); } /** * Format the date period as ISO 8601. */ public function spec(): string { return $this->toIso8601String(); } /** * Cast the current instance into the given class. * * @param string $className The $className::instance() method will be called to cast the current object. * * @return DatePeriod|object */ public function cast(string $className): object { if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( $this->rawDate($this->getStartDate()), $this->getDateInterval(), $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0, ); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Return native DatePeriod PHP object matching the current instance. * * @example * ``` * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod()); * ``` */ public function toDatePeriod(): DatePeriod { return $this->cast(DatePeriod::class); } /** * Return `true` if the period has no custom filter and is guaranteed to be endless. * * Note that we can't check if a period is endless as soon as it has custom filters * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in * a way we can't predict without actually iterating the period. */ public function isUnfilteredAndEndLess(): bool { foreach ($this->filters as $filter) { switch ($filter) { case [static::RECURRENCES_FILTER, null]: if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) { return false; } break; case [static::END_DATE_FILTER, null]: if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { return false; } break; default: return false; } } return true; } /** * Convert the date period into an array without changing current iteration state. * * @return CarbonInterface[] */ public function toArray(): array { if ($this->isUnfilteredAndEndLess()) { throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); } $state = [ $this->key, $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null, $this->validationResult, ]; $result = iterator_to_array($this); [$this->key, $this->carbonCurrent, $this->validationResult] = $state; return $result; } /** * Count dates in the date period. */ public function count(): int { return \count($this->toArray()); } /** * Return the first date in the date period. */ public function first(): ?CarbonInterface { if ($this->isUnfilteredAndEndLess()) { foreach ($this as $date) { $this->rewind(); return $date; } return null; } return ($this->toArray() ?: [])[0] ?? null; } /** * Return the last date in the date period. */ public function last(): ?CarbonInterface { $array = $this->toArray(); return $array ? $array[\count($array) - 1] : null; } /** * Convert the date period into a string. */ public function __toString(): string { return $this->toString(); } /** * Add aliases for setters. * * CarbonPeriod::days(3)->hours(5)->invert() * ->sinceNow()->until('2010-01-10') * ->filter(...) * ->count() * * Note: We use magic method to let static and instance aliases with the same names. */ public function __call(string $method, array $parameters): mixed { if (static::hasMacro($method)) { return static::bindMacroContext($this, fn () => $this->callMacro($method, $parameters)); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } $count = \count($parameters); switch ($method) { case 'start': case 'since': if ($count === 0) { return $this->getStartDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setStartDate(...$parameters); case 'sinceNow': return $this->setStartDate(new Carbon(), ...$parameters); case 'end': case 'until': if ($count === 0) { return $this->getEndDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setEndDate(...$parameters); case 'untilNow': return $this->setEndDate(new Carbon(), ...$parameters); case 'dates': case 'between': self::setDefaultParameters($parameters, [ [0, 'start', null], [1, 'end', null], ]); return $this->setDates(...$parameters); case 'recurrences': case 'times': if ($count === 0) { return $this->getRecurrences(); } self::setDefaultParameters($parameters, [ [0, 'recurrences', null], ]); return $this->setRecurrences(...$parameters); case 'options': if ($count === 0) { return $this->getOptions(); } self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->setOptions(...$parameters); case 'toggle': self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->toggleOptions(...$parameters); case 'filter': case 'push': return $this->addFilter(...$parameters); case 'prepend': return $this->prependFilter(...$parameters); case 'filters': if ($count === 0) { return $this->getFilters(); } self::setDefaultParameters($parameters, [ [0, 'filters', []], ]); return $this->setFilters(...$parameters); case 'interval': case 'each': case 'every': case 'step': case 'stepBy': if ($count === 0) { return $this->getDateInterval(); } return $this->setDateInterval(...$parameters); case 'invert': return $this->invertDateInterval(); case 'years': case 'year': case 'months': case 'month': case 'weeks': case 'week': case 'days': case 'dayz': case 'day': case 'hours': case 'hour': case 'minutes': case 'minute': case 'seconds': case 'second': case 'milliseconds': case 'millisecond': case 'microseconds': case 'microsecond': return $this->setDateInterval(( // Override default P1D when instantiating via fluent setters. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] )(...$parameters)); } $dateClass = $this->dateClass; if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { throw new UnknownMethodException($method); } return $this; } /** * Set the instance's timezone from a string or object and apply it to start/end. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->setTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->setTimezone($timezone)); } return $self; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } return $self; } /** * Returns the end is set, else calculated from start and recurrences. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. * * @return CarbonInterface */ public function calculateEnd(?string $rounding = null): CarbonInterface { if ($end = $this->getEndDate($rounding)) { return $end; } if ($this->dateInterval->isEmpty()) { return $this->getStartDate($rounding); } $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); if ($date && $rounding) { $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); } return $date; } private function getEndFromRecurrences(): ?CarbonInterface { if ($this->carbonRecurrences === null) { throw new UnreachableException( "Could not calculate period end without either explicit end or recurrences.\n". "If you're looking for a forever-period, use ->setRecurrences(INF).", ); } if ($this->carbonRecurrences === INF) { $start = $this->getStartDate(); return $start < $start->avoidMutation()->add($this->getDateInterval()) ? CarbonImmutable::endOfTime() : CarbonImmutable::startOfTime(); } if ($this->filters === [[static::RECURRENCES_FILTER, null]]) { return $this->getStartDate()->avoidMutation()->add( $this->getDateInterval()->times( $this->carbonRecurrences - ($this->isStartExcluded() ? 0 : 1), ), ); } return null; } private function iterateUntilEnd(): ?CarbonInterface { $attempts = 0; $date = null; foreach ($this as $date) { if (++$attempts > static::END_MAX_ATTEMPTS) { throw new UnreachableException( 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.', ); } } return $date; } /** * Returns true if the current period overlaps the given one (if 1 parameter passed) * or the period between 2 dates (if 2 parameters passed). * * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd * * @return bool */ public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool { $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; if (!($range instanceof self)) { $range = static::create($range); } [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); return $end > $rangeStart && $rangeEnd > $start; } /** * Execute a given function on each date of the period. * * @example * ``` * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) { * echo $date->diffInDays('2020-12-25')." days before Christmas!\n"; * }); * ``` */ public function forEach(callable $callback): void { foreach ($this as $date) { $callback($date); } } /** * Execute a given function on each date of the period and yield the result of this function. * * @example * ``` * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24'); * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) { * return $date->diffInDays('2020-12-25').' days before Christmas!'; * }))); * ``` */ public function map(callable $callback): Generator { foreach ($this as $date) { yield $callback($date); } } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. * * @see equalTo() */ public function eq(mixed $period): bool { return $this->equalTo($period); } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. */ public function equalTo(mixed $period): bool { if (!($period instanceof self)) { $period = self::make($period); } $end = $this->getEndDate(); return $period !== null && $this->getDateInterval()->eq($period->getDateInterval()) && $this->getStartDate()->eq($period->getStartDate()) && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. * * @see notEqualTo() */ public function ne(mixed $period): bool { return $this->notEqualTo($period); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. */ public function notEqualTo(mixed $period): bool { return !$this->eq($period); } /** * Determines if the start date is before another given date. * (Rather start/end are included by options is ignored.) */ public function startsBefore(mixed $date = null): bool { return $this->getStartDate()->lessThan($this->resolveCarbon($date)); } /** * Determines if the start date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsBeforeOrAt(mixed $date = null): bool { return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is after another given date. * (Rather start/end are included by options is ignored.) */ public function startsAfter(mixed $date = null): bool { return $this->getStartDate()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the start date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAfterOrAt(mixed $date = null): bool { return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAt(mixed $date = null): bool { return $this->getStartDate()->equalTo($this->resolveCarbon($date)); } /** * Determines if the end date is before another given date. * (Rather start/end are included by options is ignored.) */ public function endsBefore(mixed $date = null): bool { return $this->calculateEnd()->lessThan($this->resolveCarbon($date)); } /** * Determines if the end date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsBeforeOrAt(mixed $date = null): bool { return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is after another given date. * (Rather start/end are included by options is ignored.) */ public function endsAfter(mixed $date = null): bool { return $this->calculateEnd()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the end date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAfterOrAt(mixed $date = null): bool { return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAt(mixed $date = null): bool { return $this->calculateEnd()->equalTo($this->resolveCarbon($date)); } /** * Return true if start date is now or later. * (Rather start/end are included by options is ignored.) */ public function isStarted(): bool { return $this->startsBeforeOrAt(); } /** * Return true if end date is now or later. * (Rather start/end are included by options is ignored.) */ public function isEnded(): bool { return $this->endsBeforeOrAt(); } /** * Return true if now is between start date (included) and end date (excluded). * (Rather start/end are included by options is ignored.) */ public function isInProgress(): bool { return $this->isStarted() && !$this->isEnded(); } /** * Round the current instance at the given unit with given precision if specified and the given function. */ public function roundUnit( string $unit, DateInterval|float|int|string|null $precision = 1, callable|string $function = 'round', ): static { $self = $this->copyIfImmutable(); $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); if ($self->endDate) { $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); } /** * Truncate the current instance at the given unit with given precision if specified. */ public function floorUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. */ public function ceilUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function round( DateInterval|float|int|string|null $precision = null, callable|string $function = 'round', ): static { return $this->roundWith( $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(), $function ); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function floor(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified (else period interval is used). */ public function ceil(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'ceil'); } /** * Specify data which should be serialized to JSON. * * @link https://php.net/manual/en/jsonserializable.jsonserialize.php * * @return CarbonInterface[] */ public function jsonSerialize(): array { return $this->toArray(); } /** * Return true if the given date is between start and end. */ public function contains(mixed $date = null): bool { $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : ''); $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : ''); return $this->$startMethod($date) && $this->$endMethod($date); } /** * Return true if the current period follows a given other period (with no overlap). * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31] * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function follows(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval())); } /** * Return true if the given other period follows the current one (with no overlap). * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12] * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function isFollowedBy(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $period->follows($this); } /** * Return true if the given period either follows or is followed by the current one. * * @see follows() * @see isFollowedBy() */ public function isConsecutiveWith(mixed $period, mixed ...$arguments): bool { return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments); } public function __debugInfo(): array { $info = $this->baseDebugInfo(); unset( $info['start'], $info['end'], $info['interval'], $info['include_start_date'], $info['include_end_date'], $info['constructed'], $info["\0*\0constructed"], ); return $info; } public function __unserialize(array $data): void { try { $values = array_combine( array_map( static fn (string $key): string => preg_replace('/^\0\*\0/', '', $key), array_keys($data), ), $data, ); $this->initializeSerialization($values); foreach ($values as $key => $value) { if ($value === null) { continue; } $property = match ($key) { 'tzName' => $this->setTimezone(...), 'options' => $this->setOptions(...), 'recurrences' => $this->setRecurrences(...), 'current' => function (mixed $current): void { if (!($current instanceof CarbonInterface)) { $current = $this->resolveCarbon($current); } $this->carbonCurrent = $current; }, 'start' => 'startDate', 'interval' => $this->setDateInterval(...), 'end' => 'endDate', 'key' => null, 'include_start_date' => function (bool $included): void { $this->excludeStartDate(!$included); }, 'include_end_date' => function (bool $included): void { $this->excludeEndDate(!$included); }, default => $key, }; if ($property === null) { continue; } if (\is_callable($property)) { $property($value); continue; } if ($value instanceof DateTimeInterface && !($value instanceof CarbonInterface)) { $value = ($value instanceof DateTime) ? Carbon::instance($value) : CarbonImmutable::instance($value); } try { $this->$property = $value; } catch (Throwable) { // Must be ignored for backward-compatibility } } if (\array_key_exists('carbonRecurrences', $values)) { $this->carbonRecurrences = $values['carbonRecurrences']; } elseif (((int) ($values['recurrences'] ?? 0)) <= 1 && $this->endDate !== null) { $this->carbonRecurrences = null; } } catch (Throwable $e) { // @codeCoverageIgnoreStart if (!method_exists(parent::class, '__unserialize')) { throw $e; } parent::__unserialize($data); // @codeCoverageIgnoreEnd } } /** * Update properties after removing built-in filters. */ protected function updateInternalState(): void { if (!$this->hasFilter(static::END_DATE_FILTER)) { $this->endDate = null; } if (!$this->hasFilter(static::RECURRENCES_FILTER)) { $this->carbonRecurrences = null; } } /** * Create a filter tuple from raw parameters. * * Will create an automatic filter callback for one of Carbon's is* methods. */ protected function createFilterTuple(array $parameters): array { $method = array_shift($parameters); if (!$this->isCarbonPredicateMethod($method)) { return [$method, array_shift($parameters)]; } return [static fn ($date) => ([$date, $method])(...$parameters), $method]; } /** * Return whether given callable is a string pointing to one of Carbon's is* methods * and should be automatically converted to a filter callback. */ protected function isCarbonPredicateMethod(callable|string $callable): bool { return \is_string($callable) && str_starts_with($callable, 'is') && (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable)); } /** * Recurrences filter callback (limits number of recurrences). * * @SuppressWarnings(UnusedFormalParameter) */ protected function filterRecurrences(CarbonInterface $current, int $key): bool|callable { if ($key < $this->carbonRecurrences) { return true; } return static::END_ITERATION; } /** * End date filter callback. * * @return bool|static::END_ITERATION */ protected function filterEndDate(CarbonInterface $current): bool|callable { if (!$this->isEndExcluded() && $current == $this->endDate) { return true; } if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) { return true; } return static::END_ITERATION; } /** * End iteration filter callback. * * @return static::END_ITERATION */ protected function endIteration(): callable { return static::END_ITERATION; } /** * Handle change of the parameters. */ protected function handleChangedParameters(): void { if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { $this->dateClass = CarbonImmutable::class; } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { $this->dateClass = Carbon::class; } $this->validationResult = null; } /** * Validate current date and stop iteration when necessary. * * Returns true when current date is valid, false if it is not, or static::END_ITERATION * when iteration should be stopped. * * @return bool|static::END_ITERATION */ protected function validateCurrentDate(): bool|callable { if ($this->carbonCurrent === null) { $this->rewind(); } // Check after the first rewind to avoid repeating the initial validation. return $this->validationResult ?? ($this->validationResult = $this->checkFilters()); } /** * Check whether current value and key pass all the filters. * * @return bool|static::END_ITERATION */ protected function checkFilters(): bool|callable { $current = $this->prepareForReturn($this->carbonCurrent); foreach ($this->filters as $tuple) { $result = \call_user_func($tuple[0], $current->avoidMutation(), $this->key, $this); if ($result === static::END_ITERATION) { return static::END_ITERATION; } if (!$result) { return false; } } return true; } /** * Prepare given date to be returned to the external logic. * * @param CarbonInterface $date * * @return CarbonInterface */ protected function prepareForReturn(CarbonInterface $date) { $date = ([$this->dateClass, 'make'])($date); if ($this->timezone) { return $date->setTimezone($this->timezone); } return $date; } /** * Keep incrementing the current date until a valid date is found or the iteration is ended. * * @throws RuntimeException */ protected function incrementCurrentDateUntilValid(): void { $attempts = 0; do { $this->carbonCurrent = $this->carbonCurrent->add($this->dateInterval); $this->validationResult = null; if (++$attempts > static::NEXT_MAX_ATTEMPTS) { throw new UnreachableException('Could not find next valid date.'); } } while ($this->validateCurrentDate() === false); } /** * Call given macro. */ protected function callMacro(string $name, array $parameters): mixed { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date * * @return \Carbon\CarbonInterface */ protected function resolveCarbon($date = null) { return $this->getStartDate()->nowWithSameTz()->carbonize($date); } /** * Resolve passed arguments or DatePeriod to a CarbonPeriod object. */ protected function resolveCarbonPeriod(mixed $period, mixed ...$arguments): self { if ($period instanceof self) { return $period; } return $period instanceof DatePeriod ? static::instance($period) : static::create($period, ...$arguments); } private function orderCouple($first, $second): array { return $first > $second ? [$second, $first] : [$first, $second]; } private function makeDateTime($value): ?DateTimeInterface { if ($value instanceof DateTimeInterface) { return $value; } if ($value instanceof WeekDay || $value instanceof Month) { $dateClass = $this->dateClass; return new $dateClass($value, $this->timezoneSetting); } if (\is_string($value)) { $value = trim($value); if (!preg_match('/^P[\dT]/', $value) && !preg_match('/^R\d/', $value) && preg_match('/[a-z\d]/i', $value) ) { $dateClass = $this->dateClass; return $dateClass::parse($value, $this->timezoneSetting); } } return null; } private function isInfiniteDate($date): bool { return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); } private function rawDate($date): ?DateTimeInterface { if ($date === false || $date === null) { return null; } if ($date instanceof CarbonInterface) { return $date->isMutable() ? $date->toDateTime() : $date->toDateTimeImmutable(); } if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { return $date; } $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); } private static function setDefaultParameters(array &$parameters, array $defaults): void { foreach ($defaults as [$index, $name, $value]) { if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { $parameters[$index] = $value; } } } private function setFromAssociativeArray(array $parameters): void { if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['end'])) { $this->setEndDate($parameters['end']); } if (isset($parameters['recurrences'])) { $this->setRecurrences($parameters['recurrences']); } if (isset($parameters['interval'])) { $this->setDateInterval($parameters['interval']); } if (isset($parameters['options'])) { $this->setOptions($parameters['options']); } } private function configureTimezone(DateTimeZone $timezone, array $sortedArguments, array $originalArguments): array { $this->setTimezone($timezone); if (\is_string($originalArguments['start'] ?? null)) { $sortedArguments['start'] = $this->makeDateTime($originalArguments['start']); } if (\is_string($originalArguments['end'] ?? null)) { $sortedArguments['end'] = $this->makeDateTime($originalArguments['end']); } return $sortedArguments; } private function initializeSerialization(array $values): void { $serializationBase = [ 'start' => $values['start'] ?? $values['startDate'] ?? null, 'current' => $values['current'] ?? $values['carbonCurrent'] ?? null, 'end' => $values['end'] ?? $values['endDate'] ?? null, 'interval' => $values['interval'] ?? $values['dateInterval'] ?? null, 'recurrences' => max(1, (int) ($values['recurrences'] ?? $values['carbonRecurrences'] ?? 1)), 'include_start_date' => $values['include_start_date'] ?? true, 'include_end_date' => $values['include_end_date'] ?? false, ]; foreach (['start', 'current', 'end'] as $dateProperty) { if ($serializationBase[$dateProperty] instanceof Carbon) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTime(); } elseif ($serializationBase[$dateProperty] instanceof CarbonInterface) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTimeImmutable(); } } if ($serializationBase['interval'] instanceof CarbonInterval) { $serializationBase['interval'] = $serializationBase['interval']->toDateInterval(); } // @codeCoverageIgnoreStart if (method_exists(parent::class, '__unserialize')) { parent::__unserialize($serializationBase); return; } $excludeStart = !($values['include_start_date'] ?? true); $includeEnd = $values['include_end_date'] ?? true; parent::__construct( $serializationBase['start'], $serializationBase['interval'], $serializationBase['end'] ?? $serializationBase['recurrences'], ($excludeStart ? self::EXCLUDE_START_DATE : 0) | ($includeEnd && \defined('DatePeriod::INCLUDE_END_DATE') ? self::INCLUDE_END_DATE : 0), ); // @codeCoverageIgnoreEnd } }
PHP
{ "end_line": 1858, "name": "calculateEnd", "signature": "public function calculateEnd(?string $rounding = null): CarbonInterface", "start_line": 1841 }
{ "class_name": "CarbonPeriod", "class_signature": "class CarbonPeriod implements Countable, JsonSerializable, UnitValue", "namespace": "Carbon" }
overlaps
Carbon/src/Carbon/CarbonPeriod.php
public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool { $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; if (!($range instanceof self)) { $range = static::create($range); } [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); return $end > $rangeStart && $rangeEnd > $start; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotACarbonClassException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnreachableException; use Carbon\Traits\DeprecatedPeriodProperties; use Carbon\Traits\IntervalRounding; use Carbon\Traits\LocalFactory; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Throwable; // @codeCoverageIgnoreStart require PHP_VERSION < 8.2 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php' : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php'; // @codeCoverageIgnoreEnd /** * Substitution of DatePeriod with some modifications and many more features. * * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. * @method static static since($date = null, $inclusive = null) Alias for start(). * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. * @method static static until($date = null, $inclusive = null) Alias for end(). * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. * @method static static times($recurrences = null) Alias for recurrences(). * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance. * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. * @method static static push($callback, $name = null) Alias for filter(). * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance. * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. * @method static static year($years = 1) Alias for years(). * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. * @method static static month($months = 1) Alias for months(). * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. * @method static static week($weeks = 1) Alias for weeks(). * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. * @method static static dayz($days = 1) Alias for days(). * @method static static day($days = 1) Alias for days(). * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. * @method static static hour($hours = 1) Alias for hours(). * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. * @method static static minute($minutes = 1) Alias for minutes(). * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. * @method static static second($seconds = 1) Alias for seconds(). * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * * @mixin DeprecatedPeriodProperties * * @SuppressWarnings(TooManyFields) * @SuppressWarnings(CamelCasePropertyName) * @SuppressWarnings(CouplingBetweenObjects) */ class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue { use LocalFactory; use IntervalRounding; use Mixin { Mixin::mixin as baseMixin; } use Options { Options::__debugInfo as baseDebugInfo; } use ToStringFormat; /** * Built-in filter for limit by recurrences. * * @var callable */ public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; /** * Built-in filter for limit to an end. * * @var callable */ public const END_DATE_FILTER = [self::class, 'filterEndDate']; /** * Special value which can be returned by filters to end iteration. Also a filter. * * @var callable */ public const END_ITERATION = [self::class, 'endIteration']; /** * Exclude end date from iteration. * * @var int */ public const EXCLUDE_END_DATE = 8; /** * Yield CarbonImmutable instances. * * @var int */ public const IMMUTABLE = 4; /** * Number of maximum attempts before giving up on finding next valid date. * * @var int */ public const NEXT_MAX_ATTEMPTS = 1000; /** * Number of maximum attempts before giving up on finding end date. * * @var int */ public const END_MAX_ATTEMPTS = 10000; /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = Carbon::class; /** * The registered macros. */ protected static array $macros = []; /** * Date class of iteration items. */ protected string $dateClass = Carbon::class; /** * Underlying date interval instance. Always present, one day by default. */ protected ?CarbonInterval $dateInterval = null; /** * True once __construct is finished. */ protected bool $constructed = false; /** * Whether current date interval was set by default. */ protected bool $isDefaultInterval = false; /** * The filters stack. */ protected array $filters = []; /** * Period start date. Applied on rewind. Always present, now by default. */ protected ?CarbonInterface $startDate = null; /** * Period end date. For inverted interval should be before the start date. Applied via a filter. */ protected ?CarbonInterface $endDate = null; /** * Limit for number of recurrences. Applied via a filter. */ protected int|float|null $carbonRecurrences = null; /** * Iteration options. */ protected ?int $options = null; /** * Index of current date. Always sequential, even if some dates are skipped by filters. * Equal to null only before the first iteration. */ protected int $key = 0; /** * Current date. May temporarily hold unaccepted value when looking for a next valid date. * Equal to null only before the first iteration. */ protected ?CarbonInterface $carbonCurrent = null; /** * Timezone of current date. Taken from the start date. */ protected ?DateTimeZone $timezone = null; /** * The cached validation result for current date. */ protected array|string|bool|null $validationResult = null; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; public function getIterator(): Generator { $this->rewind(); while ($this->valid()) { $key = $this->key(); $value = $this->current(); yield $key => $value; $this->next(); } } /** * Make a CarbonPeriod instance from given variable if possible. */ public static function make(mixed $var): ?static { try { return static::instance($var); } catch (NotAPeriodException) { return static::create($var); } } /** * Create a new instance from a DatePeriod or CarbonPeriod object. */ public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); } /** * Create a new instance. */ public static function create(...$params): static { return static::createFromArray($params); } /** * Create a new instance from an array of parameters. */ public static function createFromArray(array $params): static { return new static(...$params); } /** * Create CarbonPeriod from ISO 8601 string. */ public static function createFromIso(string $iso, ?int $options = null): static { $params = static::parseIso8601($iso); $instance = static::createFromArray($params); $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options; $instance->handleChangedParameters(); return $instance; } public static function createFromISO8601String(string $iso, ?int $options = null): static { return self::createFromIso($iso, $options); } /** * Return whether the given interval contains non-zero value of any time unit. */ protected static function intervalHasTime(DateInterval $interval): bool { return $interval->h || $interval->i || $interval->s || $interval->f; } /** * Return whether given variable is an ISO 8601 specification. * * Note: Check is very basic, as actual validation will be done later when parsing. * We just want to ensure that variable is not any other type of valid parameter. */ protected static function isIso8601(mixed $var): bool { if (!\is_string($var)) { return false; } // Match slash but not within a timezone name. $part = '[a-z]+(?:[_-][a-z]+)*'; preg_match("#\b$part/$part\b|(/)#i", $var, $match); return isset($match[1]); } /** * Parse given ISO 8601 string into an array of arguments. * * @SuppressWarnings(ElseExpression) */ protected static function parseIso8601(string $iso): array { $result = []; $interval = null; $start = null; $end = null; $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = self::makeInterval($part)) { $interval = $part; } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); } $result[] = $parsed; } return $result; } /** * Add missing parts of the target date from the source date. */ protected static function addMissingParts(string $source, string $target): string { $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); return $count ? $result : $target; } private static function makeInterval(mixed $input): ?CarbonInterval { try { return CarbonInterval::make($input); } catch (Throwable) { return null; } } private static function makeTimezone(mixed $input): ?CarbonTimeZone { if (!\is_string($input)) { return null; } try { return CarbonTimeZone::create($input); } catch (Throwable) { return null; } } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonPeriod::macro('middle', function () { * return $this->getStartDate()->average($this->getEndDate()); * }); * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonPeriod::mixin(new class { * public function addDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->addDays($count) * )->setEndDate( * $this->getEndDate()->addDays($count) * ); * }; * } * public function subDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->subDays($count) * )->setEndDate( * $this->getEndDate()->subDays($count) * ); * }; * } * }); * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); * ``` * * @throws ReflectionException */ public static function mixin(object|string $mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Provide static proxy for instance aliases. */ public static function __callStatic(string $method, array $parameters): mixed { $date = new static(); if (static::hasMacro($method)) { return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters)); } return $date->$method(...$parameters); } /** * CarbonPeriod constructor. * * @SuppressWarnings(ElseExpression) * * @throws InvalidArgumentException */ public function __construct(...$arguments) { $raw = null; if (isset($arguments['raw'])) { $raw = $arguments['raw']; $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false; if (isset($arguments['dateClass'])) { $this->dateClass = $arguments['dateClass']; } $arguments = $raw; } // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. $argumentsCount = \count($arguments); if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { array_splice($arguments, 0, 1, static::parseIso8601($iso)); } if ($argumentsCount === 1) { if ($arguments[0] instanceof self) { $arguments = [ $arguments[0]->getStartDate(), $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(), $arguments[0]->getDateInterval(), $arguments[0]->getOptions(), ]; } elseif ($arguments[0] instanceof DatePeriod) { $arguments = [ $arguments[0]->start, $arguments[0]->end ?: ($arguments[0]->recurrences - 1), $arguments[0]->interval, $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, ]; } } if (is_a($this->dateClass, DateTimeImmutable::class, true)) { $this->options = static::IMMUTABLE; } $optionsSet = false; $originalArguments = []; $sortedArguments = []; foreach ($arguments as $argument) { $parsedDate = null; if ($argument instanceof DateTimeZone) { $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments); } elseif (!isset($sortedArguments['interval']) && ( (\is_string($argument) && preg_match( '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument, )) || $argument instanceof DateInterval || $argument instanceof Closure || $argument instanceof Unit ) && $parsedInterval = self::makeInterval($argument) ) { $sortedArguments['interval'] = $parsedInterval; } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) { $sortedArguments['start'] = $parsedDate; $originalArguments['start'] = $argument; } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { $sortedArguments['end'] = $parsedDate; $originalArguments['end'] = $argument; } elseif (!isset($sortedArguments['recurrences']) && !isset($sortedArguments['end']) && (\is_int($argument) || \is_float($argument)) && $argument >= 0 ) { $sortedArguments['recurrences'] = $argument; } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { $optionsSet = true; $sortedArguments['options'] = (((int) $this->options) | ((int) $argument)); } elseif ($parsedTimezone = self::makeTimezone($argument)) { $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($raw === null && isset($sortedArguments['start'])) { $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1); if (\is_float($end)) { $end = $end === INF ? PHP_INT_MAX : (int) round($end); } $raw = [ $sortedArguments['start'], $sortedArguments['interval'] ?? CarbonInterval::day(), $end, ]; } $this->setFromAssociativeArray($sortedArguments); if ($this->startDate === null) { $dateClass = $this->dateClass; $this->setStartDate($dateClass::now()); } if ($this->dateInterval === null) { $this->setDateInterval(CarbonInterval::day()); $this->isDefaultInterval = true; } if ($this->options === null) { $this->setOptions(0); } parent::__construct( $this->startDate, $this->dateInterval, $this->endDate ?? max(1, min(2147483639, $this->recurrences ?? 1)), $this->options, ); $this->constructed = true; } /** * Get a copy of the instance. */ public function copy(): static { return clone $this; } /** * Prepare the instance to be set (self if mutable to be mutated, * copy if immutable to generate a new instance). */ protected function copyIfImmutable(): static { return $this; } /** * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. */ protected function getGetter(string $name): ?callable { return match (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) { 'start', 'start_date' => [$this, 'getStartDate'], 'end', 'end_date' => [$this, 'getEndDate'], 'interval', 'date_interval' => [$this, 'getDateInterval'], 'recurrences' => [$this, 'getRecurrences'], 'include_start_date' => [$this, 'isStartIncluded'], 'include_end_date' => [$this, 'isEndIncluded'], 'current' => [$this, 'current'], 'locale' => [$this, 'locale'], 'tzname', 'tz_name' => fn () => match (true) { $this->timezoneSetting === null => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, $this->timezoneSetting instanceof DateTimeZone => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, default => null, }; } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function get(string $name) { $getter = $this->getGetter($name); if ($getter) { return $getter(); } throw new UnknownGetterException($name); } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function __get(string $name) { return $this->get($name); } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset(string $name): bool { return $this->getGetter($name) !== null; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Set the iteration item class. * * @param string $dateClass * * @return static */ public function setDateClass(string $dateClass) { if (!is_a($dateClass, CarbonInterface::class, true)) { throw new NotACarbonClassException($dateClass); } $self = $this->copyIfImmutable(); $self->dateClass = $dateClass; if (is_a($dateClass, Carbon::class, true)) { $self->options = $self->options & ~static::IMMUTABLE; } elseif (is_a($dateClass, CarbonImmutable::class, true)) { $self->options = $self->options | static::IMMUTABLE; } return $self; } /** * Returns iteration item date class. * * @return string */ public function getDateClass(): string { return $this->dateClass; } /** * Change the period date interval. * * @param DateInterval|Unit|string|int $interval * @param Unit|string $unit the unit of $interval if it's a number * * @throws InvalidIntervalException * * @return static */ public function setDateInterval(mixed $interval, Unit|string|null $unit = null): static { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->name; } if (!$interval = CarbonInterval::make($interval, $unit)) { throw new InvalidIntervalException('Invalid interval.'); } if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) { throw new InvalidIntervalException('Empty interval is not accepted.'); } $self = $this->copyIfImmutable(); $self->dateInterval = $interval; $self->isDefaultInterval = false; $self->handleChangedParameters(); return $self; } /** * Reset the date interval to the default value. * * Difference with simply setting interval to 1-day is that P1D will not appear when calling toIso8601String() * and also next adding to the interval won't include the default 1-day. */ public function resetDateInterval(): static { $self = $this->copyIfImmutable(); $self->setDateInterval(CarbonInterval::day()); $self->isDefaultInterval = true; return $self; } /** * Invert the period date interval. */ public function invertDateInterval(): static { return $this->setDateInterval($this->dateInterval->invert()); } /** * Set start and end date. * * @param DateTime|DateTimeInterface|string $start * @param DateTime|DateTimeInterface|string|null $end * * @return static */ public function setDates(mixed $start, mixed $end): static { return $this->setStartDate($start)->setEndDate($end); } /** * Change the period options. * * @param int|null $options * * @return static */ public function setOptions(?int $options): static { $self = $this->copyIfImmutable(); $self->options = $options ?? 0; $self->handleChangedParameters(); return $self; } /** * Get the period options. */ public function getOptions(): int { return $this->options ?? 0; } /** * Toggle given options on or off. * * @param int $options * @param bool|null $state * * @throws InvalidArgumentException * * @return static */ public function toggleOptions(int $options, ?bool $state = null): static { $self = $this->copyIfImmutable(); if ($state === null) { $state = ($this->options & $options) !== $options; } return $self->setOptions( $state ? $this->options | $options : $this->options & ~$options, ); } /** * Toggle EXCLUDE_START_DATE option. */ public function excludeStartDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_START_DATE, $state); } /** * Toggle EXCLUDE_END_DATE option. */ public function excludeEndDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_END_DATE, $state); } /** * Get the underlying date interval. */ public function getDateInterval(): CarbonInterval { return $this->dateInterval->copy(); } /** * Get start date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getStartDate(?string $rounding = null): CarbonInterface { $date = $this->startDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get end date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getEndDate(?string $rounding = null): ?CarbonInterface { if (!$this->endDate) { return null; } $date = $this->endDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get number of recurrences. */ #[ReturnTypeWillChange] public function getRecurrences(): int|float|null { return $this->carbonRecurrences; } /** * Returns true if the start date should be excluded. */ public function isStartExcluded(): bool { return ($this->options & static::EXCLUDE_START_DATE) !== 0; } /** * Returns true if the end date should be excluded. */ public function isEndExcluded(): bool { return ($this->options & static::EXCLUDE_END_DATE) !== 0; } /** * Returns true if the start date should be included. */ public function isStartIncluded(): bool { return !$this->isStartExcluded(); } /** * Returns true if the end date should be included. */ public function isEndIncluded(): bool { return !$this->isEndExcluded(); } /** * Return the start if it's included by option, else return the start + 1 period interval. */ public function getIncludedStartDate(): CarbonInterface { $start = $this->getStartDate(); if ($this->isStartExcluded()) { return $start->add($this->getDateInterval()); } return $start; } /** * Return the end if it's included by option, else return the end - 1 period interval. * Warning: if the period has no fixed end, this method will iterate the period to calculate it. */ public function getIncludedEndDate(): CarbonInterface { $end = $this->getEndDate(); if (!$end) { return $this->calculateEnd(); } if ($this->isEndExcluded()) { return $end->sub($this->getDateInterval()); } return $end; } /** * Add a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function addFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); $self->filters[] = $tuple; $self->handleChangedParameters(); return $self; } /** * Prepend a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function prependFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); array_unshift($self->filters, $tuple); $self->handleChangedParameters(); return $self; } /** * Remove a filter by instance or name. */ public function removeFilter(callable|string $filter): static { $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; $self->filters = array_values(array_filter( $this->filters, static fn ($tuple) => $tuple[$key] !== $filter, )); $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Return whether given instance or name is in the filter stack. */ public function hasFilter(callable|string $filter): bool { $key = \is_callable($filter) ? 0 : 1; foreach ($this->filters as $tuple) { if ($tuple[$key] === $filter) { return true; } } return false; } /** * Get filters stack. */ public function getFilters(): array { return $this->filters; } /** * Set filters stack. */ public function setFilters(array $filters): static { $self = $this->copyIfImmutable(); $self->filters = $filters; $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Reset filters stack. */ public function resetFilters(): static { $self = $this->copyIfImmutable(); $self->filters = []; if ($self->endDate !== null) { $self->filters[] = [static::END_DATE_FILTER, null]; } if ($self->carbonRecurrences !== null) { $self->filters[] = [static::RECURRENCES_FILTER, null]; } $self->handleChangedParameters(); return $self; } /** * Add a recurrences filter (set maximum number of recurrences). * * @throws InvalidArgumentException */ public function setRecurrences(int|float|null $recurrences): static { if ($recurrences === null) { return $this->removeFilter(static::RECURRENCES_FILTER); } if ($recurrences < 0) { throw new InvalidPeriodParameterException('Invalid number of recurrences.'); } /** @var self $self */ $self = $this->copyIfImmutable(); $self->carbonRecurrences = $recurrences === INF ? INF : (int) $recurrences; if (!$self->hasFilter(static::RECURRENCES_FILTER)) { return $self->addFilter(static::RECURRENCES_FILTER); } $self->handleChangedParameters(); return $self; } /** * Change the period start date. * * @param DateTime|DateTimeInterface|string $date * @param bool|null $inclusive * * @throws InvalidPeriodDateException * * @return static */ public function setStartDate(mixed $date, ?bool $inclusive = null): static { if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date, $this->timezone))) { throw new InvalidPeriodDateException('Invalid start date.'); } $self = $this->copyIfImmutable(); $self->startDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); } return $self; } /** * Change the period end date. * * @param DateTime|DateTimeInterface|string|null $date * @param bool|null $inclusive * * @throws \InvalidArgumentException * * @return static */ public function setEndDate(mixed $date, ?bool $inclusive = null): static { if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date, $this->timezone)) { throw new InvalidPeriodDateException('Invalid end date.'); } if (!$date) { return $this->removeFilter(static::END_DATE_FILTER); } $self = $this->copyIfImmutable(); $self->endDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); } if (!$self->hasFilter(static::END_DATE_FILTER)) { return $self->addFilter(static::END_DATE_FILTER); } $self->handleChangedParameters(); return $self; } /** * Check if the current position is valid. */ public function valid(): bool { return $this->validateCurrentDate() === true; } /** * Return the current key. */ public function key(): ?int { return $this->valid() ? $this->key : null; } /** * Return the current date. */ public function current(): ?CarbonInterface { return $this->valid() ? $this->prepareForReturn($this->carbonCurrent) : null; } /** * Move forward to the next date. * * @throws RuntimeException */ public function next(): void { if ($this->carbonCurrent === null) { $this->rewind(); } if ($this->validationResult !== static::END_ITERATION) { $this->key++; $this->incrementCurrentDateUntilValid(); } } /** * Rewind to the start date. * * Iterating over a date in the UTC timezone avoids bug during backward DST change. * * @see https://bugs.php.net/bug.php?id=72255 * @see https://bugs.php.net/bug.php?id=74274 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time * * @throws RuntimeException */ public function rewind(): void { $this->key = 0; $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate); $settings = $this->getSettings(); if ($this->hasLocalTranslator()) { $settings['locale'] = $this->getTranslatorLocale(); } $this->carbonCurrent->settings($settings); $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null; if ($this->timezone) { $this->carbonCurrent = $this->carbonCurrent->utc(); } $this->validationResult = null; if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { $this->incrementCurrentDateUntilValid(); } } /** * Skip iterations and returns iteration state (false if ended, true if still valid). * * @param int $count steps number to skip (1 by default) * * @return bool */ public function skip(int $count = 1): bool { for ($i = $count; $this->valid() && $i > 0; $i--) { $this->next(); } return $this->valid(); } /** * Format the date period as ISO 8601. */ public function toIso8601String(): string { $parts = []; if ($this->carbonRecurrences !== null) { $parts[] = 'R'.$this->carbonRecurrences; } $parts[] = $this->startDate->toIso8601String(); if (!$this->isDefaultInterval) { $parts[] = $this->dateInterval->spec(); } if ($this->endDate !== null) { $parts[] = $this->endDate->toIso8601String(); } return implode('/', $parts); } /** * Convert the date period into a string. */ public function toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if ($format instanceof Closure) { return $format($this); } $translator = ([$this->dateClass, 'getTranslator'])(); $parts = []; $format = $format ?? ( !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) ? 'Y-m-d H:i:s' : 'Y-m-d' ); if ($this->carbonRecurrences !== null) { $parts[] = $this->translate('period_recurrences', [], $this->carbonRecurrences, $translator); } $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([ 'join' => true, ])], null, $translator); $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator); if ($this->endDate !== null) { $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator); } $result = implode(' ', $parts); return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1); } /** * Format the date period as ISO 8601. */ public function spec(): string { return $this->toIso8601String(); } /** * Cast the current instance into the given class. * * @param string $className The $className::instance() method will be called to cast the current object. * * @return DatePeriod|object */ public function cast(string $className): object { if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( $this->rawDate($this->getStartDate()), $this->getDateInterval(), $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0, ); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Return native DatePeriod PHP object matching the current instance. * * @example * ``` * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod()); * ``` */ public function toDatePeriod(): DatePeriod { return $this->cast(DatePeriod::class); } /** * Return `true` if the period has no custom filter and is guaranteed to be endless. * * Note that we can't check if a period is endless as soon as it has custom filters * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in * a way we can't predict without actually iterating the period. */ public function isUnfilteredAndEndLess(): bool { foreach ($this->filters as $filter) { switch ($filter) { case [static::RECURRENCES_FILTER, null]: if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) { return false; } break; case [static::END_DATE_FILTER, null]: if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { return false; } break; default: return false; } } return true; } /** * Convert the date period into an array without changing current iteration state. * * @return CarbonInterface[] */ public function toArray(): array { if ($this->isUnfilteredAndEndLess()) { throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); } $state = [ $this->key, $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null, $this->validationResult, ]; $result = iterator_to_array($this); [$this->key, $this->carbonCurrent, $this->validationResult] = $state; return $result; } /** * Count dates in the date period. */ public function count(): int { return \count($this->toArray()); } /** * Return the first date in the date period. */ public function first(): ?CarbonInterface { if ($this->isUnfilteredAndEndLess()) { foreach ($this as $date) { $this->rewind(); return $date; } return null; } return ($this->toArray() ?: [])[0] ?? null; } /** * Return the last date in the date period. */ public function last(): ?CarbonInterface { $array = $this->toArray(); return $array ? $array[\count($array) - 1] : null; } /** * Convert the date period into a string. */ public function __toString(): string { return $this->toString(); } /** * Add aliases for setters. * * CarbonPeriod::days(3)->hours(5)->invert() * ->sinceNow()->until('2010-01-10') * ->filter(...) * ->count() * * Note: We use magic method to let static and instance aliases with the same names. */ public function __call(string $method, array $parameters): mixed { if (static::hasMacro($method)) { return static::bindMacroContext($this, fn () => $this->callMacro($method, $parameters)); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } $count = \count($parameters); switch ($method) { case 'start': case 'since': if ($count === 0) { return $this->getStartDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setStartDate(...$parameters); case 'sinceNow': return $this->setStartDate(new Carbon(), ...$parameters); case 'end': case 'until': if ($count === 0) { return $this->getEndDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setEndDate(...$parameters); case 'untilNow': return $this->setEndDate(new Carbon(), ...$parameters); case 'dates': case 'between': self::setDefaultParameters($parameters, [ [0, 'start', null], [1, 'end', null], ]); return $this->setDates(...$parameters); case 'recurrences': case 'times': if ($count === 0) { return $this->getRecurrences(); } self::setDefaultParameters($parameters, [ [0, 'recurrences', null], ]); return $this->setRecurrences(...$parameters); case 'options': if ($count === 0) { return $this->getOptions(); } self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->setOptions(...$parameters); case 'toggle': self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->toggleOptions(...$parameters); case 'filter': case 'push': return $this->addFilter(...$parameters); case 'prepend': return $this->prependFilter(...$parameters); case 'filters': if ($count === 0) { return $this->getFilters(); } self::setDefaultParameters($parameters, [ [0, 'filters', []], ]); return $this->setFilters(...$parameters); case 'interval': case 'each': case 'every': case 'step': case 'stepBy': if ($count === 0) { return $this->getDateInterval(); } return $this->setDateInterval(...$parameters); case 'invert': return $this->invertDateInterval(); case 'years': case 'year': case 'months': case 'month': case 'weeks': case 'week': case 'days': case 'dayz': case 'day': case 'hours': case 'hour': case 'minutes': case 'minute': case 'seconds': case 'second': case 'milliseconds': case 'millisecond': case 'microseconds': case 'microsecond': return $this->setDateInterval(( // Override default P1D when instantiating via fluent setters. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] )(...$parameters)); } $dateClass = $this->dateClass; if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { throw new UnknownMethodException($method); } return $this; } /** * Set the instance's timezone from a string or object and apply it to start/end. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->setTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->setTimezone($timezone)); } return $self; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } return $self; } /** * Returns the end is set, else calculated from start and recurrences. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. * * @return CarbonInterface */ public function calculateEnd(?string $rounding = null): CarbonInterface { if ($end = $this->getEndDate($rounding)) { return $end; } if ($this->dateInterval->isEmpty()) { return $this->getStartDate($rounding); } $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); if ($date && $rounding) { $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); } return $date; } private function getEndFromRecurrences(): ?CarbonInterface { if ($this->carbonRecurrences === null) { throw new UnreachableException( "Could not calculate period end without either explicit end or recurrences.\n". "If you're looking for a forever-period, use ->setRecurrences(INF).", ); } if ($this->carbonRecurrences === INF) { $start = $this->getStartDate(); return $start < $start->avoidMutation()->add($this->getDateInterval()) ? CarbonImmutable::endOfTime() : CarbonImmutable::startOfTime(); } if ($this->filters === [[static::RECURRENCES_FILTER, null]]) { return $this->getStartDate()->avoidMutation()->add( $this->getDateInterval()->times( $this->carbonRecurrences - ($this->isStartExcluded() ? 0 : 1), ), ); } return null; } private function iterateUntilEnd(): ?CarbonInterface { $attempts = 0; $date = null; foreach ($this as $date) { if (++$attempts > static::END_MAX_ATTEMPTS) { throw new UnreachableException( 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.', ); } } return $date; } /** * Returns true if the current period overlaps the given one (if 1 parameter passed) * or the period between 2 dates (if 2 parameters passed). * * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd * * @return bool */ public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool { $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; if (!($range instanceof self)) { $range = static::create($range); } [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); return $end > $rangeStart && $rangeEnd > $start; } /** * Execute a given function on each date of the period. * * @example * ``` * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) { * echo $date->diffInDays('2020-12-25')." days before Christmas!\n"; * }); * ``` */ public function forEach(callable $callback): void { foreach ($this as $date) { $callback($date); } } /** * Execute a given function on each date of the period and yield the result of this function. * * @example * ``` * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24'); * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) { * return $date->diffInDays('2020-12-25').' days before Christmas!'; * }))); * ``` */ public function map(callable $callback): Generator { foreach ($this as $date) { yield $callback($date); } } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. * * @see equalTo() */ public function eq(mixed $period): bool { return $this->equalTo($period); } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. */ public function equalTo(mixed $period): bool { if (!($period instanceof self)) { $period = self::make($period); } $end = $this->getEndDate(); return $period !== null && $this->getDateInterval()->eq($period->getDateInterval()) && $this->getStartDate()->eq($period->getStartDate()) && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. * * @see notEqualTo() */ public function ne(mixed $period): bool { return $this->notEqualTo($period); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. */ public function notEqualTo(mixed $period): bool { return !$this->eq($period); } /** * Determines if the start date is before another given date. * (Rather start/end are included by options is ignored.) */ public function startsBefore(mixed $date = null): bool { return $this->getStartDate()->lessThan($this->resolveCarbon($date)); } /** * Determines if the start date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsBeforeOrAt(mixed $date = null): bool { return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is after another given date. * (Rather start/end are included by options is ignored.) */ public function startsAfter(mixed $date = null): bool { return $this->getStartDate()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the start date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAfterOrAt(mixed $date = null): bool { return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAt(mixed $date = null): bool { return $this->getStartDate()->equalTo($this->resolveCarbon($date)); } /** * Determines if the end date is before another given date. * (Rather start/end are included by options is ignored.) */ public function endsBefore(mixed $date = null): bool { return $this->calculateEnd()->lessThan($this->resolveCarbon($date)); } /** * Determines if the end date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsBeforeOrAt(mixed $date = null): bool { return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is after another given date. * (Rather start/end are included by options is ignored.) */ public function endsAfter(mixed $date = null): bool { return $this->calculateEnd()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the end date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAfterOrAt(mixed $date = null): bool { return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAt(mixed $date = null): bool { return $this->calculateEnd()->equalTo($this->resolveCarbon($date)); } /** * Return true if start date is now or later. * (Rather start/end are included by options is ignored.) */ public function isStarted(): bool { return $this->startsBeforeOrAt(); } /** * Return true if end date is now or later. * (Rather start/end are included by options is ignored.) */ public function isEnded(): bool { return $this->endsBeforeOrAt(); } /** * Return true if now is between start date (included) and end date (excluded). * (Rather start/end are included by options is ignored.) */ public function isInProgress(): bool { return $this->isStarted() && !$this->isEnded(); } /** * Round the current instance at the given unit with given precision if specified and the given function. */ public function roundUnit( string $unit, DateInterval|float|int|string|null $precision = 1, callable|string $function = 'round', ): static { $self = $this->copyIfImmutable(); $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); if ($self->endDate) { $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); } /** * Truncate the current instance at the given unit with given precision if specified. */ public function floorUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. */ public function ceilUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function round( DateInterval|float|int|string|null $precision = null, callable|string $function = 'round', ): static { return $this->roundWith( $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(), $function ); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function floor(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified (else period interval is used). */ public function ceil(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'ceil'); } /** * Specify data which should be serialized to JSON. * * @link https://php.net/manual/en/jsonserializable.jsonserialize.php * * @return CarbonInterface[] */ public function jsonSerialize(): array { return $this->toArray(); } /** * Return true if the given date is between start and end. */ public function contains(mixed $date = null): bool { $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : ''); $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : ''); return $this->$startMethod($date) && $this->$endMethod($date); } /** * Return true if the current period follows a given other period (with no overlap). * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31] * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function follows(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval())); } /** * Return true if the given other period follows the current one (with no overlap). * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12] * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function isFollowedBy(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $period->follows($this); } /** * Return true if the given period either follows or is followed by the current one. * * @see follows() * @see isFollowedBy() */ public function isConsecutiveWith(mixed $period, mixed ...$arguments): bool { return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments); } public function __debugInfo(): array { $info = $this->baseDebugInfo(); unset( $info['start'], $info['end'], $info['interval'], $info['include_start_date'], $info['include_end_date'], $info['constructed'], $info["\0*\0constructed"], ); return $info; } public function __unserialize(array $data): void { try { $values = array_combine( array_map( static fn (string $key): string => preg_replace('/^\0\*\0/', '', $key), array_keys($data), ), $data, ); $this->initializeSerialization($values); foreach ($values as $key => $value) { if ($value === null) { continue; } $property = match ($key) { 'tzName' => $this->setTimezone(...), 'options' => $this->setOptions(...), 'recurrences' => $this->setRecurrences(...), 'current' => function (mixed $current): void { if (!($current instanceof CarbonInterface)) { $current = $this->resolveCarbon($current); } $this->carbonCurrent = $current; }, 'start' => 'startDate', 'interval' => $this->setDateInterval(...), 'end' => 'endDate', 'key' => null, 'include_start_date' => function (bool $included): void { $this->excludeStartDate(!$included); }, 'include_end_date' => function (bool $included): void { $this->excludeEndDate(!$included); }, default => $key, }; if ($property === null) { continue; } if (\is_callable($property)) { $property($value); continue; } if ($value instanceof DateTimeInterface && !($value instanceof CarbonInterface)) { $value = ($value instanceof DateTime) ? Carbon::instance($value) : CarbonImmutable::instance($value); } try { $this->$property = $value; } catch (Throwable) { // Must be ignored for backward-compatibility } } if (\array_key_exists('carbonRecurrences', $values)) { $this->carbonRecurrences = $values['carbonRecurrences']; } elseif (((int) ($values['recurrences'] ?? 0)) <= 1 && $this->endDate !== null) { $this->carbonRecurrences = null; } } catch (Throwable $e) { // @codeCoverageIgnoreStart if (!method_exists(parent::class, '__unserialize')) { throw $e; } parent::__unserialize($data); // @codeCoverageIgnoreEnd } } /** * Update properties after removing built-in filters. */ protected function updateInternalState(): void { if (!$this->hasFilter(static::END_DATE_FILTER)) { $this->endDate = null; } if (!$this->hasFilter(static::RECURRENCES_FILTER)) { $this->carbonRecurrences = null; } } /** * Create a filter tuple from raw parameters. * * Will create an automatic filter callback for one of Carbon's is* methods. */ protected function createFilterTuple(array $parameters): array { $method = array_shift($parameters); if (!$this->isCarbonPredicateMethod($method)) { return [$method, array_shift($parameters)]; } return [static fn ($date) => ([$date, $method])(...$parameters), $method]; } /** * Return whether given callable is a string pointing to one of Carbon's is* methods * and should be automatically converted to a filter callback. */ protected function isCarbonPredicateMethod(callable|string $callable): bool { return \is_string($callable) && str_starts_with($callable, 'is') && (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable)); } /** * Recurrences filter callback (limits number of recurrences). * * @SuppressWarnings(UnusedFormalParameter) */ protected function filterRecurrences(CarbonInterface $current, int $key): bool|callable { if ($key < $this->carbonRecurrences) { return true; } return static::END_ITERATION; } /** * End date filter callback. * * @return bool|static::END_ITERATION */ protected function filterEndDate(CarbonInterface $current): bool|callable { if (!$this->isEndExcluded() && $current == $this->endDate) { return true; } if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) { return true; } return static::END_ITERATION; } /** * End iteration filter callback. * * @return static::END_ITERATION */ protected function endIteration(): callable { return static::END_ITERATION; } /** * Handle change of the parameters. */ protected function handleChangedParameters(): void { if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { $this->dateClass = CarbonImmutable::class; } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { $this->dateClass = Carbon::class; } $this->validationResult = null; } /** * Validate current date and stop iteration when necessary. * * Returns true when current date is valid, false if it is not, or static::END_ITERATION * when iteration should be stopped. * * @return bool|static::END_ITERATION */ protected function validateCurrentDate(): bool|callable { if ($this->carbonCurrent === null) { $this->rewind(); } // Check after the first rewind to avoid repeating the initial validation. return $this->validationResult ?? ($this->validationResult = $this->checkFilters()); } /** * Check whether current value and key pass all the filters. * * @return bool|static::END_ITERATION */ protected function checkFilters(): bool|callable { $current = $this->prepareForReturn($this->carbonCurrent); foreach ($this->filters as $tuple) { $result = \call_user_func($tuple[0], $current->avoidMutation(), $this->key, $this); if ($result === static::END_ITERATION) { return static::END_ITERATION; } if (!$result) { return false; } } return true; } /** * Prepare given date to be returned to the external logic. * * @param CarbonInterface $date * * @return CarbonInterface */ protected function prepareForReturn(CarbonInterface $date) { $date = ([$this->dateClass, 'make'])($date); if ($this->timezone) { return $date->setTimezone($this->timezone); } return $date; } /** * Keep incrementing the current date until a valid date is found or the iteration is ended. * * @throws RuntimeException */ protected function incrementCurrentDateUntilValid(): void { $attempts = 0; do { $this->carbonCurrent = $this->carbonCurrent->add($this->dateInterval); $this->validationResult = null; if (++$attempts > static::NEXT_MAX_ATTEMPTS) { throw new UnreachableException('Could not find next valid date.'); } } while ($this->validateCurrentDate() === false); } /** * Call given macro. */ protected function callMacro(string $name, array $parameters): mixed { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date * * @return \Carbon\CarbonInterface */ protected function resolveCarbon($date = null) { return $this->getStartDate()->nowWithSameTz()->carbonize($date); } /** * Resolve passed arguments or DatePeriod to a CarbonPeriod object. */ protected function resolveCarbonPeriod(mixed $period, mixed ...$arguments): self { if ($period instanceof self) { return $period; } return $period instanceof DatePeriod ? static::instance($period) : static::create($period, ...$arguments); } private function orderCouple($first, $second): array { return $first > $second ? [$second, $first] : [$first, $second]; } private function makeDateTime($value): ?DateTimeInterface { if ($value instanceof DateTimeInterface) { return $value; } if ($value instanceof WeekDay || $value instanceof Month) { $dateClass = $this->dateClass; return new $dateClass($value, $this->timezoneSetting); } if (\is_string($value)) { $value = trim($value); if (!preg_match('/^P[\dT]/', $value) && !preg_match('/^R\d/', $value) && preg_match('/[a-z\d]/i', $value) ) { $dateClass = $this->dateClass; return $dateClass::parse($value, $this->timezoneSetting); } } return null; } private function isInfiniteDate($date): bool { return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); } private function rawDate($date): ?DateTimeInterface { if ($date === false || $date === null) { return null; } if ($date instanceof CarbonInterface) { return $date->isMutable() ? $date->toDateTime() : $date->toDateTimeImmutable(); } if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { return $date; } $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); } private static function setDefaultParameters(array &$parameters, array $defaults): void { foreach ($defaults as [$index, $name, $value]) { if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { $parameters[$index] = $value; } } } private function setFromAssociativeArray(array $parameters): void { if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['end'])) { $this->setEndDate($parameters['end']); } if (isset($parameters['recurrences'])) { $this->setRecurrences($parameters['recurrences']); } if (isset($parameters['interval'])) { $this->setDateInterval($parameters['interval']); } if (isset($parameters['options'])) { $this->setOptions($parameters['options']); } } private function configureTimezone(DateTimeZone $timezone, array $sortedArguments, array $originalArguments): array { $this->setTimezone($timezone); if (\is_string($originalArguments['start'] ?? null)) { $sortedArguments['start'] = $this->makeDateTime($originalArguments['start']); } if (\is_string($originalArguments['end'] ?? null)) { $sortedArguments['end'] = $this->makeDateTime($originalArguments['end']); } return $sortedArguments; } private function initializeSerialization(array $values): void { $serializationBase = [ 'start' => $values['start'] ?? $values['startDate'] ?? null, 'current' => $values['current'] ?? $values['carbonCurrent'] ?? null, 'end' => $values['end'] ?? $values['endDate'] ?? null, 'interval' => $values['interval'] ?? $values['dateInterval'] ?? null, 'recurrences' => max(1, (int) ($values['recurrences'] ?? $values['carbonRecurrences'] ?? 1)), 'include_start_date' => $values['include_start_date'] ?? true, 'include_end_date' => $values['include_end_date'] ?? false, ]; foreach (['start', 'current', 'end'] as $dateProperty) { if ($serializationBase[$dateProperty] instanceof Carbon) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTime(); } elseif ($serializationBase[$dateProperty] instanceof CarbonInterface) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTimeImmutable(); } } if ($serializationBase['interval'] instanceof CarbonInterval) { $serializationBase['interval'] = $serializationBase['interval']->toDateInterval(); } // @codeCoverageIgnoreStart if (method_exists(parent::class, '__unserialize')) { parent::__unserialize($serializationBase); return; } $excludeStart = !($values['include_start_date'] ?? true); $includeEnd = $values['include_end_date'] ?? true; parent::__construct( $serializationBase['start'], $serializationBase['interval'], $serializationBase['end'] ?? $serializationBase['recurrences'], ($excludeStart ? self::EXCLUDE_START_DATE : 0) | ($includeEnd && \defined('DatePeriod::INCLUDE_END_DATE') ? self::INCLUDE_END_DATE : 0), ); // @codeCoverageIgnoreEnd } }
PHP
{ "end_line": 1925, "name": "overlaps", "signature": "public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool", "start_line": 1913 }
{ "class_name": "CarbonPeriod", "class_signature": "class CarbonPeriod implements Countable, JsonSerializable, UnitValue", "namespace": "Carbon" }
equalTo
Carbon/src/Carbon/CarbonPeriod.php
public function equalTo(mixed $period): bool { if (!($period instanceof self)) { $period = self::make($period); } $end = $this->getEndDate(); return $period !== null && $this->getDateInterval()->eq($period->getDateInterval()) && $this->getStartDate()->eq($period->getStartDate()) && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotACarbonClassException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnreachableException; use Carbon\Traits\DeprecatedPeriodProperties; use Carbon\Traits\IntervalRounding; use Carbon\Traits\LocalFactory; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Throwable; // @codeCoverageIgnoreStart require PHP_VERSION < 8.2 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php' : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php'; // @codeCoverageIgnoreEnd /** * Substitution of DatePeriod with some modifications and many more features. * * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. * @method static static since($date = null, $inclusive = null) Alias for start(). * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. * @method static static until($date = null, $inclusive = null) Alias for end(). * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. * @method static static times($recurrences = null) Alias for recurrences(). * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance. * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. * @method static static push($callback, $name = null) Alias for filter(). * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance. * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. * @method static static year($years = 1) Alias for years(). * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. * @method static static month($months = 1) Alias for months(). * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. * @method static static week($weeks = 1) Alias for weeks(). * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. * @method static static dayz($days = 1) Alias for days(). * @method static static day($days = 1) Alias for days(). * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. * @method static static hour($hours = 1) Alias for hours(). * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. * @method static static minute($minutes = 1) Alias for minutes(). * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. * @method static static second($seconds = 1) Alias for seconds(). * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * * @mixin DeprecatedPeriodProperties * * @SuppressWarnings(TooManyFields) * @SuppressWarnings(CamelCasePropertyName) * @SuppressWarnings(CouplingBetweenObjects) */ class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue { use LocalFactory; use IntervalRounding; use Mixin { Mixin::mixin as baseMixin; } use Options { Options::__debugInfo as baseDebugInfo; } use ToStringFormat; /** * Built-in filter for limit by recurrences. * * @var callable */ public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; /** * Built-in filter for limit to an end. * * @var callable */ public const END_DATE_FILTER = [self::class, 'filterEndDate']; /** * Special value which can be returned by filters to end iteration. Also a filter. * * @var callable */ public const END_ITERATION = [self::class, 'endIteration']; /** * Exclude end date from iteration. * * @var int */ public const EXCLUDE_END_DATE = 8; /** * Yield CarbonImmutable instances. * * @var int */ public const IMMUTABLE = 4; /** * Number of maximum attempts before giving up on finding next valid date. * * @var int */ public const NEXT_MAX_ATTEMPTS = 1000; /** * Number of maximum attempts before giving up on finding end date. * * @var int */ public const END_MAX_ATTEMPTS = 10000; /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = Carbon::class; /** * The registered macros. */ protected static array $macros = []; /** * Date class of iteration items. */ protected string $dateClass = Carbon::class; /** * Underlying date interval instance. Always present, one day by default. */ protected ?CarbonInterval $dateInterval = null; /** * True once __construct is finished. */ protected bool $constructed = false; /** * Whether current date interval was set by default. */ protected bool $isDefaultInterval = false; /** * The filters stack. */ protected array $filters = []; /** * Period start date. Applied on rewind. Always present, now by default. */ protected ?CarbonInterface $startDate = null; /** * Period end date. For inverted interval should be before the start date. Applied via a filter. */ protected ?CarbonInterface $endDate = null; /** * Limit for number of recurrences. Applied via a filter. */ protected int|float|null $carbonRecurrences = null; /** * Iteration options. */ protected ?int $options = null; /** * Index of current date. Always sequential, even if some dates are skipped by filters. * Equal to null only before the first iteration. */ protected int $key = 0; /** * Current date. May temporarily hold unaccepted value when looking for a next valid date. * Equal to null only before the first iteration. */ protected ?CarbonInterface $carbonCurrent = null; /** * Timezone of current date. Taken from the start date. */ protected ?DateTimeZone $timezone = null; /** * The cached validation result for current date. */ protected array|string|bool|null $validationResult = null; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; public function getIterator(): Generator { $this->rewind(); while ($this->valid()) { $key = $this->key(); $value = $this->current(); yield $key => $value; $this->next(); } } /** * Make a CarbonPeriod instance from given variable if possible. */ public static function make(mixed $var): ?static { try { return static::instance($var); } catch (NotAPeriodException) { return static::create($var); } } /** * Create a new instance from a DatePeriod or CarbonPeriod object. */ public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); } /** * Create a new instance. */ public static function create(...$params): static { return static::createFromArray($params); } /** * Create a new instance from an array of parameters. */ public static function createFromArray(array $params): static { return new static(...$params); } /** * Create CarbonPeriod from ISO 8601 string. */ public static function createFromIso(string $iso, ?int $options = null): static { $params = static::parseIso8601($iso); $instance = static::createFromArray($params); $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options; $instance->handleChangedParameters(); return $instance; } public static function createFromISO8601String(string $iso, ?int $options = null): static { return self::createFromIso($iso, $options); } /** * Return whether the given interval contains non-zero value of any time unit. */ protected static function intervalHasTime(DateInterval $interval): bool { return $interval->h || $interval->i || $interval->s || $interval->f; } /** * Return whether given variable is an ISO 8601 specification. * * Note: Check is very basic, as actual validation will be done later when parsing. * We just want to ensure that variable is not any other type of valid parameter. */ protected static function isIso8601(mixed $var): bool { if (!\is_string($var)) { return false; } // Match slash but not within a timezone name. $part = '[a-z]+(?:[_-][a-z]+)*'; preg_match("#\b$part/$part\b|(/)#i", $var, $match); return isset($match[1]); } /** * Parse given ISO 8601 string into an array of arguments. * * @SuppressWarnings(ElseExpression) */ protected static function parseIso8601(string $iso): array { $result = []; $interval = null; $start = null; $end = null; $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = self::makeInterval($part)) { $interval = $part; } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); } $result[] = $parsed; } return $result; } /** * Add missing parts of the target date from the source date. */ protected static function addMissingParts(string $source, string $target): string { $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); return $count ? $result : $target; } private static function makeInterval(mixed $input): ?CarbonInterval { try { return CarbonInterval::make($input); } catch (Throwable) { return null; } } private static function makeTimezone(mixed $input): ?CarbonTimeZone { if (!\is_string($input)) { return null; } try { return CarbonTimeZone::create($input); } catch (Throwable) { return null; } } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonPeriod::macro('middle', function () { * return $this->getStartDate()->average($this->getEndDate()); * }); * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonPeriod::mixin(new class { * public function addDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->addDays($count) * )->setEndDate( * $this->getEndDate()->addDays($count) * ); * }; * } * public function subDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->subDays($count) * )->setEndDate( * $this->getEndDate()->subDays($count) * ); * }; * } * }); * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); * ``` * * @throws ReflectionException */ public static function mixin(object|string $mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Provide static proxy for instance aliases. */ public static function __callStatic(string $method, array $parameters): mixed { $date = new static(); if (static::hasMacro($method)) { return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters)); } return $date->$method(...$parameters); } /** * CarbonPeriod constructor. * * @SuppressWarnings(ElseExpression) * * @throws InvalidArgumentException */ public function __construct(...$arguments) { $raw = null; if (isset($arguments['raw'])) { $raw = $arguments['raw']; $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false; if (isset($arguments['dateClass'])) { $this->dateClass = $arguments['dateClass']; } $arguments = $raw; } // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. $argumentsCount = \count($arguments); if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { array_splice($arguments, 0, 1, static::parseIso8601($iso)); } if ($argumentsCount === 1) { if ($arguments[0] instanceof self) { $arguments = [ $arguments[0]->getStartDate(), $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(), $arguments[0]->getDateInterval(), $arguments[0]->getOptions(), ]; } elseif ($arguments[0] instanceof DatePeriod) { $arguments = [ $arguments[0]->start, $arguments[0]->end ?: ($arguments[0]->recurrences - 1), $arguments[0]->interval, $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, ]; } } if (is_a($this->dateClass, DateTimeImmutable::class, true)) { $this->options = static::IMMUTABLE; } $optionsSet = false; $originalArguments = []; $sortedArguments = []; foreach ($arguments as $argument) { $parsedDate = null; if ($argument instanceof DateTimeZone) { $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments); } elseif (!isset($sortedArguments['interval']) && ( (\is_string($argument) && preg_match( '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument, )) || $argument instanceof DateInterval || $argument instanceof Closure || $argument instanceof Unit ) && $parsedInterval = self::makeInterval($argument) ) { $sortedArguments['interval'] = $parsedInterval; } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) { $sortedArguments['start'] = $parsedDate; $originalArguments['start'] = $argument; } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { $sortedArguments['end'] = $parsedDate; $originalArguments['end'] = $argument; } elseif (!isset($sortedArguments['recurrences']) && !isset($sortedArguments['end']) && (\is_int($argument) || \is_float($argument)) && $argument >= 0 ) { $sortedArguments['recurrences'] = $argument; } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { $optionsSet = true; $sortedArguments['options'] = (((int) $this->options) | ((int) $argument)); } elseif ($parsedTimezone = self::makeTimezone($argument)) { $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($raw === null && isset($sortedArguments['start'])) { $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1); if (\is_float($end)) { $end = $end === INF ? PHP_INT_MAX : (int) round($end); } $raw = [ $sortedArguments['start'], $sortedArguments['interval'] ?? CarbonInterval::day(), $end, ]; } $this->setFromAssociativeArray($sortedArguments); if ($this->startDate === null) { $dateClass = $this->dateClass; $this->setStartDate($dateClass::now()); } if ($this->dateInterval === null) { $this->setDateInterval(CarbonInterval::day()); $this->isDefaultInterval = true; } if ($this->options === null) { $this->setOptions(0); } parent::__construct( $this->startDate, $this->dateInterval, $this->endDate ?? max(1, min(2147483639, $this->recurrences ?? 1)), $this->options, ); $this->constructed = true; } /** * Get a copy of the instance. */ public function copy(): static { return clone $this; } /** * Prepare the instance to be set (self if mutable to be mutated, * copy if immutable to generate a new instance). */ protected function copyIfImmutable(): static { return $this; } /** * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. */ protected function getGetter(string $name): ?callable { return match (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) { 'start', 'start_date' => [$this, 'getStartDate'], 'end', 'end_date' => [$this, 'getEndDate'], 'interval', 'date_interval' => [$this, 'getDateInterval'], 'recurrences' => [$this, 'getRecurrences'], 'include_start_date' => [$this, 'isStartIncluded'], 'include_end_date' => [$this, 'isEndIncluded'], 'current' => [$this, 'current'], 'locale' => [$this, 'locale'], 'tzname', 'tz_name' => fn () => match (true) { $this->timezoneSetting === null => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, $this->timezoneSetting instanceof DateTimeZone => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, default => null, }; } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function get(string $name) { $getter = $this->getGetter($name); if ($getter) { return $getter(); } throw new UnknownGetterException($name); } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function __get(string $name) { return $this->get($name); } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset(string $name): bool { return $this->getGetter($name) !== null; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Set the iteration item class. * * @param string $dateClass * * @return static */ public function setDateClass(string $dateClass) { if (!is_a($dateClass, CarbonInterface::class, true)) { throw new NotACarbonClassException($dateClass); } $self = $this->copyIfImmutable(); $self->dateClass = $dateClass; if (is_a($dateClass, Carbon::class, true)) { $self->options = $self->options & ~static::IMMUTABLE; } elseif (is_a($dateClass, CarbonImmutable::class, true)) { $self->options = $self->options | static::IMMUTABLE; } return $self; } /** * Returns iteration item date class. * * @return string */ public function getDateClass(): string { return $this->dateClass; } /** * Change the period date interval. * * @param DateInterval|Unit|string|int $interval * @param Unit|string $unit the unit of $interval if it's a number * * @throws InvalidIntervalException * * @return static */ public function setDateInterval(mixed $interval, Unit|string|null $unit = null): static { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->name; } if (!$interval = CarbonInterval::make($interval, $unit)) { throw new InvalidIntervalException('Invalid interval.'); } if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) { throw new InvalidIntervalException('Empty interval is not accepted.'); } $self = $this->copyIfImmutable(); $self->dateInterval = $interval; $self->isDefaultInterval = false; $self->handleChangedParameters(); return $self; } /** * Reset the date interval to the default value. * * Difference with simply setting interval to 1-day is that P1D will not appear when calling toIso8601String() * and also next adding to the interval won't include the default 1-day. */ public function resetDateInterval(): static { $self = $this->copyIfImmutable(); $self->setDateInterval(CarbonInterval::day()); $self->isDefaultInterval = true; return $self; } /** * Invert the period date interval. */ public function invertDateInterval(): static { return $this->setDateInterval($this->dateInterval->invert()); } /** * Set start and end date. * * @param DateTime|DateTimeInterface|string $start * @param DateTime|DateTimeInterface|string|null $end * * @return static */ public function setDates(mixed $start, mixed $end): static { return $this->setStartDate($start)->setEndDate($end); } /** * Change the period options. * * @param int|null $options * * @return static */ public function setOptions(?int $options): static { $self = $this->copyIfImmutable(); $self->options = $options ?? 0; $self->handleChangedParameters(); return $self; } /** * Get the period options. */ public function getOptions(): int { return $this->options ?? 0; } /** * Toggle given options on or off. * * @param int $options * @param bool|null $state * * @throws InvalidArgumentException * * @return static */ public function toggleOptions(int $options, ?bool $state = null): static { $self = $this->copyIfImmutable(); if ($state === null) { $state = ($this->options & $options) !== $options; } return $self->setOptions( $state ? $this->options | $options : $this->options & ~$options, ); } /** * Toggle EXCLUDE_START_DATE option. */ public function excludeStartDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_START_DATE, $state); } /** * Toggle EXCLUDE_END_DATE option. */ public function excludeEndDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_END_DATE, $state); } /** * Get the underlying date interval. */ public function getDateInterval(): CarbonInterval { return $this->dateInterval->copy(); } /** * Get start date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getStartDate(?string $rounding = null): CarbonInterface { $date = $this->startDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get end date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getEndDate(?string $rounding = null): ?CarbonInterface { if (!$this->endDate) { return null; } $date = $this->endDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get number of recurrences. */ #[ReturnTypeWillChange] public function getRecurrences(): int|float|null { return $this->carbonRecurrences; } /** * Returns true if the start date should be excluded. */ public function isStartExcluded(): bool { return ($this->options & static::EXCLUDE_START_DATE) !== 0; } /** * Returns true if the end date should be excluded. */ public function isEndExcluded(): bool { return ($this->options & static::EXCLUDE_END_DATE) !== 0; } /** * Returns true if the start date should be included. */ public function isStartIncluded(): bool { return !$this->isStartExcluded(); } /** * Returns true if the end date should be included. */ public function isEndIncluded(): bool { return !$this->isEndExcluded(); } /** * Return the start if it's included by option, else return the start + 1 period interval. */ public function getIncludedStartDate(): CarbonInterface { $start = $this->getStartDate(); if ($this->isStartExcluded()) { return $start->add($this->getDateInterval()); } return $start; } /** * Return the end if it's included by option, else return the end - 1 period interval. * Warning: if the period has no fixed end, this method will iterate the period to calculate it. */ public function getIncludedEndDate(): CarbonInterface { $end = $this->getEndDate(); if (!$end) { return $this->calculateEnd(); } if ($this->isEndExcluded()) { return $end->sub($this->getDateInterval()); } return $end; } /** * Add a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function addFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); $self->filters[] = $tuple; $self->handleChangedParameters(); return $self; } /** * Prepend a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function prependFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); array_unshift($self->filters, $tuple); $self->handleChangedParameters(); return $self; } /** * Remove a filter by instance or name. */ public function removeFilter(callable|string $filter): static { $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; $self->filters = array_values(array_filter( $this->filters, static fn ($tuple) => $tuple[$key] !== $filter, )); $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Return whether given instance or name is in the filter stack. */ public function hasFilter(callable|string $filter): bool { $key = \is_callable($filter) ? 0 : 1; foreach ($this->filters as $tuple) { if ($tuple[$key] === $filter) { return true; } } return false; } /** * Get filters stack. */ public function getFilters(): array { return $this->filters; } /** * Set filters stack. */ public function setFilters(array $filters): static { $self = $this->copyIfImmutable(); $self->filters = $filters; $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Reset filters stack. */ public function resetFilters(): static { $self = $this->copyIfImmutable(); $self->filters = []; if ($self->endDate !== null) { $self->filters[] = [static::END_DATE_FILTER, null]; } if ($self->carbonRecurrences !== null) { $self->filters[] = [static::RECURRENCES_FILTER, null]; } $self->handleChangedParameters(); return $self; } /** * Add a recurrences filter (set maximum number of recurrences). * * @throws InvalidArgumentException */ public function setRecurrences(int|float|null $recurrences): static { if ($recurrences === null) { return $this->removeFilter(static::RECURRENCES_FILTER); } if ($recurrences < 0) { throw new InvalidPeriodParameterException('Invalid number of recurrences.'); } /** @var self $self */ $self = $this->copyIfImmutable(); $self->carbonRecurrences = $recurrences === INF ? INF : (int) $recurrences; if (!$self->hasFilter(static::RECURRENCES_FILTER)) { return $self->addFilter(static::RECURRENCES_FILTER); } $self->handleChangedParameters(); return $self; } /** * Change the period start date. * * @param DateTime|DateTimeInterface|string $date * @param bool|null $inclusive * * @throws InvalidPeriodDateException * * @return static */ public function setStartDate(mixed $date, ?bool $inclusive = null): static { if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date, $this->timezone))) { throw new InvalidPeriodDateException('Invalid start date.'); } $self = $this->copyIfImmutable(); $self->startDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); } return $self; } /** * Change the period end date. * * @param DateTime|DateTimeInterface|string|null $date * @param bool|null $inclusive * * @throws \InvalidArgumentException * * @return static */ public function setEndDate(mixed $date, ?bool $inclusive = null): static { if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date, $this->timezone)) { throw new InvalidPeriodDateException('Invalid end date.'); } if (!$date) { return $this->removeFilter(static::END_DATE_FILTER); } $self = $this->copyIfImmutable(); $self->endDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); } if (!$self->hasFilter(static::END_DATE_FILTER)) { return $self->addFilter(static::END_DATE_FILTER); } $self->handleChangedParameters(); return $self; } /** * Check if the current position is valid. */ public function valid(): bool { return $this->validateCurrentDate() === true; } /** * Return the current key. */ public function key(): ?int { return $this->valid() ? $this->key : null; } /** * Return the current date. */ public function current(): ?CarbonInterface { return $this->valid() ? $this->prepareForReturn($this->carbonCurrent) : null; } /** * Move forward to the next date. * * @throws RuntimeException */ public function next(): void { if ($this->carbonCurrent === null) { $this->rewind(); } if ($this->validationResult !== static::END_ITERATION) { $this->key++; $this->incrementCurrentDateUntilValid(); } } /** * Rewind to the start date. * * Iterating over a date in the UTC timezone avoids bug during backward DST change. * * @see https://bugs.php.net/bug.php?id=72255 * @see https://bugs.php.net/bug.php?id=74274 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time * * @throws RuntimeException */ public function rewind(): void { $this->key = 0; $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate); $settings = $this->getSettings(); if ($this->hasLocalTranslator()) { $settings['locale'] = $this->getTranslatorLocale(); } $this->carbonCurrent->settings($settings); $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null; if ($this->timezone) { $this->carbonCurrent = $this->carbonCurrent->utc(); } $this->validationResult = null; if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { $this->incrementCurrentDateUntilValid(); } } /** * Skip iterations and returns iteration state (false if ended, true if still valid). * * @param int $count steps number to skip (1 by default) * * @return bool */ public function skip(int $count = 1): bool { for ($i = $count; $this->valid() && $i > 0; $i--) { $this->next(); } return $this->valid(); } /** * Format the date period as ISO 8601. */ public function toIso8601String(): string { $parts = []; if ($this->carbonRecurrences !== null) { $parts[] = 'R'.$this->carbonRecurrences; } $parts[] = $this->startDate->toIso8601String(); if (!$this->isDefaultInterval) { $parts[] = $this->dateInterval->spec(); } if ($this->endDate !== null) { $parts[] = $this->endDate->toIso8601String(); } return implode('/', $parts); } /** * Convert the date period into a string. */ public function toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if ($format instanceof Closure) { return $format($this); } $translator = ([$this->dateClass, 'getTranslator'])(); $parts = []; $format = $format ?? ( !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) ? 'Y-m-d H:i:s' : 'Y-m-d' ); if ($this->carbonRecurrences !== null) { $parts[] = $this->translate('period_recurrences', [], $this->carbonRecurrences, $translator); } $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([ 'join' => true, ])], null, $translator); $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator); if ($this->endDate !== null) { $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator); } $result = implode(' ', $parts); return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1); } /** * Format the date period as ISO 8601. */ public function spec(): string { return $this->toIso8601String(); } /** * Cast the current instance into the given class. * * @param string $className The $className::instance() method will be called to cast the current object. * * @return DatePeriod|object */ public function cast(string $className): object { if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( $this->rawDate($this->getStartDate()), $this->getDateInterval(), $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0, ); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Return native DatePeriod PHP object matching the current instance. * * @example * ``` * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod()); * ``` */ public function toDatePeriod(): DatePeriod { return $this->cast(DatePeriod::class); } /** * Return `true` if the period has no custom filter and is guaranteed to be endless. * * Note that we can't check if a period is endless as soon as it has custom filters * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in * a way we can't predict without actually iterating the period. */ public function isUnfilteredAndEndLess(): bool { foreach ($this->filters as $filter) { switch ($filter) { case [static::RECURRENCES_FILTER, null]: if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) { return false; } break; case [static::END_DATE_FILTER, null]: if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { return false; } break; default: return false; } } return true; } /** * Convert the date period into an array without changing current iteration state. * * @return CarbonInterface[] */ public function toArray(): array { if ($this->isUnfilteredAndEndLess()) { throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); } $state = [ $this->key, $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null, $this->validationResult, ]; $result = iterator_to_array($this); [$this->key, $this->carbonCurrent, $this->validationResult] = $state; return $result; } /** * Count dates in the date period. */ public function count(): int { return \count($this->toArray()); } /** * Return the first date in the date period. */ public function first(): ?CarbonInterface { if ($this->isUnfilteredAndEndLess()) { foreach ($this as $date) { $this->rewind(); return $date; } return null; } return ($this->toArray() ?: [])[0] ?? null; } /** * Return the last date in the date period. */ public function last(): ?CarbonInterface { $array = $this->toArray(); return $array ? $array[\count($array) - 1] : null; } /** * Convert the date period into a string. */ public function __toString(): string { return $this->toString(); } /** * Add aliases for setters. * * CarbonPeriod::days(3)->hours(5)->invert() * ->sinceNow()->until('2010-01-10') * ->filter(...) * ->count() * * Note: We use magic method to let static and instance aliases with the same names. */ public function __call(string $method, array $parameters): mixed { if (static::hasMacro($method)) { return static::bindMacroContext($this, fn () => $this->callMacro($method, $parameters)); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } $count = \count($parameters); switch ($method) { case 'start': case 'since': if ($count === 0) { return $this->getStartDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setStartDate(...$parameters); case 'sinceNow': return $this->setStartDate(new Carbon(), ...$parameters); case 'end': case 'until': if ($count === 0) { return $this->getEndDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setEndDate(...$parameters); case 'untilNow': return $this->setEndDate(new Carbon(), ...$parameters); case 'dates': case 'between': self::setDefaultParameters($parameters, [ [0, 'start', null], [1, 'end', null], ]); return $this->setDates(...$parameters); case 'recurrences': case 'times': if ($count === 0) { return $this->getRecurrences(); } self::setDefaultParameters($parameters, [ [0, 'recurrences', null], ]); return $this->setRecurrences(...$parameters); case 'options': if ($count === 0) { return $this->getOptions(); } self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->setOptions(...$parameters); case 'toggle': self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->toggleOptions(...$parameters); case 'filter': case 'push': return $this->addFilter(...$parameters); case 'prepend': return $this->prependFilter(...$parameters); case 'filters': if ($count === 0) { return $this->getFilters(); } self::setDefaultParameters($parameters, [ [0, 'filters', []], ]); return $this->setFilters(...$parameters); case 'interval': case 'each': case 'every': case 'step': case 'stepBy': if ($count === 0) { return $this->getDateInterval(); } return $this->setDateInterval(...$parameters); case 'invert': return $this->invertDateInterval(); case 'years': case 'year': case 'months': case 'month': case 'weeks': case 'week': case 'days': case 'dayz': case 'day': case 'hours': case 'hour': case 'minutes': case 'minute': case 'seconds': case 'second': case 'milliseconds': case 'millisecond': case 'microseconds': case 'microsecond': return $this->setDateInterval(( // Override default P1D when instantiating via fluent setters. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] )(...$parameters)); } $dateClass = $this->dateClass; if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { throw new UnknownMethodException($method); } return $this; } /** * Set the instance's timezone from a string or object and apply it to start/end. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->setTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->setTimezone($timezone)); } return $self; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } return $self; } /** * Returns the end is set, else calculated from start and recurrences. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. * * @return CarbonInterface */ public function calculateEnd(?string $rounding = null): CarbonInterface { if ($end = $this->getEndDate($rounding)) { return $end; } if ($this->dateInterval->isEmpty()) { return $this->getStartDate($rounding); } $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); if ($date && $rounding) { $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); } return $date; } private function getEndFromRecurrences(): ?CarbonInterface { if ($this->carbonRecurrences === null) { throw new UnreachableException( "Could not calculate period end without either explicit end or recurrences.\n". "If you're looking for a forever-period, use ->setRecurrences(INF).", ); } if ($this->carbonRecurrences === INF) { $start = $this->getStartDate(); return $start < $start->avoidMutation()->add($this->getDateInterval()) ? CarbonImmutable::endOfTime() : CarbonImmutable::startOfTime(); } if ($this->filters === [[static::RECURRENCES_FILTER, null]]) { return $this->getStartDate()->avoidMutation()->add( $this->getDateInterval()->times( $this->carbonRecurrences - ($this->isStartExcluded() ? 0 : 1), ), ); } return null; } private function iterateUntilEnd(): ?CarbonInterface { $attempts = 0; $date = null; foreach ($this as $date) { if (++$attempts > static::END_MAX_ATTEMPTS) { throw new UnreachableException( 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.', ); } } return $date; } /** * Returns true if the current period overlaps the given one (if 1 parameter passed) * or the period between 2 dates (if 2 parameters passed). * * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd * * @return bool */ public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool { $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; if (!($range instanceof self)) { $range = static::create($range); } [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); return $end > $rangeStart && $rangeEnd > $start; } /** * Execute a given function on each date of the period. * * @example * ``` * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) { * echo $date->diffInDays('2020-12-25')." days before Christmas!\n"; * }); * ``` */ public function forEach(callable $callback): void { foreach ($this as $date) { $callback($date); } } /** * Execute a given function on each date of the period and yield the result of this function. * * @example * ``` * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24'); * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) { * return $date->diffInDays('2020-12-25').' days before Christmas!'; * }))); * ``` */ public function map(callable $callback): Generator { foreach ($this as $date) { yield $callback($date); } } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. * * @see equalTo() */ public function eq(mixed $period): bool { return $this->equalTo($period); } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. */ public function equalTo(mixed $period): bool { if (!($period instanceof self)) { $period = self::make($period); } $end = $this->getEndDate(); return $period !== null && $this->getDateInterval()->eq($period->getDateInterval()) && $this->getStartDate()->eq($period->getStartDate()) && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. * * @see notEqualTo() */ public function ne(mixed $period): bool { return $this->notEqualTo($period); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. */ public function notEqualTo(mixed $period): bool { return !$this->eq($period); } /** * Determines if the start date is before another given date. * (Rather start/end are included by options is ignored.) */ public function startsBefore(mixed $date = null): bool { return $this->getStartDate()->lessThan($this->resolveCarbon($date)); } /** * Determines if the start date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsBeforeOrAt(mixed $date = null): bool { return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is after another given date. * (Rather start/end are included by options is ignored.) */ public function startsAfter(mixed $date = null): bool { return $this->getStartDate()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the start date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAfterOrAt(mixed $date = null): bool { return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAt(mixed $date = null): bool { return $this->getStartDate()->equalTo($this->resolveCarbon($date)); } /** * Determines if the end date is before another given date. * (Rather start/end are included by options is ignored.) */ public function endsBefore(mixed $date = null): bool { return $this->calculateEnd()->lessThan($this->resolveCarbon($date)); } /** * Determines if the end date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsBeforeOrAt(mixed $date = null): bool { return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is after another given date. * (Rather start/end are included by options is ignored.) */ public function endsAfter(mixed $date = null): bool { return $this->calculateEnd()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the end date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAfterOrAt(mixed $date = null): bool { return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAt(mixed $date = null): bool { return $this->calculateEnd()->equalTo($this->resolveCarbon($date)); } /** * Return true if start date is now or later. * (Rather start/end are included by options is ignored.) */ public function isStarted(): bool { return $this->startsBeforeOrAt(); } /** * Return true if end date is now or later. * (Rather start/end are included by options is ignored.) */ public function isEnded(): bool { return $this->endsBeforeOrAt(); } /** * Return true if now is between start date (included) and end date (excluded). * (Rather start/end are included by options is ignored.) */ public function isInProgress(): bool { return $this->isStarted() && !$this->isEnded(); } /** * Round the current instance at the given unit with given precision if specified and the given function. */ public function roundUnit( string $unit, DateInterval|float|int|string|null $precision = 1, callable|string $function = 'round', ): static { $self = $this->copyIfImmutable(); $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); if ($self->endDate) { $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); } /** * Truncate the current instance at the given unit with given precision if specified. */ public function floorUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. */ public function ceilUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function round( DateInterval|float|int|string|null $precision = null, callable|string $function = 'round', ): static { return $this->roundWith( $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(), $function ); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function floor(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified (else period interval is used). */ public function ceil(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'ceil'); } /** * Specify data which should be serialized to JSON. * * @link https://php.net/manual/en/jsonserializable.jsonserialize.php * * @return CarbonInterface[] */ public function jsonSerialize(): array { return $this->toArray(); } /** * Return true if the given date is between start and end. */ public function contains(mixed $date = null): bool { $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : ''); $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : ''); return $this->$startMethod($date) && $this->$endMethod($date); } /** * Return true if the current period follows a given other period (with no overlap). * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31] * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function follows(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval())); } /** * Return true if the given other period follows the current one (with no overlap). * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12] * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function isFollowedBy(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $period->follows($this); } /** * Return true if the given period either follows or is followed by the current one. * * @see follows() * @see isFollowedBy() */ public function isConsecutiveWith(mixed $period, mixed ...$arguments): bool { return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments); } public function __debugInfo(): array { $info = $this->baseDebugInfo(); unset( $info['start'], $info['end'], $info['interval'], $info['include_start_date'], $info['include_end_date'], $info['constructed'], $info["\0*\0constructed"], ); return $info; } public function __unserialize(array $data): void { try { $values = array_combine( array_map( static fn (string $key): string => preg_replace('/^\0\*\0/', '', $key), array_keys($data), ), $data, ); $this->initializeSerialization($values); foreach ($values as $key => $value) { if ($value === null) { continue; } $property = match ($key) { 'tzName' => $this->setTimezone(...), 'options' => $this->setOptions(...), 'recurrences' => $this->setRecurrences(...), 'current' => function (mixed $current): void { if (!($current instanceof CarbonInterface)) { $current = $this->resolveCarbon($current); } $this->carbonCurrent = $current; }, 'start' => 'startDate', 'interval' => $this->setDateInterval(...), 'end' => 'endDate', 'key' => null, 'include_start_date' => function (bool $included): void { $this->excludeStartDate(!$included); }, 'include_end_date' => function (bool $included): void { $this->excludeEndDate(!$included); }, default => $key, }; if ($property === null) { continue; } if (\is_callable($property)) { $property($value); continue; } if ($value instanceof DateTimeInterface && !($value instanceof CarbonInterface)) { $value = ($value instanceof DateTime) ? Carbon::instance($value) : CarbonImmutable::instance($value); } try { $this->$property = $value; } catch (Throwable) { // Must be ignored for backward-compatibility } } if (\array_key_exists('carbonRecurrences', $values)) { $this->carbonRecurrences = $values['carbonRecurrences']; } elseif (((int) ($values['recurrences'] ?? 0)) <= 1 && $this->endDate !== null) { $this->carbonRecurrences = null; } } catch (Throwable $e) { // @codeCoverageIgnoreStart if (!method_exists(parent::class, '__unserialize')) { throw $e; } parent::__unserialize($data); // @codeCoverageIgnoreEnd } } /** * Update properties after removing built-in filters. */ protected function updateInternalState(): void { if (!$this->hasFilter(static::END_DATE_FILTER)) { $this->endDate = null; } if (!$this->hasFilter(static::RECURRENCES_FILTER)) { $this->carbonRecurrences = null; } } /** * Create a filter tuple from raw parameters. * * Will create an automatic filter callback for one of Carbon's is* methods. */ protected function createFilterTuple(array $parameters): array { $method = array_shift($parameters); if (!$this->isCarbonPredicateMethod($method)) { return [$method, array_shift($parameters)]; } return [static fn ($date) => ([$date, $method])(...$parameters), $method]; } /** * Return whether given callable is a string pointing to one of Carbon's is* methods * and should be automatically converted to a filter callback. */ protected function isCarbonPredicateMethod(callable|string $callable): bool { return \is_string($callable) && str_starts_with($callable, 'is') && (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable)); } /** * Recurrences filter callback (limits number of recurrences). * * @SuppressWarnings(UnusedFormalParameter) */ protected function filterRecurrences(CarbonInterface $current, int $key): bool|callable { if ($key < $this->carbonRecurrences) { return true; } return static::END_ITERATION; } /** * End date filter callback. * * @return bool|static::END_ITERATION */ protected function filterEndDate(CarbonInterface $current): bool|callable { if (!$this->isEndExcluded() && $current == $this->endDate) { return true; } if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) { return true; } return static::END_ITERATION; } /** * End iteration filter callback. * * @return static::END_ITERATION */ protected function endIteration(): callable { return static::END_ITERATION; } /** * Handle change of the parameters. */ protected function handleChangedParameters(): void { if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { $this->dateClass = CarbonImmutable::class; } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { $this->dateClass = Carbon::class; } $this->validationResult = null; } /** * Validate current date and stop iteration when necessary. * * Returns true when current date is valid, false if it is not, or static::END_ITERATION * when iteration should be stopped. * * @return bool|static::END_ITERATION */ protected function validateCurrentDate(): bool|callable { if ($this->carbonCurrent === null) { $this->rewind(); } // Check after the first rewind to avoid repeating the initial validation. return $this->validationResult ?? ($this->validationResult = $this->checkFilters()); } /** * Check whether current value and key pass all the filters. * * @return bool|static::END_ITERATION */ protected function checkFilters(): bool|callable { $current = $this->prepareForReturn($this->carbonCurrent); foreach ($this->filters as $tuple) { $result = \call_user_func($tuple[0], $current->avoidMutation(), $this->key, $this); if ($result === static::END_ITERATION) { return static::END_ITERATION; } if (!$result) { return false; } } return true; } /** * Prepare given date to be returned to the external logic. * * @param CarbonInterface $date * * @return CarbonInterface */ protected function prepareForReturn(CarbonInterface $date) { $date = ([$this->dateClass, 'make'])($date); if ($this->timezone) { return $date->setTimezone($this->timezone); } return $date; } /** * Keep incrementing the current date until a valid date is found or the iteration is ended. * * @throws RuntimeException */ protected function incrementCurrentDateUntilValid(): void { $attempts = 0; do { $this->carbonCurrent = $this->carbonCurrent->add($this->dateInterval); $this->validationResult = null; if (++$attempts > static::NEXT_MAX_ATTEMPTS) { throw new UnreachableException('Could not find next valid date.'); } } while ($this->validateCurrentDate() === false); } /** * Call given macro. */ protected function callMacro(string $name, array $parameters): mixed { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date * * @return \Carbon\CarbonInterface */ protected function resolveCarbon($date = null) { return $this->getStartDate()->nowWithSameTz()->carbonize($date); } /** * Resolve passed arguments or DatePeriod to a CarbonPeriod object. */ protected function resolveCarbonPeriod(mixed $period, mixed ...$arguments): self { if ($period instanceof self) { return $period; } return $period instanceof DatePeriod ? static::instance($period) : static::create($period, ...$arguments); } private function orderCouple($first, $second): array { return $first > $second ? [$second, $first] : [$first, $second]; } private function makeDateTime($value): ?DateTimeInterface { if ($value instanceof DateTimeInterface) { return $value; } if ($value instanceof WeekDay || $value instanceof Month) { $dateClass = $this->dateClass; return new $dateClass($value, $this->timezoneSetting); } if (\is_string($value)) { $value = trim($value); if (!preg_match('/^P[\dT]/', $value) && !preg_match('/^R\d/', $value) && preg_match('/[a-z\d]/i', $value) ) { $dateClass = $this->dateClass; return $dateClass::parse($value, $this->timezoneSetting); } } return null; } private function isInfiniteDate($date): bool { return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); } private function rawDate($date): ?DateTimeInterface { if ($date === false || $date === null) { return null; } if ($date instanceof CarbonInterface) { return $date->isMutable() ? $date->toDateTime() : $date->toDateTimeImmutable(); } if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { return $date; } $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); } private static function setDefaultParameters(array &$parameters, array $defaults): void { foreach ($defaults as [$index, $name, $value]) { if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { $parameters[$index] = $value; } } } private function setFromAssociativeArray(array $parameters): void { if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['end'])) { $this->setEndDate($parameters['end']); } if (isset($parameters['recurrences'])) { $this->setRecurrences($parameters['recurrences']); } if (isset($parameters['interval'])) { $this->setDateInterval($parameters['interval']); } if (isset($parameters['options'])) { $this->setOptions($parameters['options']); } } private function configureTimezone(DateTimeZone $timezone, array $sortedArguments, array $originalArguments): array { $this->setTimezone($timezone); if (\is_string($originalArguments['start'] ?? null)) { $sortedArguments['start'] = $this->makeDateTime($originalArguments['start']); } if (\is_string($originalArguments['end'] ?? null)) { $sortedArguments['end'] = $this->makeDateTime($originalArguments['end']); } return $sortedArguments; } private function initializeSerialization(array $values): void { $serializationBase = [ 'start' => $values['start'] ?? $values['startDate'] ?? null, 'current' => $values['current'] ?? $values['carbonCurrent'] ?? null, 'end' => $values['end'] ?? $values['endDate'] ?? null, 'interval' => $values['interval'] ?? $values['dateInterval'] ?? null, 'recurrences' => max(1, (int) ($values['recurrences'] ?? $values['carbonRecurrences'] ?? 1)), 'include_start_date' => $values['include_start_date'] ?? true, 'include_end_date' => $values['include_end_date'] ?? false, ]; foreach (['start', 'current', 'end'] as $dateProperty) { if ($serializationBase[$dateProperty] instanceof Carbon) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTime(); } elseif ($serializationBase[$dateProperty] instanceof CarbonInterface) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTimeImmutable(); } } if ($serializationBase['interval'] instanceof CarbonInterval) { $serializationBase['interval'] = $serializationBase['interval']->toDateInterval(); } // @codeCoverageIgnoreStart if (method_exists(parent::class, '__unserialize')) { parent::__unserialize($serializationBase); return; } $excludeStart = !($values['include_start_date'] ?? true); $includeEnd = $values['include_end_date'] ?? true; parent::__construct( $serializationBase['start'], $serializationBase['interval'], $serializationBase['end'] ?? $serializationBase['recurrences'], ($excludeStart ? self::EXCLUDE_START_DATE : 0) | ($includeEnd && \defined('DatePeriod::INCLUDE_END_DATE') ? self::INCLUDE_END_DATE : 0), ); // @codeCoverageIgnoreEnd } }
PHP
{ "end_line": 1990, "name": "equalTo", "signature": "public function equalTo(mixed $period): bool", "start_line": 1977 }
{ "class_name": "CarbonPeriod", "class_signature": "class CarbonPeriod implements Countable, JsonSerializable, UnitValue", "namespace": "Carbon" }
roundUnit
Carbon/src/Carbon/CarbonPeriod.php
public function roundUnit( string $unit, DateInterval|float|int|string|null $precision = 1, callable|string $function = 'round', ): static { $self = $this->copyIfImmutable(); $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); if ($self->endDate) { $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Constants\UnitValue; use Carbon\Exceptions\EndLessPeriodException; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidIntervalException; use Carbon\Exceptions\InvalidPeriodDateException; use Carbon\Exceptions\InvalidPeriodParameterException; use Carbon\Exceptions\NotACarbonClassException; use Carbon\Exceptions\NotAPeriodException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnreachableException; use Carbon\Traits\DeprecatedPeriodProperties; use Carbon\Traits\IntervalRounding; use Carbon\Traits\LocalFactory; use Carbon\Traits\Mixin; use Carbon\Traits\Options; use Carbon\Traits\ToStringFormat; use Closure; use Countable; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use JsonSerializable; use ReflectionException; use ReturnTypeWillChange; use RuntimeException; use Throwable; // @codeCoverageIgnoreStart require PHP_VERSION < 8.2 ? __DIR__.'/../../lazy/Carbon/ProtectedDatePeriod.php' : __DIR__.'/../../lazy/Carbon/UnprotectedDatePeriod.php'; // @codeCoverageIgnoreEnd /** * Substitution of DatePeriod with some modifications and many more features. * * @method static static|CarbonInterface start($date = null, $inclusive = null) Create instance specifying start date or modify the start date if called on an instance. * @method static static since($date = null, $inclusive = null) Alias for start(). * @method static static sinceNow($inclusive = null) Create instance with start date set to now or set the start date to now if called on an instance. * @method static static|CarbonInterface end($date = null, $inclusive = null) Create instance specifying end date or modify the end date if called on an instance. * @method static static until($date = null, $inclusive = null) Alias for end(). * @method static static untilNow($inclusive = null) Create instance with end date set to now or set the end date to now if called on an instance. * @method static static dates($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static between($start, $end = null) Create instance with start and end dates or modify the start and end dates if called on an instance. * @method static static recurrences($recurrences = null) Create instance with maximum number of recurrences or modify the number of recurrences if called on an instance. * @method static static times($recurrences = null) Alias for recurrences(). * @method static static|int|null options($options = null) Create instance with options or modify the options if called on an instance. * @method static static toggle($options, $state = null) Create instance with options toggled on or off, or toggle options if called on an instance. * @method static static filter($callback, $name = null) Create instance with filter added to the stack or append a filter if called on an instance. * @method static static push($callback, $name = null) Alias for filter(). * @method static static prepend($callback, $name = null) Create instance with filter prepended to the stack or prepend a filter if called on an instance. * @method static static|array filters(array $filters = []) Create instance with filters stack or replace the whole filters stack if called on an instance. * @method static static|CarbonInterval interval($interval = null) Create instance with given date interval or modify the interval if called on an instance. * @method static static each($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static every($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static step($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static stepBy($interval) Create instance with given date interval or modify the interval if called on an instance. * @method static static invert() Create instance with inverted date interval or invert the interval if called on an instance. * @method static static years($years = 1) Create instance specifying a number of years for date interval or replace the interval by the given a number of years if called on an instance. * @method static static year($years = 1) Alias for years(). * @method static static months($months = 1) Create instance specifying a number of months for date interval or replace the interval by the given a number of months if called on an instance. * @method static static month($months = 1) Alias for months(). * @method static static weeks($weeks = 1) Create instance specifying a number of weeks for date interval or replace the interval by the given a number of weeks if called on an instance. * @method static static week($weeks = 1) Alias for weeks(). * @method static static days($days = 1) Create instance specifying a number of days for date interval or replace the interval by the given a number of days if called on an instance. * @method static static dayz($days = 1) Alias for days(). * @method static static day($days = 1) Alias for days(). * @method static static hours($hours = 1) Create instance specifying a number of hours for date interval or replace the interval by the given a number of hours if called on an instance. * @method static static hour($hours = 1) Alias for hours(). * @method static static minutes($minutes = 1) Create instance specifying a number of minutes for date interval or replace the interval by the given a number of minutes if called on an instance. * @method static static minute($minutes = 1) Alias for minutes(). * @method static static seconds($seconds = 1) Create instance specifying a number of seconds for date interval or replace the interval by the given a number of seconds if called on an instance. * @method static static second($seconds = 1) Alias for seconds(). * @method static static milliseconds($milliseconds = 1) Create instance specifying a number of milliseconds for date interval or replace the interval by the given a number of milliseconds if called on an instance. * @method static static millisecond($milliseconds = 1) Alias for milliseconds(). * @method static static microseconds($microseconds = 1) Create instance specifying a number of microseconds for date interval or replace the interval by the given a number of microseconds if called on an instance. * @method static static microsecond($microseconds = 1) Alias for microseconds(). * @method $this roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method $this floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method $this floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method $this ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method $this ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method $this roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method $this floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method $this floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method $this ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method $this ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method $this roundWeek(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundWeeks(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorWeek(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorWeeks(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilWeek(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilWeeks(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method $this floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method $this floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method $this ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method $this ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method $this roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method $this floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method $this floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method $this ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method $this ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method $this roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method $this floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method $this floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method $this ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method $this ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method $this roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method $this floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method $this floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method $this ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method $this ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method $this roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method $this floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method $this ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method $this roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method $this floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method $this floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method $this ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method $this ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method $this roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method $this floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method $this floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method $this ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method $this ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method $this roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method $this floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method $this ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method $this roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method $this floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method $this ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method $this roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method $this floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method $this ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method $this ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * * @mixin DeprecatedPeriodProperties * * @SuppressWarnings(TooManyFields) * @SuppressWarnings(CamelCasePropertyName) * @SuppressWarnings(CouplingBetweenObjects) */ class CarbonPeriod extends DatePeriodBase implements Countable, JsonSerializable, UnitValue { use LocalFactory; use IntervalRounding; use Mixin { Mixin::mixin as baseMixin; } use Options { Options::__debugInfo as baseDebugInfo; } use ToStringFormat; /** * Built-in filter for limit by recurrences. * * @var callable */ public const RECURRENCES_FILTER = [self::class, 'filterRecurrences']; /** * Built-in filter for limit to an end. * * @var callable */ public const END_DATE_FILTER = [self::class, 'filterEndDate']; /** * Special value which can be returned by filters to end iteration. Also a filter. * * @var callable */ public const END_ITERATION = [self::class, 'endIteration']; /** * Exclude end date from iteration. * * @var int */ public const EXCLUDE_END_DATE = 8; /** * Yield CarbonImmutable instances. * * @var int */ public const IMMUTABLE = 4; /** * Number of maximum attempts before giving up on finding next valid date. * * @var int */ public const NEXT_MAX_ATTEMPTS = 1000; /** * Number of maximum attempts before giving up on finding end date. * * @var int */ public const END_MAX_ATTEMPTS = 10000; /** * Default date class of iteration items. * * @var string */ protected const DEFAULT_DATE_CLASS = Carbon::class; /** * The registered macros. */ protected static array $macros = []; /** * Date class of iteration items. */ protected string $dateClass = Carbon::class; /** * Underlying date interval instance. Always present, one day by default. */ protected ?CarbonInterval $dateInterval = null; /** * True once __construct is finished. */ protected bool $constructed = false; /** * Whether current date interval was set by default. */ protected bool $isDefaultInterval = false; /** * The filters stack. */ protected array $filters = []; /** * Period start date. Applied on rewind. Always present, now by default. */ protected ?CarbonInterface $startDate = null; /** * Period end date. For inverted interval should be before the start date. Applied via a filter. */ protected ?CarbonInterface $endDate = null; /** * Limit for number of recurrences. Applied via a filter. */ protected int|float|null $carbonRecurrences = null; /** * Iteration options. */ protected ?int $options = null; /** * Index of current date. Always sequential, even if some dates are skipped by filters. * Equal to null only before the first iteration. */ protected int $key = 0; /** * Current date. May temporarily hold unaccepted value when looking for a next valid date. * Equal to null only before the first iteration. */ protected ?CarbonInterface $carbonCurrent = null; /** * Timezone of current date. Taken from the start date. */ protected ?DateTimeZone $timezone = null; /** * The cached validation result for current date. */ protected array|string|bool|null $validationResult = null; /** * Timezone handler for settings() method. */ protected DateTimeZone|string|int|null $timezoneSetting = null; public function getIterator(): Generator { $this->rewind(); while ($this->valid()) { $key = $this->key(); $value = $this->current(); yield $key => $value; $this->next(); } } /** * Make a CarbonPeriod instance from given variable if possible. */ public static function make(mixed $var): ?static { try { return static::instance($var); } catch (NotAPeriodException) { return static::create($var); } } /** * Create a new instance from a DatePeriod or CarbonPeriod object. */ public static function instance(mixed $period): static { if ($period instanceof static) { return $period->copy(); } if ($period instanceof self) { return new static( $period->getStartDate(), $period->getEndDate() ?? $period->getRecurrences(), $period->getDateInterval(), $period->getOptions(), ); } if ($period instanceof DatePeriod) { return new static( $period->start, $period->end ?: ($period->recurrences - 1), $period->interval, $period->include_start_date ? 0 : static::EXCLUDE_START_DATE, ); } $class = static::class; $type = \gettype($period); $chunks = explode('::', __METHOD__); throw new NotAPeriodException( 'Argument 1 passed to '.$class.'::'.end($chunks).'() '. 'must be an instance of DatePeriod or '.$class.', '. ($type === 'object' ? 'instance of '.\get_class($period) : $type).' given.', ); } /** * Create a new instance. */ public static function create(...$params): static { return static::createFromArray($params); } /** * Create a new instance from an array of parameters. */ public static function createFromArray(array $params): static { return new static(...$params); } /** * Create CarbonPeriod from ISO 8601 string. */ public static function createFromIso(string $iso, ?int $options = null): static { $params = static::parseIso8601($iso); $instance = static::createFromArray($params); $instance->options = ($instance instanceof CarbonPeriodImmutable ? static::IMMUTABLE : 0) | $options; $instance->handleChangedParameters(); return $instance; } public static function createFromISO8601String(string $iso, ?int $options = null): static { return self::createFromIso($iso, $options); } /** * Return whether the given interval contains non-zero value of any time unit. */ protected static function intervalHasTime(DateInterval $interval): bool { return $interval->h || $interval->i || $interval->s || $interval->f; } /** * Return whether given variable is an ISO 8601 specification. * * Note: Check is very basic, as actual validation will be done later when parsing. * We just want to ensure that variable is not any other type of valid parameter. */ protected static function isIso8601(mixed $var): bool { if (!\is_string($var)) { return false; } // Match slash but not within a timezone name. $part = '[a-z]+(?:[_-][a-z]+)*'; preg_match("#\b$part/$part\b|(/)#i", $var, $match); return isset($match[1]); } /** * Parse given ISO 8601 string into an array of arguments. * * @SuppressWarnings(ElseExpression) */ protected static function parseIso8601(string $iso): array { $result = []; $interval = null; $start = null; $end = null; $dateClass = static::DEFAULT_DATE_CLASS; foreach (explode('/', $iso) as $key => $part) { if ($key === 0 && preg_match('/^R(\d*|INF)$/', $part, $match)) { $parsed = \strlen($match[1]) ? (($match[1] !== 'INF') ? (int) $match[1] : INF) : null; } elseif ($interval === null && $parsed = self::makeInterval($part)) { $interval = $part; } elseif ($start === null && $parsed = $dateClass::make($part)) { $start = $part; } elseif ($end === null && $parsed = $dateClass::make(static::addMissingParts($start ?? '', $part))) { $end = $part; } else { throw new InvalidPeriodParameterException("Invalid ISO 8601 specification: $iso."); } $result[] = $parsed; } return $result; } /** * Add missing parts of the target date from the source date. */ protected static function addMissingParts(string $source, string $target): string { $pattern = '/'.preg_replace('/\d+/', '[0-9]+', preg_quote($target, '/')).'$/'; $result = preg_replace($pattern, $target, $source, 1, $count); return $count ? $result : $target; } private static function makeInterval(mixed $input): ?CarbonInterval { try { return CarbonInterval::make($input); } catch (Throwable) { return null; } } private static function makeTimezone(mixed $input): ?CarbonTimeZone { if (!\is_string($input)) { return null; } try { return CarbonTimeZone::create($input); } catch (Throwable) { return null; } } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * CarbonPeriod::macro('middle', function () { * return $this->getStartDate()->average($this->getEndDate()); * }); * echo CarbonPeriod::since('2011-05-12')->until('2011-06-03')->middle(); * ``` * * @param-closure-this static $macro */ public static function macro(string $name, ?callable $macro): void { static::$macros[$name] = $macro; } /** * Register macros from a mixin object. * * @example * ``` * CarbonPeriod::mixin(new class { * public function addDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->addDays($count) * )->setEndDate( * $this->getEndDate()->addDays($count) * ); * }; * } * public function subDays() { * return function ($count = 1) { * return $this->setStartDate( * $this->getStartDate()->subDays($count) * )->setEndDate( * $this->getEndDate()->subDays($count) * ); * }; * } * }); * echo CarbonPeriod::create('2000-01-01', '2000-02-01')->addDays(5)->subDays(3); * ``` * * @throws ReflectionException */ public static function mixin(object|string $mixin): void { static::baseMixin($mixin); } /** * Check if macro is registered. */ public static function hasMacro(string $name): bool { return isset(static::$macros[$name]); } /** * Provide static proxy for instance aliases. */ public static function __callStatic(string $method, array $parameters): mixed { $date = new static(); if (static::hasMacro($method)) { return static::bindMacroContext(null, static fn () => $date->callMacro($method, $parameters)); } return $date->$method(...$parameters); } /** * CarbonPeriod constructor. * * @SuppressWarnings(ElseExpression) * * @throws InvalidArgumentException */ public function __construct(...$arguments) { $raw = null; if (isset($arguments['raw'])) { $raw = $arguments['raw']; $this->isDefaultInterval = $arguments['isDefaultInterval'] ?? false; if (isset($arguments['dateClass'])) { $this->dateClass = $arguments['dateClass']; } $arguments = $raw; } // Parse and assign arguments one by one. First argument may be an ISO 8601 spec, // which will be first parsed into parts and then processed the same way. $argumentsCount = \count($arguments); if ($argumentsCount && static::isIso8601($iso = $arguments[0])) { array_splice($arguments, 0, 1, static::parseIso8601($iso)); } if ($argumentsCount === 1) { if ($arguments[0] instanceof self) { $arguments = [ $arguments[0]->getStartDate(), $arguments[0]->getEndDate() ?? $arguments[0]->getRecurrences(), $arguments[0]->getDateInterval(), $arguments[0]->getOptions(), ]; } elseif ($arguments[0] instanceof DatePeriod) { $arguments = [ $arguments[0]->start, $arguments[0]->end ?: ($arguments[0]->recurrences - 1), $arguments[0]->interval, $arguments[0]->include_start_date ? 0 : static::EXCLUDE_START_DATE, ]; } } if (is_a($this->dateClass, DateTimeImmutable::class, true)) { $this->options = static::IMMUTABLE; } $optionsSet = false; $originalArguments = []; $sortedArguments = []; foreach ($arguments as $argument) { $parsedDate = null; if ($argument instanceof DateTimeZone) { $sortedArguments = $this->configureTimezone($argument, $sortedArguments, $originalArguments); } elseif (!isset($sortedArguments['interval']) && ( (\is_string($argument) && preg_match( '/^(-?\d(\d(?![\/-])|[^\d\/-]([\/-])?)*|P[T\d].*|(?:\h*\d+(?:\.\d+)?\h*[a-z]+)+)$/i', $argument, )) || $argument instanceof DateInterval || $argument instanceof Closure || $argument instanceof Unit ) && $parsedInterval = self::makeInterval($argument) ) { $sortedArguments['interval'] = $parsedInterval; } elseif (!isset($sortedArguments['start']) && $parsedDate = $this->makeDateTime($argument)) { $sortedArguments['start'] = $parsedDate; $originalArguments['start'] = $argument; } elseif (!isset($sortedArguments['end']) && ($parsedDate = $parsedDate ?? $this->makeDateTime($argument))) { $sortedArguments['end'] = $parsedDate; $originalArguments['end'] = $argument; } elseif (!isset($sortedArguments['recurrences']) && !isset($sortedArguments['end']) && (\is_int($argument) || \is_float($argument)) && $argument >= 0 ) { $sortedArguments['recurrences'] = $argument; } elseif (!$optionsSet && (\is_int($argument) || $argument === null)) { $optionsSet = true; $sortedArguments['options'] = (((int) $this->options) | ((int) $argument)); } elseif ($parsedTimezone = self::makeTimezone($argument)) { $sortedArguments = $this->configureTimezone($parsedTimezone, $sortedArguments, $originalArguments); } else { throw new InvalidPeriodParameterException('Invalid constructor parameters.'); } } if ($raw === null && isset($sortedArguments['start'])) { $end = $sortedArguments['end'] ?? max(1, $sortedArguments['recurrences'] ?? 1); if (\is_float($end)) { $end = $end === INF ? PHP_INT_MAX : (int) round($end); } $raw = [ $sortedArguments['start'], $sortedArguments['interval'] ?? CarbonInterval::day(), $end, ]; } $this->setFromAssociativeArray($sortedArguments); if ($this->startDate === null) { $dateClass = $this->dateClass; $this->setStartDate($dateClass::now()); } if ($this->dateInterval === null) { $this->setDateInterval(CarbonInterval::day()); $this->isDefaultInterval = true; } if ($this->options === null) { $this->setOptions(0); } parent::__construct( $this->startDate, $this->dateInterval, $this->endDate ?? max(1, min(2147483639, $this->recurrences ?? 1)), $this->options, ); $this->constructed = true; } /** * Get a copy of the instance. */ public function copy(): static { return clone $this; } /** * Prepare the instance to be set (self if mutable to be mutated, * copy if immutable to generate a new instance). */ protected function copyIfImmutable(): static { return $this; } /** * Get the getter for a property allowing both `DatePeriod` snakeCase and camelCase names. */ protected function getGetter(string $name): ?callable { return match (strtolower(preg_replace('/[A-Z]/', '_$0', $name))) { 'start', 'start_date' => [$this, 'getStartDate'], 'end', 'end_date' => [$this, 'getEndDate'], 'interval', 'date_interval' => [$this, 'getDateInterval'], 'recurrences' => [$this, 'getRecurrences'], 'include_start_date' => [$this, 'isStartIncluded'], 'include_end_date' => [$this, 'isEndIncluded'], 'current' => [$this, 'current'], 'locale' => [$this, 'locale'], 'tzname', 'tz_name' => fn () => match (true) { $this->timezoneSetting === null => null, \is_string($this->timezoneSetting) => $this->timezoneSetting, $this->timezoneSetting instanceof DateTimeZone => $this->timezoneSetting->getName(), default => CarbonTimeZone::instance($this->timezoneSetting)->getName(), }, default => null, }; } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function get(string $name) { $getter = $this->getGetter($name); if ($getter) { return $getter(); } throw new UnknownGetterException($name); } /** * Get a property allowing both `DatePeriod` snakeCase and camelCase names. * * @param string $name * * @return bool|CarbonInterface|CarbonInterval|int|null */ public function __get(string $name) { return $this->get($name); } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset(string $name): bool { return $this->getGetter($name) !== null; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Set the iteration item class. * * @param string $dateClass * * @return static */ public function setDateClass(string $dateClass) { if (!is_a($dateClass, CarbonInterface::class, true)) { throw new NotACarbonClassException($dateClass); } $self = $this->copyIfImmutable(); $self->dateClass = $dateClass; if (is_a($dateClass, Carbon::class, true)) { $self->options = $self->options & ~static::IMMUTABLE; } elseif (is_a($dateClass, CarbonImmutable::class, true)) { $self->options = $self->options | static::IMMUTABLE; } return $self; } /** * Returns iteration item date class. * * @return string */ public function getDateClass(): string { return $this->dateClass; } /** * Change the period date interval. * * @param DateInterval|Unit|string|int $interval * @param Unit|string $unit the unit of $interval if it's a number * * @throws InvalidIntervalException * * @return static */ public function setDateInterval(mixed $interval, Unit|string|null $unit = null): static { if ($interval instanceof Unit) { $interval = $interval->interval(); } if ($unit instanceof Unit) { $unit = $unit->name; } if (!$interval = CarbonInterval::make($interval, $unit)) { throw new InvalidIntervalException('Invalid interval.'); } if ($interval->spec() === 'PT0S' && !$interval->f && !$interval->getStep()) { throw new InvalidIntervalException('Empty interval is not accepted.'); } $self = $this->copyIfImmutable(); $self->dateInterval = $interval; $self->isDefaultInterval = false; $self->handleChangedParameters(); return $self; } /** * Reset the date interval to the default value. * * Difference with simply setting interval to 1-day is that P1D will not appear when calling toIso8601String() * and also next adding to the interval won't include the default 1-day. */ public function resetDateInterval(): static { $self = $this->copyIfImmutable(); $self->setDateInterval(CarbonInterval::day()); $self->isDefaultInterval = true; return $self; } /** * Invert the period date interval. */ public function invertDateInterval(): static { return $this->setDateInterval($this->dateInterval->invert()); } /** * Set start and end date. * * @param DateTime|DateTimeInterface|string $start * @param DateTime|DateTimeInterface|string|null $end * * @return static */ public function setDates(mixed $start, mixed $end): static { return $this->setStartDate($start)->setEndDate($end); } /** * Change the period options. * * @param int|null $options * * @return static */ public function setOptions(?int $options): static { $self = $this->copyIfImmutable(); $self->options = $options ?? 0; $self->handleChangedParameters(); return $self; } /** * Get the period options. */ public function getOptions(): int { return $this->options ?? 0; } /** * Toggle given options on or off. * * @param int $options * @param bool|null $state * * @throws InvalidArgumentException * * @return static */ public function toggleOptions(int $options, ?bool $state = null): static { $self = $this->copyIfImmutable(); if ($state === null) { $state = ($this->options & $options) !== $options; } return $self->setOptions( $state ? $this->options | $options : $this->options & ~$options, ); } /** * Toggle EXCLUDE_START_DATE option. */ public function excludeStartDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_START_DATE, $state); } /** * Toggle EXCLUDE_END_DATE option. */ public function excludeEndDate(bool $state = true): static { return $this->toggleOptions(static::EXCLUDE_END_DATE, $state); } /** * Get the underlying date interval. */ public function getDateInterval(): CarbonInterval { return $this->dateInterval->copy(); } /** * Get start date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getStartDate(?string $rounding = null): CarbonInterface { $date = $this->startDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get end date of the period. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. */ public function getEndDate(?string $rounding = null): ?CarbonInterface { if (!$this->endDate) { return null; } $date = $this->endDate->avoidMutation(); return $rounding ? $date->round($this->getDateInterval(), $rounding) : $date; } /** * Get number of recurrences. */ #[ReturnTypeWillChange] public function getRecurrences(): int|float|null { return $this->carbonRecurrences; } /** * Returns true if the start date should be excluded. */ public function isStartExcluded(): bool { return ($this->options & static::EXCLUDE_START_DATE) !== 0; } /** * Returns true if the end date should be excluded. */ public function isEndExcluded(): bool { return ($this->options & static::EXCLUDE_END_DATE) !== 0; } /** * Returns true if the start date should be included. */ public function isStartIncluded(): bool { return !$this->isStartExcluded(); } /** * Returns true if the end date should be included. */ public function isEndIncluded(): bool { return !$this->isEndExcluded(); } /** * Return the start if it's included by option, else return the start + 1 period interval. */ public function getIncludedStartDate(): CarbonInterface { $start = $this->getStartDate(); if ($this->isStartExcluded()) { return $start->add($this->getDateInterval()); } return $start; } /** * Return the end if it's included by option, else return the end - 1 period interval. * Warning: if the period has no fixed end, this method will iterate the period to calculate it. */ public function getIncludedEndDate(): CarbonInterface { $end = $this->getEndDate(); if (!$end) { return $this->calculateEnd(); } if ($this->isEndExcluded()) { return $end->sub($this->getDateInterval()); } return $end; } /** * Add a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function addFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); $self->filters[] = $tuple; $self->handleChangedParameters(); return $self; } /** * Prepend a filter to the stack. * * @SuppressWarnings(UnusedFormalParameter) */ public function prependFilter(callable|string $callback, ?string $name = null): static { $self = $this->copyIfImmutable(); $tuple = $self->createFilterTuple(\func_get_args()); array_unshift($self->filters, $tuple); $self->handleChangedParameters(); return $self; } /** * Remove a filter by instance or name. */ public function removeFilter(callable|string $filter): static { $self = $this->copyIfImmutable(); $key = \is_callable($filter) ? 0 : 1; $self->filters = array_values(array_filter( $this->filters, static fn ($tuple) => $tuple[$key] !== $filter, )); $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Return whether given instance or name is in the filter stack. */ public function hasFilter(callable|string $filter): bool { $key = \is_callable($filter) ? 0 : 1; foreach ($this->filters as $tuple) { if ($tuple[$key] === $filter) { return true; } } return false; } /** * Get filters stack. */ public function getFilters(): array { return $this->filters; } /** * Set filters stack. */ public function setFilters(array $filters): static { $self = $this->copyIfImmutable(); $self->filters = $filters; $self->updateInternalState(); $self->handleChangedParameters(); return $self; } /** * Reset filters stack. */ public function resetFilters(): static { $self = $this->copyIfImmutable(); $self->filters = []; if ($self->endDate !== null) { $self->filters[] = [static::END_DATE_FILTER, null]; } if ($self->carbonRecurrences !== null) { $self->filters[] = [static::RECURRENCES_FILTER, null]; } $self->handleChangedParameters(); return $self; } /** * Add a recurrences filter (set maximum number of recurrences). * * @throws InvalidArgumentException */ public function setRecurrences(int|float|null $recurrences): static { if ($recurrences === null) { return $this->removeFilter(static::RECURRENCES_FILTER); } if ($recurrences < 0) { throw new InvalidPeriodParameterException('Invalid number of recurrences.'); } /** @var self $self */ $self = $this->copyIfImmutable(); $self->carbonRecurrences = $recurrences === INF ? INF : (int) $recurrences; if (!$self->hasFilter(static::RECURRENCES_FILTER)) { return $self->addFilter(static::RECURRENCES_FILTER); } $self->handleChangedParameters(); return $self; } /** * Change the period start date. * * @param DateTime|DateTimeInterface|string $date * @param bool|null $inclusive * * @throws InvalidPeriodDateException * * @return static */ public function setStartDate(mixed $date, ?bool $inclusive = null): static { if (!$this->isInfiniteDate($date) && !($date = ([$this->dateClass, 'make'])($date, $this->timezone))) { throw new InvalidPeriodDateException('Invalid start date.'); } $self = $this->copyIfImmutable(); $self->startDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_START_DATE, !$inclusive); } return $self; } /** * Change the period end date. * * @param DateTime|DateTimeInterface|string|null $date * @param bool|null $inclusive * * @throws \InvalidArgumentException * * @return static */ public function setEndDate(mixed $date, ?bool $inclusive = null): static { if ($date !== null && !$this->isInfiniteDate($date) && !$date = ([$this->dateClass, 'make'])($date, $this->timezone)) { throw new InvalidPeriodDateException('Invalid end date.'); } if (!$date) { return $this->removeFilter(static::END_DATE_FILTER); } $self = $this->copyIfImmutable(); $self->endDate = $date; if ($inclusive !== null) { $self = $self->toggleOptions(static::EXCLUDE_END_DATE, !$inclusive); } if (!$self->hasFilter(static::END_DATE_FILTER)) { return $self->addFilter(static::END_DATE_FILTER); } $self->handleChangedParameters(); return $self; } /** * Check if the current position is valid. */ public function valid(): bool { return $this->validateCurrentDate() === true; } /** * Return the current key. */ public function key(): ?int { return $this->valid() ? $this->key : null; } /** * Return the current date. */ public function current(): ?CarbonInterface { return $this->valid() ? $this->prepareForReturn($this->carbonCurrent) : null; } /** * Move forward to the next date. * * @throws RuntimeException */ public function next(): void { if ($this->carbonCurrent === null) { $this->rewind(); } if ($this->validationResult !== static::END_ITERATION) { $this->key++; $this->incrementCurrentDateUntilValid(); } } /** * Rewind to the start date. * * Iterating over a date in the UTC timezone avoids bug during backward DST change. * * @see https://bugs.php.net/bug.php?id=72255 * @see https://bugs.php.net/bug.php?id=74274 * @see https://wiki.php.net/rfc/datetime_and_daylight_saving_time * * @throws RuntimeException */ public function rewind(): void { $this->key = 0; $this->carbonCurrent = ([$this->dateClass, 'make'])($this->startDate); $settings = $this->getSettings(); if ($this->hasLocalTranslator()) { $settings['locale'] = $this->getTranslatorLocale(); } $this->carbonCurrent->settings($settings); $this->timezone = static::intervalHasTime($this->dateInterval) ? $this->carbonCurrent->getTimezone() : null; if ($this->timezone) { $this->carbonCurrent = $this->carbonCurrent->utc(); } $this->validationResult = null; if ($this->isStartExcluded() || $this->validateCurrentDate() === false) { $this->incrementCurrentDateUntilValid(); } } /** * Skip iterations and returns iteration state (false if ended, true if still valid). * * @param int $count steps number to skip (1 by default) * * @return bool */ public function skip(int $count = 1): bool { for ($i = $count; $this->valid() && $i > 0; $i--) { $this->next(); } return $this->valid(); } /** * Format the date period as ISO 8601. */ public function toIso8601String(): string { $parts = []; if ($this->carbonRecurrences !== null) { $parts[] = 'R'.$this->carbonRecurrences; } $parts[] = $this->startDate->toIso8601String(); if (!$this->isDefaultInterval) { $parts[] = $this->dateInterval->spec(); } if ($this->endDate !== null) { $parts[] = $this->endDate->toIso8601String(); } return implode('/', $parts); } /** * Convert the date period into a string. */ public function toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; if ($format instanceof Closure) { return $format($this); } $translator = ([$this->dateClass, 'getTranslator'])(); $parts = []; $format = $format ?? ( !$this->startDate->isStartOfDay() || ($this->endDate && !$this->endDate->isStartOfDay()) ? 'Y-m-d H:i:s' : 'Y-m-d' ); if ($this->carbonRecurrences !== null) { $parts[] = $this->translate('period_recurrences', [], $this->carbonRecurrences, $translator); } $parts[] = $this->translate('period_interval', [':interval' => $this->dateInterval->forHumans([ 'join' => true, ])], null, $translator); $parts[] = $this->translate('period_start_date', [':date' => $this->startDate->rawFormat($format)], null, $translator); if ($this->endDate !== null) { $parts[] = $this->translate('period_end_date', [':date' => $this->endDate->rawFormat($format)], null, $translator); } $result = implode(' ', $parts); return mb_strtoupper(mb_substr($result, 0, 1)).mb_substr($result, 1); } /** * Format the date period as ISO 8601. */ public function spec(): string { return $this->toIso8601String(); } /** * Cast the current instance into the given class. * * @param string $className The $className::instance() method will be called to cast the current object. * * @return DatePeriod|object */ public function cast(string $className): object { if (!method_exists($className, 'instance')) { if (is_a($className, DatePeriod::class, true)) { return new $className( $this->rawDate($this->getStartDate()), $this->getDateInterval(), $this->getEndDate() ? $this->rawDate($this->getIncludedEndDate()) : $this->getRecurrences(), $this->isStartExcluded() ? DatePeriod::EXCLUDE_START_DATE : 0, ); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Return native DatePeriod PHP object matching the current instance. * * @example * ``` * var_dump(CarbonPeriod::create('2021-01-05', '2021-02-15')->toDatePeriod()); * ``` */ public function toDatePeriod(): DatePeriod { return $this->cast(DatePeriod::class); } /** * Return `true` if the period has no custom filter and is guaranteed to be endless. * * Note that we can't check if a period is endless as soon as it has custom filters * because filters can emit `CarbonPeriod::END_ITERATION` to stop the iteration in * a way we can't predict without actually iterating the period. */ public function isUnfilteredAndEndLess(): bool { foreach ($this->filters as $filter) { switch ($filter) { case [static::RECURRENCES_FILTER, null]: if ($this->carbonRecurrences !== null && is_finite($this->carbonRecurrences)) { return false; } break; case [static::END_DATE_FILTER, null]: if ($this->endDate !== null && !$this->endDate->isEndOfTime()) { return false; } break; default: return false; } } return true; } /** * Convert the date period into an array without changing current iteration state. * * @return CarbonInterface[] */ public function toArray(): array { if ($this->isUnfilteredAndEndLess()) { throw new EndLessPeriodException("Endless period can't be converted to array nor counted."); } $state = [ $this->key, $this->carbonCurrent ? $this->carbonCurrent->avoidMutation() : null, $this->validationResult, ]; $result = iterator_to_array($this); [$this->key, $this->carbonCurrent, $this->validationResult] = $state; return $result; } /** * Count dates in the date period. */ public function count(): int { return \count($this->toArray()); } /** * Return the first date in the date period. */ public function first(): ?CarbonInterface { if ($this->isUnfilteredAndEndLess()) { foreach ($this as $date) { $this->rewind(); return $date; } return null; } return ($this->toArray() ?: [])[0] ?? null; } /** * Return the last date in the date period. */ public function last(): ?CarbonInterface { $array = $this->toArray(); return $array ? $array[\count($array) - 1] : null; } /** * Convert the date period into a string. */ public function __toString(): string { return $this->toString(); } /** * Add aliases for setters. * * CarbonPeriod::days(3)->hours(5)->invert() * ->sinceNow()->until('2010-01-10') * ->filter(...) * ->count() * * Note: We use magic method to let static and instance aliases with the same names. */ public function __call(string $method, array $parameters): mixed { if (static::hasMacro($method)) { return static::bindMacroContext($this, fn () => $this->callMacro($method, $parameters)); } $roundedValue = $this->callRoundMethod($method, $parameters); if ($roundedValue !== null) { return $roundedValue; } $count = \count($parameters); switch ($method) { case 'start': case 'since': if ($count === 0) { return $this->getStartDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setStartDate(...$parameters); case 'sinceNow': return $this->setStartDate(new Carbon(), ...$parameters); case 'end': case 'until': if ($count === 0) { return $this->getEndDate(); } self::setDefaultParameters($parameters, [ [0, 'date', null], ]); return $this->setEndDate(...$parameters); case 'untilNow': return $this->setEndDate(new Carbon(), ...$parameters); case 'dates': case 'between': self::setDefaultParameters($parameters, [ [0, 'start', null], [1, 'end', null], ]); return $this->setDates(...$parameters); case 'recurrences': case 'times': if ($count === 0) { return $this->getRecurrences(); } self::setDefaultParameters($parameters, [ [0, 'recurrences', null], ]); return $this->setRecurrences(...$parameters); case 'options': if ($count === 0) { return $this->getOptions(); } self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->setOptions(...$parameters); case 'toggle': self::setDefaultParameters($parameters, [ [0, 'options', null], ]); return $this->toggleOptions(...$parameters); case 'filter': case 'push': return $this->addFilter(...$parameters); case 'prepend': return $this->prependFilter(...$parameters); case 'filters': if ($count === 0) { return $this->getFilters(); } self::setDefaultParameters($parameters, [ [0, 'filters', []], ]); return $this->setFilters(...$parameters); case 'interval': case 'each': case 'every': case 'step': case 'stepBy': if ($count === 0) { return $this->getDateInterval(); } return $this->setDateInterval(...$parameters); case 'invert': return $this->invertDateInterval(); case 'years': case 'year': case 'months': case 'month': case 'weeks': case 'week': case 'days': case 'dayz': case 'day': case 'hours': case 'hour': case 'minutes': case 'minute': case 'seconds': case 'second': case 'milliseconds': case 'millisecond': case 'microseconds': case 'microsecond': return $this->setDateInterval(( // Override default P1D when instantiating via fluent setters. [$this->isDefaultInterval ? new CarbonInterval('PT0S') : $this->dateInterval, $method] )(...$parameters)); } $dateClass = $this->dateClass; if ($this->localStrictModeEnabled ?? $dateClass::isStrictModeEnabled()) { throw new UnknownMethodException($method); } return $this; } /** * Set the instance's timezone from a string or object and apply it to start/end. */ public function setTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->setTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->setTimezone($timezone)); } return $self; } /** * Set the instance's timezone from a string or object and add/subtract the offset difference to start/end. */ public function shiftTimezone(DateTimeZone|string|int $timezone): static { $self = $this->copyIfImmutable(); $self->timezoneSetting = $timezone; $self->timezone = CarbonTimeZone::instance($timezone); if ($self->startDate) { $self = $self->setStartDate($self->startDate->shiftTimezone($timezone)); } if ($self->endDate) { $self = $self->setEndDate($self->endDate->shiftTimezone($timezone)); } return $self; } /** * Returns the end is set, else calculated from start and recurrences. * * @param string|null $rounding Optional rounding 'floor', 'ceil', 'round' using the period interval. * * @return CarbonInterface */ public function calculateEnd(?string $rounding = null): CarbonInterface { if ($end = $this->getEndDate($rounding)) { return $end; } if ($this->dateInterval->isEmpty()) { return $this->getStartDate($rounding); } $date = $this->getEndFromRecurrences() ?? $this->iterateUntilEnd(); if ($date && $rounding) { $date = $date->avoidMutation()->round($this->getDateInterval(), $rounding); } return $date; } private function getEndFromRecurrences(): ?CarbonInterface { if ($this->carbonRecurrences === null) { throw new UnreachableException( "Could not calculate period end without either explicit end or recurrences.\n". "If you're looking for a forever-period, use ->setRecurrences(INF).", ); } if ($this->carbonRecurrences === INF) { $start = $this->getStartDate(); return $start < $start->avoidMutation()->add($this->getDateInterval()) ? CarbonImmutable::endOfTime() : CarbonImmutable::startOfTime(); } if ($this->filters === [[static::RECURRENCES_FILTER, null]]) { return $this->getStartDate()->avoidMutation()->add( $this->getDateInterval()->times( $this->carbonRecurrences - ($this->isStartExcluded() ? 0 : 1), ), ); } return null; } private function iterateUntilEnd(): ?CarbonInterface { $attempts = 0; $date = null; foreach ($this as $date) { if (++$attempts > static::END_MAX_ATTEMPTS) { throw new UnreachableException( 'Could not calculate period end after iterating '.static::END_MAX_ATTEMPTS.' times.', ); } } return $date; } /** * Returns true if the current period overlaps the given one (if 1 parameter passed) * or the period between 2 dates (if 2 parameters passed). * * @param CarbonPeriod|\DateTimeInterface|Carbon|CarbonImmutable|string $rangeOrRangeStart * @param \DateTimeInterface|Carbon|CarbonImmutable|string|null $rangeEnd * * @return bool */ public function overlaps(mixed $rangeOrRangeStart, mixed $rangeEnd = null): bool { $range = $rangeEnd ? static::create($rangeOrRangeStart, $rangeEnd) : $rangeOrRangeStart; if (!($range instanceof self)) { $range = static::create($range); } [$start, $end] = $this->orderCouple($this->getStartDate(), $this->calculateEnd()); [$rangeStart, $rangeEnd] = $this->orderCouple($range->getStartDate(), $range->calculateEnd()); return $end > $rangeStart && $rangeEnd > $start; } /** * Execute a given function on each date of the period. * * @example * ``` * Carbon::create('2020-11-29')->daysUntil('2020-12-24')->forEach(function (Carbon $date) { * echo $date->diffInDays('2020-12-25')." days before Christmas!\n"; * }); * ``` */ public function forEach(callable $callback): void { foreach ($this as $date) { $callback($date); } } /** * Execute a given function on each date of the period and yield the result of this function. * * @example * ``` * $period = Carbon::create('2020-11-29')->daysUntil('2020-12-24'); * echo implode("\n", iterator_to_array($period->map(function (Carbon $date) { * return $date->diffInDays('2020-12-25').' days before Christmas!'; * }))); * ``` */ public function map(callable $callback): Generator { foreach ($this as $date) { yield $callback($date); } } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. * * @see equalTo() */ public function eq(mixed $period): bool { return $this->equalTo($period); } /** * Determines if the instance is equal to another. * Warning: if options differ, instances will never be equal. */ public function equalTo(mixed $period): bool { if (!($period instanceof self)) { $period = self::make($period); } $end = $this->getEndDate(); return $period !== null && $this->getDateInterval()->eq($period->getDateInterval()) && $this->getStartDate()->eq($period->getStartDate()) && ($end ? $end->eq($period->getEndDate()) : $this->getRecurrences() === $period->getRecurrences()) && ($this->getOptions() & (~static::IMMUTABLE)) === ($period->getOptions() & (~static::IMMUTABLE)); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. * * @see notEqualTo() */ public function ne(mixed $period): bool { return $this->notEqualTo($period); } /** * Determines if the instance is not equal to another. * Warning: if options differ, instances will never be equal. */ public function notEqualTo(mixed $period): bool { return !$this->eq($period); } /** * Determines if the start date is before another given date. * (Rather start/end are included by options is ignored.) */ public function startsBefore(mixed $date = null): bool { return $this->getStartDate()->lessThan($this->resolveCarbon($date)); } /** * Determines if the start date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsBeforeOrAt(mixed $date = null): bool { return $this->getStartDate()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is after another given date. * (Rather start/end are included by options is ignored.) */ public function startsAfter(mixed $date = null): bool { return $this->getStartDate()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the start date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAfterOrAt(mixed $date = null): bool { return $this->getStartDate()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the start date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function startsAt(mixed $date = null): bool { return $this->getStartDate()->equalTo($this->resolveCarbon($date)); } /** * Determines if the end date is before another given date. * (Rather start/end are included by options is ignored.) */ public function endsBefore(mixed $date = null): bool { return $this->calculateEnd()->lessThan($this->resolveCarbon($date)); } /** * Determines if the end date is before or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsBeforeOrAt(mixed $date = null): bool { return $this->calculateEnd()->lessThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is after another given date. * (Rather start/end are included by options is ignored.) */ public function endsAfter(mixed $date = null): bool { return $this->calculateEnd()->greaterThan($this->resolveCarbon($date)); } /** * Determines if the end date is after or the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAfterOrAt(mixed $date = null): bool { return $this->calculateEnd()->greaterThanOrEqualTo($this->resolveCarbon($date)); } /** * Determines if the end date is the same as a given date. * (Rather start/end are included by options is ignored.) */ public function endsAt(mixed $date = null): bool { return $this->calculateEnd()->equalTo($this->resolveCarbon($date)); } /** * Return true if start date is now or later. * (Rather start/end are included by options is ignored.) */ public function isStarted(): bool { return $this->startsBeforeOrAt(); } /** * Return true if end date is now or later. * (Rather start/end are included by options is ignored.) */ public function isEnded(): bool { return $this->endsBeforeOrAt(); } /** * Return true if now is between start date (included) and end date (excluded). * (Rather start/end are included by options is ignored.) */ public function isInProgress(): bool { return $this->isStarted() && !$this->isEnded(); } /** * Round the current instance at the given unit with given precision if specified and the given function. */ public function roundUnit( string $unit, DateInterval|float|int|string|null $precision = 1, callable|string $function = 'round', ): static { $self = $this->copyIfImmutable(); $self = $self->setStartDate($self->getStartDate()->roundUnit($unit, $precision, $function)); if ($self->endDate) { $self = $self->setEndDate($self->getEndDate()->roundUnit($unit, $precision, $function)); } return $self->setDateInterval($self->getDateInterval()->roundUnit($unit, $precision, $function)); } /** * Truncate the current instance at the given unit with given precision if specified. */ public function floorUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'floor'); } /** * Ceil the current instance at the given unit with given precision if specified. */ public function ceilUnit(string $unit, DateInterval|float|int|string|null $precision = 1): static { return $this->roundUnit($unit, $precision, 'ceil'); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function round( DateInterval|float|int|string|null $precision = null, callable|string $function = 'round', ): static { return $this->roundWith( $precision ?? $this->getDateInterval()->setLocalTranslator(TranslatorImmutable::get('en'))->forHumans(), $function ); } /** * Round the current instance second with given precision if specified (else period interval is used). */ public function floor(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'floor'); } /** * Ceil the current instance second with given precision if specified (else period interval is used). */ public function ceil(DateInterval|float|int|string|null $precision = null): static { return $this->round($precision, 'ceil'); } /** * Specify data which should be serialized to JSON. * * @link https://php.net/manual/en/jsonserializable.jsonserialize.php * * @return CarbonInterface[] */ public function jsonSerialize(): array { return $this->toArray(); } /** * Return true if the given date is between start and end. */ public function contains(mixed $date = null): bool { $startMethod = 'startsBefore'.($this->isStartIncluded() ? 'OrAt' : ''); $endMethod = 'endsAfter'.($this->isEndIncluded() ? 'OrAt' : ''); return $this->$startMethod($date) && $this->$endMethod($date); } /** * Return true if the current period follows a given other period (with no overlap). * For instance, [2019-08-01 -> 2019-08-12] follows [2019-07-29 -> 2019-07-31] * Note than in this example, follows() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function follows(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $this->getIncludedStartDate()->equalTo($period->getIncludedEndDate()->add($period->getDateInterval())); } /** * Return true if the given other period follows the current one (with no overlap). * For instance, [2019-07-29 -> 2019-07-31] is followed by [2019-08-01 -> 2019-08-12] * Note than in this example, isFollowedBy() would be false if 2019-08-01 or 2019-07-31 was excluded by options. */ public function isFollowedBy(mixed $period, mixed ...$arguments): bool { $period = $this->resolveCarbonPeriod($period, ...$arguments); return $period->follows($this); } /** * Return true if the given period either follows or is followed by the current one. * * @see follows() * @see isFollowedBy() */ public function isConsecutiveWith(mixed $period, mixed ...$arguments): bool { return $this->follows($period, ...$arguments) || $this->isFollowedBy($period, ...$arguments); } public function __debugInfo(): array { $info = $this->baseDebugInfo(); unset( $info['start'], $info['end'], $info['interval'], $info['include_start_date'], $info['include_end_date'], $info['constructed'], $info["\0*\0constructed"], ); return $info; } public function __unserialize(array $data): void { try { $values = array_combine( array_map( static fn (string $key): string => preg_replace('/^\0\*\0/', '', $key), array_keys($data), ), $data, ); $this->initializeSerialization($values); foreach ($values as $key => $value) { if ($value === null) { continue; } $property = match ($key) { 'tzName' => $this->setTimezone(...), 'options' => $this->setOptions(...), 'recurrences' => $this->setRecurrences(...), 'current' => function (mixed $current): void { if (!($current instanceof CarbonInterface)) { $current = $this->resolveCarbon($current); } $this->carbonCurrent = $current; }, 'start' => 'startDate', 'interval' => $this->setDateInterval(...), 'end' => 'endDate', 'key' => null, 'include_start_date' => function (bool $included): void { $this->excludeStartDate(!$included); }, 'include_end_date' => function (bool $included): void { $this->excludeEndDate(!$included); }, default => $key, }; if ($property === null) { continue; } if (\is_callable($property)) { $property($value); continue; } if ($value instanceof DateTimeInterface && !($value instanceof CarbonInterface)) { $value = ($value instanceof DateTime) ? Carbon::instance($value) : CarbonImmutable::instance($value); } try { $this->$property = $value; } catch (Throwable) { // Must be ignored for backward-compatibility } } if (\array_key_exists('carbonRecurrences', $values)) { $this->carbonRecurrences = $values['carbonRecurrences']; } elseif (((int) ($values['recurrences'] ?? 0)) <= 1 && $this->endDate !== null) { $this->carbonRecurrences = null; } } catch (Throwable $e) { // @codeCoverageIgnoreStart if (!method_exists(parent::class, '__unserialize')) { throw $e; } parent::__unserialize($data); // @codeCoverageIgnoreEnd } } /** * Update properties after removing built-in filters. */ protected function updateInternalState(): void { if (!$this->hasFilter(static::END_DATE_FILTER)) { $this->endDate = null; } if (!$this->hasFilter(static::RECURRENCES_FILTER)) { $this->carbonRecurrences = null; } } /** * Create a filter tuple from raw parameters. * * Will create an automatic filter callback for one of Carbon's is* methods. */ protected function createFilterTuple(array $parameters): array { $method = array_shift($parameters); if (!$this->isCarbonPredicateMethod($method)) { return [$method, array_shift($parameters)]; } return [static fn ($date) => ([$date, $method])(...$parameters), $method]; } /** * Return whether given callable is a string pointing to one of Carbon's is* methods * and should be automatically converted to a filter callback. */ protected function isCarbonPredicateMethod(callable|string $callable): bool { return \is_string($callable) && str_starts_with($callable, 'is') && (method_exists($this->dateClass, $callable) || ([$this->dateClass, 'hasMacro'])($callable)); } /** * Recurrences filter callback (limits number of recurrences). * * @SuppressWarnings(UnusedFormalParameter) */ protected function filterRecurrences(CarbonInterface $current, int $key): bool|callable { if ($key < $this->carbonRecurrences) { return true; } return static::END_ITERATION; } /** * End date filter callback. * * @return bool|static::END_ITERATION */ protected function filterEndDate(CarbonInterface $current): bool|callable { if (!$this->isEndExcluded() && $current == $this->endDate) { return true; } if ($this->dateInterval->invert ? $current > $this->endDate : $current < $this->endDate) { return true; } return static::END_ITERATION; } /** * End iteration filter callback. * * @return static::END_ITERATION */ protected function endIteration(): callable { return static::END_ITERATION; } /** * Handle change of the parameters. */ protected function handleChangedParameters(): void { if (($this->getOptions() & static::IMMUTABLE) && $this->dateClass === Carbon::class) { $this->dateClass = CarbonImmutable::class; } elseif (!($this->getOptions() & static::IMMUTABLE) && $this->dateClass === CarbonImmutable::class) { $this->dateClass = Carbon::class; } $this->validationResult = null; } /** * Validate current date and stop iteration when necessary. * * Returns true when current date is valid, false if it is not, or static::END_ITERATION * when iteration should be stopped. * * @return bool|static::END_ITERATION */ protected function validateCurrentDate(): bool|callable { if ($this->carbonCurrent === null) { $this->rewind(); } // Check after the first rewind to avoid repeating the initial validation. return $this->validationResult ?? ($this->validationResult = $this->checkFilters()); } /** * Check whether current value and key pass all the filters. * * @return bool|static::END_ITERATION */ protected function checkFilters(): bool|callable { $current = $this->prepareForReturn($this->carbonCurrent); foreach ($this->filters as $tuple) { $result = \call_user_func($tuple[0], $current->avoidMutation(), $this->key, $this); if ($result === static::END_ITERATION) { return static::END_ITERATION; } if (!$result) { return false; } } return true; } /** * Prepare given date to be returned to the external logic. * * @param CarbonInterface $date * * @return CarbonInterface */ protected function prepareForReturn(CarbonInterface $date) { $date = ([$this->dateClass, 'make'])($date); if ($this->timezone) { return $date->setTimezone($this->timezone); } return $date; } /** * Keep incrementing the current date until a valid date is found or the iteration is ended. * * @throws RuntimeException */ protected function incrementCurrentDateUntilValid(): void { $attempts = 0; do { $this->carbonCurrent = $this->carbonCurrent->add($this->dateInterval); $this->validationResult = null; if (++$attempts > static::NEXT_MAX_ATTEMPTS) { throw new UnreachableException('Could not find next valid date.'); } } while ($this->validateCurrentDate() === false); } /** * Call given macro. */ protected function callMacro(string $name, array $parameters): mixed { $macro = static::$macros[$name]; if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return ($boundMacro ?: $macro)(...$parameters); } return $macro(...$parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param \Carbon\Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|\DateTimeInterface|string|null $date * * @return \Carbon\CarbonInterface */ protected function resolveCarbon($date = null) { return $this->getStartDate()->nowWithSameTz()->carbonize($date); } /** * Resolve passed arguments or DatePeriod to a CarbonPeriod object. */ protected function resolveCarbonPeriod(mixed $period, mixed ...$arguments): self { if ($period instanceof self) { return $period; } return $period instanceof DatePeriod ? static::instance($period) : static::create($period, ...$arguments); } private function orderCouple($first, $second): array { return $first > $second ? [$second, $first] : [$first, $second]; } private function makeDateTime($value): ?DateTimeInterface { if ($value instanceof DateTimeInterface) { return $value; } if ($value instanceof WeekDay || $value instanceof Month) { $dateClass = $this->dateClass; return new $dateClass($value, $this->timezoneSetting); } if (\is_string($value)) { $value = trim($value); if (!preg_match('/^P[\dT]/', $value) && !preg_match('/^R\d/', $value) && preg_match('/[a-z\d]/i', $value) ) { $dateClass = $this->dateClass; return $dateClass::parse($value, $this->timezoneSetting); } } return null; } private function isInfiniteDate($date): bool { return $date instanceof CarbonInterface && ($date->isEndOfTime() || $date->isStartOfTime()); } private function rawDate($date): ?DateTimeInterface { if ($date === false || $date === null) { return null; } if ($date instanceof CarbonInterface) { return $date->isMutable() ? $date->toDateTime() : $date->toDateTimeImmutable(); } if (\in_array(\get_class($date), [DateTime::class, DateTimeImmutable::class], true)) { return $date; } $class = $date instanceof DateTime ? DateTime::class : DateTimeImmutable::class; return new $class($date->format('Y-m-d H:i:s.u'), $date->getTimezone()); } private static function setDefaultParameters(array &$parameters, array $defaults): void { foreach ($defaults as [$index, $name, $value]) { if (!\array_key_exists($index, $parameters) && !\array_key_exists($name, $parameters)) { $parameters[$index] = $value; } } } private function setFromAssociativeArray(array $parameters): void { if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['start'])) { $this->setStartDate($parameters['start']); } if (isset($parameters['end'])) { $this->setEndDate($parameters['end']); } if (isset($parameters['recurrences'])) { $this->setRecurrences($parameters['recurrences']); } if (isset($parameters['interval'])) { $this->setDateInterval($parameters['interval']); } if (isset($parameters['options'])) { $this->setOptions($parameters['options']); } } private function configureTimezone(DateTimeZone $timezone, array $sortedArguments, array $originalArguments): array { $this->setTimezone($timezone); if (\is_string($originalArguments['start'] ?? null)) { $sortedArguments['start'] = $this->makeDateTime($originalArguments['start']); } if (\is_string($originalArguments['end'] ?? null)) { $sortedArguments['end'] = $this->makeDateTime($originalArguments['end']); } return $sortedArguments; } private function initializeSerialization(array $values): void { $serializationBase = [ 'start' => $values['start'] ?? $values['startDate'] ?? null, 'current' => $values['current'] ?? $values['carbonCurrent'] ?? null, 'end' => $values['end'] ?? $values['endDate'] ?? null, 'interval' => $values['interval'] ?? $values['dateInterval'] ?? null, 'recurrences' => max(1, (int) ($values['recurrences'] ?? $values['carbonRecurrences'] ?? 1)), 'include_start_date' => $values['include_start_date'] ?? true, 'include_end_date' => $values['include_end_date'] ?? false, ]; foreach (['start', 'current', 'end'] as $dateProperty) { if ($serializationBase[$dateProperty] instanceof Carbon) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTime(); } elseif ($serializationBase[$dateProperty] instanceof CarbonInterface) { $serializationBase[$dateProperty] = $serializationBase[$dateProperty]->toDateTimeImmutable(); } } if ($serializationBase['interval'] instanceof CarbonInterval) { $serializationBase['interval'] = $serializationBase['interval']->toDateInterval(); } // @codeCoverageIgnoreStart if (method_exists(parent::class, '__unserialize')) { parent::__unserialize($serializationBase); return; } $excludeStart = !($values['include_start_date'] ?? true); $includeEnd = $values['include_end_date'] ?? true; parent::__construct( $serializationBase['start'], $serializationBase['interval'], $serializationBase['end'] ?? $serializationBase['recurrences'], ($excludeStart ? self::EXCLUDE_START_DATE : 0) | ($includeEnd && \defined('DatePeriod::INCLUDE_END_DATE') ? self::INCLUDE_END_DATE : 0), ); // @codeCoverageIgnoreEnd } }
PHP
{ "end_line": 2145, "name": "roundUnit", "signature": "public function roundUnit(", "start_line": 2132 }
{ "class_name": "CarbonPeriod", "class_signature": "class CarbonPeriod implements Countable, JsonSerializable, UnitValue", "namespace": "Carbon" }
cast
Carbon/src/Carbon/CarbonTimeZone.php
public function cast(string $className): mixed { if (!method_exists($className, 'instance')) { if (is_a($className, DateTimeZone::class, true)) { return new $className($this->getName()); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Traits\LocalFactory; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Exception; use Throwable; class CarbonTimeZone extends DateTimeZone { use LocalFactory; public const MAXIMUM_TIMEZONE_OFFSET = 99; public function __construct(string|int|float $timezone) { $this->initLocalFactory(); parent::__construct(static::getDateTimeZoneNameFromMixed($timezone)); } protected static function parseNumericTimezone(string|int|float $timezone): string { if (abs((float) $timezone) > static::MAXIMUM_TIMEZONE_OFFSET) { throw new InvalidTimeZoneException( 'Absolute timezone offset cannot be greater than '. static::MAXIMUM_TIMEZONE_OFFSET.'.', ); } return ($timezone >= 0 ? '+' : '').ltrim((string) $timezone, '+').':00'; } protected static function getDateTimeZoneNameFromMixed(string|int|float $timezone): string { if (\is_string($timezone)) { $timezone = preg_replace('/^\s*([+-]\d+)(\d{2})\s*$/', '$1:$2', $timezone); } if (is_numeric($timezone)) { return static::parseNumericTimezone($timezone); } return $timezone; } /** * Cast the current instance into the given class. * * @param class-string<DateTimeZone> $className The $className::instance() method will be called to cast the current object. * * @return DateTimeZone|mixed */ public function cast(string $className): mixed { if (!method_exists($className, 'instance')) { if (is_a($className, DateTimeZone::class, true)) { return new $className($this->getName()); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Create a CarbonTimeZone from mixed input. * * @param DateTimeZone|string|int|false|null $object original value to get CarbonTimeZone from it. * @param DateTimeZone|string|int|false|null $objectDump dump of the object for error messages. * * @throws InvalidTimeZoneException * * @return static|null */ public static function instance( DateTimeZone|string|int|false|null $object, DateTimeZone|string|int|false|null $objectDump = null, ): ?self { $timezone = $object; if ($timezone instanceof static) { return $timezone; } if ($timezone === null || $timezone === false) { return null; } try { if (!($timezone instanceof DateTimeZone)) { $name = static::getDateTimeZoneNameFromMixed($object); $timezone = new static($name); } return $timezone instanceof static ? $timezone : new static($timezone->getName()); } catch (Exception $exception) { throw new InvalidTimeZoneException( 'Unknown or bad timezone ('.($objectDump ?: $object).')', previous: $exception, ); } } /** * Returns abbreviated name of the current timezone according to DST setting. * * @param bool $dst * * @return string */ public function getAbbreviatedName(bool $dst = false): string { $name = $this->getName(); $date = new DateTimeImmutable($dst ? 'July 1' : 'January 1', $this); $timezone = $date->format('T'); $abbreviations = $this->listAbbreviations(); $matchingZones = array_merge($abbreviations[$timezone] ?? [], $abbreviations[strtolower($timezone)] ?? []); if ($matchingZones !== []) { foreach ($matchingZones as $zone) { if ($zone['timezone_id'] === $name && $zone['dst'] == $dst) { return $timezone; } } } foreach ($abbreviations as $abbreviation => $zones) { foreach ($zones as $zone) { if ($zone['timezone_id'] === $name && $zone['dst'] == $dst) { return strtoupper($abbreviation); } } } return 'unknown'; } /** * @alias getAbbreviatedName * * Returns abbreviated name of the current timezone according to DST setting. * * @param bool $dst * * @return string */ public function getAbbr(bool $dst = false): string { return $this->getAbbreviatedName($dst); } /** * Get the offset as string "sHH:MM" (such as "+00:00" or "-12:30"). */ public function toOffsetName(?DateTimeInterface $date = null): string { return static::getOffsetNameFromMinuteOffset( $this->getOffset($this->resolveCarbon($date)) / 60, ); } /** * Returns a new CarbonTimeZone object using the offset string instead of region string. */ public function toOffsetTimeZone(?DateTimeInterface $date = null): static { return new static($this->toOffsetName($date)); } /** * Returns the first region string (such as "America/Toronto") that matches the current timezone or * false if no match is found. * * @see timezone_name_from_abbr native PHP function. */ public function toRegionName(?DateTimeInterface $date = null, int $isDST = 1): ?string { $name = $this->getName(); $firstChar = substr($name, 0, 1); if ($firstChar !== '+' && $firstChar !== '-') { return $name; } $date = $this->resolveCarbon($date); // Integer construction no longer supported since PHP 8 // @codeCoverageIgnoreStart try { $offset = @$this->getOffset($date) ?: 0; } catch (Throwable) { $offset = 0; } // @codeCoverageIgnoreEnd $name = @timezone_name_from_abbr('', $offset, $isDST); if ($name) { return $name; } foreach (timezone_identifiers_list() as $timezone) { if (Carbon::instance($date)->setTimezone($timezone)->getOffset() === $offset) { return $timezone; } } return null; } /** * Returns a new CarbonTimeZone object using the region string instead of offset string. */ public function toRegionTimeZone(?DateTimeInterface $date = null): ?self { $timezone = $this->toRegionName($date); if ($timezone !== null) { return new static($timezone); } if (Carbon::isStrictModeEnabled()) { throw new InvalidTimeZoneException('Unknown timezone for offset '.$this->getOffset($this->resolveCarbon($date)).' seconds.'); } return null; } /** * Cast to string (get timezone name). * * @return string */ public function __toString() { return $this->getName(); } /** * Return the type number: * * Type 1; A UTC offset, such as -0300 * Type 2; A timezone abbreviation, such as GMT * Type 3: A timezone identifier, such as Europe/London */ public function getType(): int { return preg_match('/"timezone_type";i:(\d)/', serialize($this), $match) ? (int) $match[1] : 3; } /** * Create a CarbonTimeZone from mixed input. * * @param DateTimeZone|string|int|null $object * * @return false|static */ public static function create($object = null) { return static::instance($object); } /** * Create a CarbonTimeZone from int/float hour offset. * * @param float $hourOffset number of hour of the timezone shift (can be decimal). * * @return false|static */ public static function createFromHourOffset(float $hourOffset) { return static::createFromMinuteOffset($hourOffset * Carbon::MINUTES_PER_HOUR); } /** * Create a CarbonTimeZone from int/float minute offset. * * @param float $minuteOffset number of total minutes of the timezone shift. * * @return false|static */ public static function createFromMinuteOffset(float $minuteOffset) { return static::instance(static::getOffsetNameFromMinuteOffset($minuteOffset)); } /** * Convert a total minutes offset into a standardized timezone offset string. * * @param float $minutes number of total minutes of the timezone shift. * * @return string */ public static function getOffsetNameFromMinuteOffset(float $minutes): string { $minutes = round($minutes); $unsignedMinutes = abs($minutes); return ($minutes < 0 ? '-' : '+'). str_pad((string) floor($unsignedMinutes / 60), 2, '0', STR_PAD_LEFT). ':'. str_pad((string) ($unsignedMinutes % 60), 2, '0', STR_PAD_LEFT); } private function resolveCarbon(?DateTimeInterface $date): DateTimeInterface { if ($date) { return $date; } if (isset($this->clock)) { return $this->clock->now()->setTimezone($this); } return Carbon::now($this); } }
PHP
{ "end_line": 81, "name": "cast", "signature": "public function cast(string $className): mixed", "start_line": 70 }
{ "class_name": "CarbonTimeZone", "class_signature": "class CarbonTimeZone", "namespace": "Carbon" }
instance
Carbon/src/Carbon/CarbonTimeZone.php
public static function instance( DateTimeZone|string|int|false|null $object, DateTimeZone|string|int|false|null $objectDump = null, ): ?self { $timezone = $object; if ($timezone instanceof static) { return $timezone; } if ($timezone === null || $timezone === false) { return null; } try { if (!($timezone instanceof DateTimeZone)) { $name = static::getDateTimeZoneNameFromMixed($object); $timezone = new static($name); } return $timezone instanceof static ? $timezone : new static($timezone->getName()); } catch (Exception $exception) { throw new InvalidTimeZoneException( 'Unknown or bad timezone ('.($objectDump ?: $object).')', previous: $exception, ); } }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Traits\LocalFactory; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Exception; use Throwable; class CarbonTimeZone extends DateTimeZone { use LocalFactory; public const MAXIMUM_TIMEZONE_OFFSET = 99; public function __construct(string|int|float $timezone) { $this->initLocalFactory(); parent::__construct(static::getDateTimeZoneNameFromMixed($timezone)); } protected static function parseNumericTimezone(string|int|float $timezone): string { if (abs((float) $timezone) > static::MAXIMUM_TIMEZONE_OFFSET) { throw new InvalidTimeZoneException( 'Absolute timezone offset cannot be greater than '. static::MAXIMUM_TIMEZONE_OFFSET.'.', ); } return ($timezone >= 0 ? '+' : '').ltrim((string) $timezone, '+').':00'; } protected static function getDateTimeZoneNameFromMixed(string|int|float $timezone): string { if (\is_string($timezone)) { $timezone = preg_replace('/^\s*([+-]\d+)(\d{2})\s*$/', '$1:$2', $timezone); } if (is_numeric($timezone)) { return static::parseNumericTimezone($timezone); } return $timezone; } /** * Cast the current instance into the given class. * * @param class-string<DateTimeZone> $className The $className::instance() method will be called to cast the current object. * * @return DateTimeZone|mixed */ public function cast(string $className): mixed { if (!method_exists($className, 'instance')) { if (is_a($className, DateTimeZone::class, true)) { return new $className($this->getName()); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Create a CarbonTimeZone from mixed input. * * @param DateTimeZone|string|int|false|null $object original value to get CarbonTimeZone from it. * @param DateTimeZone|string|int|false|null $objectDump dump of the object for error messages. * * @throws InvalidTimeZoneException * * @return static|null */ public static function instance( DateTimeZone|string|int|false|null $object, DateTimeZone|string|int|false|null $objectDump = null, ): ?self { $timezone = $object; if ($timezone instanceof static) { return $timezone; } if ($timezone === null || $timezone === false) { return null; } try { if (!($timezone instanceof DateTimeZone)) { $name = static::getDateTimeZoneNameFromMixed($object); $timezone = new static($name); } return $timezone instanceof static ? $timezone : new static($timezone->getName()); } catch (Exception $exception) { throw new InvalidTimeZoneException( 'Unknown or bad timezone ('.($objectDump ?: $object).')', previous: $exception, ); } } /** * Returns abbreviated name of the current timezone according to DST setting. * * @param bool $dst * * @return string */ public function getAbbreviatedName(bool $dst = false): string { $name = $this->getName(); $date = new DateTimeImmutable($dst ? 'July 1' : 'January 1', $this); $timezone = $date->format('T'); $abbreviations = $this->listAbbreviations(); $matchingZones = array_merge($abbreviations[$timezone] ?? [], $abbreviations[strtolower($timezone)] ?? []); if ($matchingZones !== []) { foreach ($matchingZones as $zone) { if ($zone['timezone_id'] === $name && $zone['dst'] == $dst) { return $timezone; } } } foreach ($abbreviations as $abbreviation => $zones) { foreach ($zones as $zone) { if ($zone['timezone_id'] === $name && $zone['dst'] == $dst) { return strtoupper($abbreviation); } } } return 'unknown'; } /** * @alias getAbbreviatedName * * Returns abbreviated name of the current timezone according to DST setting. * * @param bool $dst * * @return string */ public function getAbbr(bool $dst = false): string { return $this->getAbbreviatedName($dst); } /** * Get the offset as string "sHH:MM" (such as "+00:00" or "-12:30"). */ public function toOffsetName(?DateTimeInterface $date = null): string { return static::getOffsetNameFromMinuteOffset( $this->getOffset($this->resolveCarbon($date)) / 60, ); } /** * Returns a new CarbonTimeZone object using the offset string instead of region string. */ public function toOffsetTimeZone(?DateTimeInterface $date = null): static { return new static($this->toOffsetName($date)); } /** * Returns the first region string (such as "America/Toronto") that matches the current timezone or * false if no match is found. * * @see timezone_name_from_abbr native PHP function. */ public function toRegionName(?DateTimeInterface $date = null, int $isDST = 1): ?string { $name = $this->getName(); $firstChar = substr($name, 0, 1); if ($firstChar !== '+' && $firstChar !== '-') { return $name; } $date = $this->resolveCarbon($date); // Integer construction no longer supported since PHP 8 // @codeCoverageIgnoreStart try { $offset = @$this->getOffset($date) ?: 0; } catch (Throwable) { $offset = 0; } // @codeCoverageIgnoreEnd $name = @timezone_name_from_abbr('', $offset, $isDST); if ($name) { return $name; } foreach (timezone_identifiers_list() as $timezone) { if (Carbon::instance($date)->setTimezone($timezone)->getOffset() === $offset) { return $timezone; } } return null; } /** * Returns a new CarbonTimeZone object using the region string instead of offset string. */ public function toRegionTimeZone(?DateTimeInterface $date = null): ?self { $timezone = $this->toRegionName($date); if ($timezone !== null) { return new static($timezone); } if (Carbon::isStrictModeEnabled()) { throw new InvalidTimeZoneException('Unknown timezone for offset '.$this->getOffset($this->resolveCarbon($date)).' seconds.'); } return null; } /** * Cast to string (get timezone name). * * @return string */ public function __toString() { return $this->getName(); } /** * Return the type number: * * Type 1; A UTC offset, such as -0300 * Type 2; A timezone abbreviation, such as GMT * Type 3: A timezone identifier, such as Europe/London */ public function getType(): int { return preg_match('/"timezone_type";i:(\d)/', serialize($this), $match) ? (int) $match[1] : 3; } /** * Create a CarbonTimeZone from mixed input. * * @param DateTimeZone|string|int|null $object * * @return false|static */ public static function create($object = null) { return static::instance($object); } /** * Create a CarbonTimeZone from int/float hour offset. * * @param float $hourOffset number of hour of the timezone shift (can be decimal). * * @return false|static */ public static function createFromHourOffset(float $hourOffset) { return static::createFromMinuteOffset($hourOffset * Carbon::MINUTES_PER_HOUR); } /** * Create a CarbonTimeZone from int/float minute offset. * * @param float $minuteOffset number of total minutes of the timezone shift. * * @return false|static */ public static function createFromMinuteOffset(float $minuteOffset) { return static::instance(static::getOffsetNameFromMinuteOffset($minuteOffset)); } /** * Convert a total minutes offset into a standardized timezone offset string. * * @param float $minutes number of total minutes of the timezone shift. * * @return string */ public static function getOffsetNameFromMinuteOffset(float $minutes): string { $minutes = round($minutes); $unsignedMinutes = abs($minutes); return ($minutes < 0 ? '-' : '+'). str_pad((string) floor($unsignedMinutes / 60), 2, '0', STR_PAD_LEFT). ':'. str_pad((string) ($unsignedMinutes % 60), 2, '0', STR_PAD_LEFT); } private function resolveCarbon(?DateTimeInterface $date): DateTimeInterface { if ($date) { return $date; } if (isset($this->clock)) { return $this->clock->now()->setTimezone($this); } return Carbon::now($this); } }
PHP
{ "end_line": 120, "name": "instance", "signature": "public static function instance(", "start_line": 93 }
{ "class_name": "CarbonTimeZone", "class_signature": "class CarbonTimeZone", "namespace": "Carbon" }
toRegionName
Carbon/src/Carbon/CarbonTimeZone.php
public function toRegionName(?DateTimeInterface $date = null, int $isDST = 1): ?string { $name = $this->getName(); $firstChar = substr($name, 0, 1); if ($firstChar !== '+' && $firstChar !== '-') { return $name; } $date = $this->resolveCarbon($date); // Integer construction no longer supported since PHP 8 // @codeCoverageIgnoreStart try { $offset = @$this->getOffset($date) ?: 0; } catch (Throwable) { $offset = 0; } // @codeCoverageIgnoreEnd $name = @timezone_name_from_abbr('', $offset, $isDST); if ($name) { return $name; } foreach (timezone_identifiers_list() as $timezone) { if (Carbon::instance($date)->setTimezone($timezone)->getOffset() === $offset) { return $timezone; } } return null; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Traits\LocalFactory; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Exception; use Throwable; class CarbonTimeZone extends DateTimeZone { use LocalFactory; public const MAXIMUM_TIMEZONE_OFFSET = 99; public function __construct(string|int|float $timezone) { $this->initLocalFactory(); parent::__construct(static::getDateTimeZoneNameFromMixed($timezone)); } protected static function parseNumericTimezone(string|int|float $timezone): string { if (abs((float) $timezone) > static::MAXIMUM_TIMEZONE_OFFSET) { throw new InvalidTimeZoneException( 'Absolute timezone offset cannot be greater than '. static::MAXIMUM_TIMEZONE_OFFSET.'.', ); } return ($timezone >= 0 ? '+' : '').ltrim((string) $timezone, '+').':00'; } protected static function getDateTimeZoneNameFromMixed(string|int|float $timezone): string { if (\is_string($timezone)) { $timezone = preg_replace('/^\s*([+-]\d+)(\d{2})\s*$/', '$1:$2', $timezone); } if (is_numeric($timezone)) { return static::parseNumericTimezone($timezone); } return $timezone; } /** * Cast the current instance into the given class. * * @param class-string<DateTimeZone> $className The $className::instance() method will be called to cast the current object. * * @return DateTimeZone|mixed */ public function cast(string $className): mixed { if (!method_exists($className, 'instance')) { if (is_a($className, DateTimeZone::class, true)) { return new $className($this->getName()); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Create a CarbonTimeZone from mixed input. * * @param DateTimeZone|string|int|false|null $object original value to get CarbonTimeZone from it. * @param DateTimeZone|string|int|false|null $objectDump dump of the object for error messages. * * @throws InvalidTimeZoneException * * @return static|null */ public static function instance( DateTimeZone|string|int|false|null $object, DateTimeZone|string|int|false|null $objectDump = null, ): ?self { $timezone = $object; if ($timezone instanceof static) { return $timezone; } if ($timezone === null || $timezone === false) { return null; } try { if (!($timezone instanceof DateTimeZone)) { $name = static::getDateTimeZoneNameFromMixed($object); $timezone = new static($name); } return $timezone instanceof static ? $timezone : new static($timezone->getName()); } catch (Exception $exception) { throw new InvalidTimeZoneException( 'Unknown or bad timezone ('.($objectDump ?: $object).')', previous: $exception, ); } } /** * Returns abbreviated name of the current timezone according to DST setting. * * @param bool $dst * * @return string */ public function getAbbreviatedName(bool $dst = false): string { $name = $this->getName(); $date = new DateTimeImmutable($dst ? 'July 1' : 'January 1', $this); $timezone = $date->format('T'); $abbreviations = $this->listAbbreviations(); $matchingZones = array_merge($abbreviations[$timezone] ?? [], $abbreviations[strtolower($timezone)] ?? []); if ($matchingZones !== []) { foreach ($matchingZones as $zone) { if ($zone['timezone_id'] === $name && $zone['dst'] == $dst) { return $timezone; } } } foreach ($abbreviations as $abbreviation => $zones) { foreach ($zones as $zone) { if ($zone['timezone_id'] === $name && $zone['dst'] == $dst) { return strtoupper($abbreviation); } } } return 'unknown'; } /** * @alias getAbbreviatedName * * Returns abbreviated name of the current timezone according to DST setting. * * @param bool $dst * * @return string */ public function getAbbr(bool $dst = false): string { return $this->getAbbreviatedName($dst); } /** * Get the offset as string "sHH:MM" (such as "+00:00" or "-12:30"). */ public function toOffsetName(?DateTimeInterface $date = null): string { return static::getOffsetNameFromMinuteOffset( $this->getOffset($this->resolveCarbon($date)) / 60, ); } /** * Returns a new CarbonTimeZone object using the offset string instead of region string. */ public function toOffsetTimeZone(?DateTimeInterface $date = null): static { return new static($this->toOffsetName($date)); } /** * Returns the first region string (such as "America/Toronto") that matches the current timezone or * false if no match is found. * * @see timezone_name_from_abbr native PHP function. */ public function toRegionName(?DateTimeInterface $date = null, int $isDST = 1): ?string { $name = $this->getName(); $firstChar = substr($name, 0, 1); if ($firstChar !== '+' && $firstChar !== '-') { return $name; } $date = $this->resolveCarbon($date); // Integer construction no longer supported since PHP 8 // @codeCoverageIgnoreStart try { $offset = @$this->getOffset($date) ?: 0; } catch (Throwable) { $offset = 0; } // @codeCoverageIgnoreEnd $name = @timezone_name_from_abbr('', $offset, $isDST); if ($name) { return $name; } foreach (timezone_identifiers_list() as $timezone) { if (Carbon::instance($date)->setTimezone($timezone)->getOffset() === $offset) { return $timezone; } } return null; } /** * Returns a new CarbonTimeZone object using the region string instead of offset string. */ public function toRegionTimeZone(?DateTimeInterface $date = null): ?self { $timezone = $this->toRegionName($date); if ($timezone !== null) { return new static($timezone); } if (Carbon::isStrictModeEnabled()) { throw new InvalidTimeZoneException('Unknown timezone for offset '.$this->getOffset($this->resolveCarbon($date)).' seconds.'); } return null; } /** * Cast to string (get timezone name). * * @return string */ public function __toString() { return $this->getName(); } /** * Return the type number: * * Type 1; A UTC offset, such as -0300 * Type 2; A timezone abbreviation, such as GMT * Type 3: A timezone identifier, such as Europe/London */ public function getType(): int { return preg_match('/"timezone_type";i:(\d)/', serialize($this), $match) ? (int) $match[1] : 3; } /** * Create a CarbonTimeZone from mixed input. * * @param DateTimeZone|string|int|null $object * * @return false|static */ public static function create($object = null) { return static::instance($object); } /** * Create a CarbonTimeZone from int/float hour offset. * * @param float $hourOffset number of hour of the timezone shift (can be decimal). * * @return false|static */ public static function createFromHourOffset(float $hourOffset) { return static::createFromMinuteOffset($hourOffset * Carbon::MINUTES_PER_HOUR); } /** * Create a CarbonTimeZone from int/float minute offset. * * @param float $minuteOffset number of total minutes of the timezone shift. * * @return false|static */ public static function createFromMinuteOffset(float $minuteOffset) { return static::instance(static::getOffsetNameFromMinuteOffset($minuteOffset)); } /** * Convert a total minutes offset into a standardized timezone offset string. * * @param float $minutes number of total minutes of the timezone shift. * * @return string */ public static function getOffsetNameFromMinuteOffset(float $minutes): string { $minutes = round($minutes); $unsignedMinutes = abs($minutes); return ($minutes < 0 ? '-' : '+'). str_pad((string) floor($unsignedMinutes / 60), 2, '0', STR_PAD_LEFT). ':'. str_pad((string) ($unsignedMinutes % 60), 2, '0', STR_PAD_LEFT); } private function resolveCarbon(?DateTimeInterface $date): DateTimeInterface { if ($date) { return $date; } if (isset($this->clock)) { return $this->clock->now()->setTimezone($this); } return Carbon::now($this); } }
PHP
{ "end_line": 228, "name": "toRegionName", "signature": "public function toRegionName(?DateTimeInterface $date = null, int $isDST = 1): ?string", "start_line": 195 }
{ "class_name": "CarbonTimeZone", "class_signature": "class CarbonTimeZone", "namespace": "Carbon" }
toRegionTimeZone
Carbon/src/Carbon/CarbonTimeZone.php
public function toRegionTimeZone(?DateTimeInterface $date = null): ?self { $timezone = $this->toRegionName($date); if ($timezone !== null) { return new static($timezone); } if (Carbon::isStrictModeEnabled()) { throw new InvalidTimeZoneException('Unknown timezone for offset '.$this->getOffset($this->resolveCarbon($date)).' seconds.'); } return null; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Exceptions\InvalidCastException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Traits\LocalFactory; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Exception; use Throwable; class CarbonTimeZone extends DateTimeZone { use LocalFactory; public const MAXIMUM_TIMEZONE_OFFSET = 99; public function __construct(string|int|float $timezone) { $this->initLocalFactory(); parent::__construct(static::getDateTimeZoneNameFromMixed($timezone)); } protected static function parseNumericTimezone(string|int|float $timezone): string { if (abs((float) $timezone) > static::MAXIMUM_TIMEZONE_OFFSET) { throw new InvalidTimeZoneException( 'Absolute timezone offset cannot be greater than '. static::MAXIMUM_TIMEZONE_OFFSET.'.', ); } return ($timezone >= 0 ? '+' : '').ltrim((string) $timezone, '+').':00'; } protected static function getDateTimeZoneNameFromMixed(string|int|float $timezone): string { if (\is_string($timezone)) { $timezone = preg_replace('/^\s*([+-]\d+)(\d{2})\s*$/', '$1:$2', $timezone); } if (is_numeric($timezone)) { return static::parseNumericTimezone($timezone); } return $timezone; } /** * Cast the current instance into the given class. * * @param class-string<DateTimeZone> $className The $className::instance() method will be called to cast the current object. * * @return DateTimeZone|mixed */ public function cast(string $className): mixed { if (!method_exists($className, 'instance')) { if (is_a($className, DateTimeZone::class, true)) { return new $className($this->getName()); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } /** * Create a CarbonTimeZone from mixed input. * * @param DateTimeZone|string|int|false|null $object original value to get CarbonTimeZone from it. * @param DateTimeZone|string|int|false|null $objectDump dump of the object for error messages. * * @throws InvalidTimeZoneException * * @return static|null */ public static function instance( DateTimeZone|string|int|false|null $object, DateTimeZone|string|int|false|null $objectDump = null, ): ?self { $timezone = $object; if ($timezone instanceof static) { return $timezone; } if ($timezone === null || $timezone === false) { return null; } try { if (!($timezone instanceof DateTimeZone)) { $name = static::getDateTimeZoneNameFromMixed($object); $timezone = new static($name); } return $timezone instanceof static ? $timezone : new static($timezone->getName()); } catch (Exception $exception) { throw new InvalidTimeZoneException( 'Unknown or bad timezone ('.($objectDump ?: $object).')', previous: $exception, ); } } /** * Returns abbreviated name of the current timezone according to DST setting. * * @param bool $dst * * @return string */ public function getAbbreviatedName(bool $dst = false): string { $name = $this->getName(); $date = new DateTimeImmutable($dst ? 'July 1' : 'January 1', $this); $timezone = $date->format('T'); $abbreviations = $this->listAbbreviations(); $matchingZones = array_merge($abbreviations[$timezone] ?? [], $abbreviations[strtolower($timezone)] ?? []); if ($matchingZones !== []) { foreach ($matchingZones as $zone) { if ($zone['timezone_id'] === $name && $zone['dst'] == $dst) { return $timezone; } } } foreach ($abbreviations as $abbreviation => $zones) { foreach ($zones as $zone) { if ($zone['timezone_id'] === $name && $zone['dst'] == $dst) { return strtoupper($abbreviation); } } } return 'unknown'; } /** * @alias getAbbreviatedName * * Returns abbreviated name of the current timezone according to DST setting. * * @param bool $dst * * @return string */ public function getAbbr(bool $dst = false): string { return $this->getAbbreviatedName($dst); } /** * Get the offset as string "sHH:MM" (such as "+00:00" or "-12:30"). */ public function toOffsetName(?DateTimeInterface $date = null): string { return static::getOffsetNameFromMinuteOffset( $this->getOffset($this->resolveCarbon($date)) / 60, ); } /** * Returns a new CarbonTimeZone object using the offset string instead of region string. */ public function toOffsetTimeZone(?DateTimeInterface $date = null): static { return new static($this->toOffsetName($date)); } /** * Returns the first region string (such as "America/Toronto") that matches the current timezone or * false if no match is found. * * @see timezone_name_from_abbr native PHP function. */ public function toRegionName(?DateTimeInterface $date = null, int $isDST = 1): ?string { $name = $this->getName(); $firstChar = substr($name, 0, 1); if ($firstChar !== '+' && $firstChar !== '-') { return $name; } $date = $this->resolveCarbon($date); // Integer construction no longer supported since PHP 8 // @codeCoverageIgnoreStart try { $offset = @$this->getOffset($date) ?: 0; } catch (Throwable) { $offset = 0; } // @codeCoverageIgnoreEnd $name = @timezone_name_from_abbr('', $offset, $isDST); if ($name) { return $name; } foreach (timezone_identifiers_list() as $timezone) { if (Carbon::instance($date)->setTimezone($timezone)->getOffset() === $offset) { return $timezone; } } return null; } /** * Returns a new CarbonTimeZone object using the region string instead of offset string. */ public function toRegionTimeZone(?DateTimeInterface $date = null): ?self { $timezone = $this->toRegionName($date); if ($timezone !== null) { return new static($timezone); } if (Carbon::isStrictModeEnabled()) { throw new InvalidTimeZoneException('Unknown timezone for offset '.$this->getOffset($this->resolveCarbon($date)).' seconds.'); } return null; } /** * Cast to string (get timezone name). * * @return string */ public function __toString() { return $this->getName(); } /** * Return the type number: * * Type 1; A UTC offset, such as -0300 * Type 2; A timezone abbreviation, such as GMT * Type 3: A timezone identifier, such as Europe/London */ public function getType(): int { return preg_match('/"timezone_type";i:(\d)/', serialize($this), $match) ? (int) $match[1] : 3; } /** * Create a CarbonTimeZone from mixed input. * * @param DateTimeZone|string|int|null $object * * @return false|static */ public static function create($object = null) { return static::instance($object); } /** * Create a CarbonTimeZone from int/float hour offset. * * @param float $hourOffset number of hour of the timezone shift (can be decimal). * * @return false|static */ public static function createFromHourOffset(float $hourOffset) { return static::createFromMinuteOffset($hourOffset * Carbon::MINUTES_PER_HOUR); } /** * Create a CarbonTimeZone from int/float minute offset. * * @param float $minuteOffset number of total minutes of the timezone shift. * * @return false|static */ public static function createFromMinuteOffset(float $minuteOffset) { return static::instance(static::getOffsetNameFromMinuteOffset($minuteOffset)); } /** * Convert a total minutes offset into a standardized timezone offset string. * * @param float $minutes number of total minutes of the timezone shift. * * @return string */ public static function getOffsetNameFromMinuteOffset(float $minutes): string { $minutes = round($minutes); $unsignedMinutes = abs($minutes); return ($minutes < 0 ? '-' : '+'). str_pad((string) floor($unsignedMinutes / 60), 2, '0', STR_PAD_LEFT). ':'. str_pad((string) ($unsignedMinutes % 60), 2, '0', STR_PAD_LEFT); } private function resolveCarbon(?DateTimeInterface $date): DateTimeInterface { if ($date) { return $date; } if (isset($this->clock)) { return $this->clock->now()->setTimezone($this); } return Carbon::now($this); } }
PHP
{ "end_line": 246, "name": "toRegionTimeZone", "signature": "public function toRegionTimeZone(?DateTimeInterface $date = null): ?self", "start_line": 233 }
{ "class_name": "CarbonTimeZone", "class_signature": "class CarbonTimeZone", "namespace": "Carbon" }
genericMacro
Carbon/src/Carbon/Factory.php
public function genericMacro(callable $macro, int $priority = 0): void { $genericMacros = $this->getSettings()['genericMacros'] ?? []; if (!isset($genericMacros[$priority])) { $genericMacros[$priority] = []; krsort($genericMacros, SORT_NUMERIC); } $genericMacros[$priority][] = $macro; $this->mergeSettings([ 'genericMacros' => $genericMacros, ]); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Closure; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use InvalidArgumentException; use ReflectionMethod; use RuntimeException; use Symfony\Contracts\Translation\TranslatorInterface; use Throwable; /** * A factory to generate Carbon instances with common settings. * * <autodoc generated by `composer phpdoc`> * * @method bool canBeCreatedFromFormat(?string $date, string $format) Checks if the (date)time string is in a given format and valid to create a * new instance. * @method ?Carbon create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null) Create a new Carbon instance from a specific date and time. * If any of $year, $month or $day are set to null their now() values will * be used. * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * If $hour is not null then the default values for $minute and $second * will be 0. * @method Carbon createFromDate($year = null, $month = null, $day = null, $timezone = null) Create a Carbon instance from just a date. The time portion is set to now. * @method ?Carbon createFromFormat($format, $time, $timezone = null) Create a Carbon instance from a specific format. * @method ?Carbon createFromIsoFormat(string $format, string $time, $timezone = null, ?string $locale = 'en', ?TranslatorInterface $translator = null) Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()). * @method ?Carbon createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null) Create a Carbon instance from a specific format and a string in a given language. * @method ?Carbon createFromLocaleIsoFormat(string $format, string $locale, string $time, $timezone = null) Create a Carbon instance from a specific ISO format and a string in a given language. * @method Carbon createFromTime($hour = 0, $minute = 0, $second = 0, $timezone = null) Create a Carbon instance from just a time. The date portion is set to today. * @method Carbon createFromTimeString(string $time, DateTimeZone|string|int|null $timezone = null) Create a Carbon instance from a time string. The date portion is set to today. * @method Carbon createFromTimestamp(string|int|float $timestamp, DateTimeZone|string|int|null $timezone = null) Create a Carbon instance from a timestamp and set the timezone (UTC by default). * Timestamp input can be given as int, float or a string containing one or more numbers. * @method Carbon createFromTimestampMs(string|int|float $timestamp, DateTimeZone|string|int|null $timezone = null) Create a Carbon instance from a timestamp in milliseconds. * Timestamp input can be given as int, float or a string containing one or more numbers. * @method Carbon createFromTimestampMsUTC($timestamp) Create a Carbon instance from a timestamp in milliseconds. * Timestamp input can be given as int, float or a string containing one or more numbers. * @method Carbon createFromTimestampUTC(string|int|float $timestamp) Create a Carbon instance from a timestamp keeping the timezone to UTC. * Timestamp input can be given as int, float or a string containing one or more numbers. * @method Carbon createMidnightDate($year = null, $month = null, $day = null, $timezone = null) Create a Carbon instance from just a date. The time portion is set to midnight. * @method ?Carbon createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null) Create a new safe Carbon instance from a specific date and time. * If any of $year, $month or $day are set to null their now() values will * be used. * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * If $hour is not null then the default values for $minute and $second * will be 0. * If one of the set values is not valid, an InvalidDateException * will be thrown. * @method Carbon createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $timezone = null) Create a new Carbon instance from a specific date and time using strict validation. * @method mixed executeWithLocale(string $locale, callable $func) Set the current locale to the given, execute the passed function, reset the locale to previous one, * then return the result of the closure (or null if the closure was void). * @method Carbon fromSerialized($value, array $options = []) Create an instance from a serialized string. * If $value is not from a trusted source, consider using the allowed_classes option to limit * the types of objects that can be built, for instance: * @method array getAvailableLocales() Returns the list of internally available locales and already loaded custom locales. * (It will ignore custom translator dynamic loading.) * @method Language[] getAvailableLocalesInfo() Returns list of Language object for each available locale. This object allow you to get the ISO name, native * name, region and variant of the locale. * @method array getDays() Get the days of the week. * @method ?string getFallbackLocale() Get the fallback locale. * @method array getFormatsToIsoReplacements() List of replacements from date() format to isoFormat(). * @method array getIsoUnits() Returns list of locale units for ISO formatting. * @method array|false getLastErrors() {@inheritdoc} * @method string getLocale() Get the current translator locale. * @method int getMidDayAt() get midday/noon hour * @method string getTimeFormatByPrecision(string $unitPrecision) Return a format from H:i to H:i:s.u according to given unit precision. * @method string|Closure|null getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null) Returns raw translation message for a given key. * @method int getWeekEndsAt(?string $locale = null) Get the last day of week. * @method int getWeekStartsAt(?string $locale = null) Get the first day of week. * @method bool hasRelativeKeywords(?string $time) Determine if a time string will produce a relative date. * @method Carbon instance(DateTimeInterface $date) Create a Carbon instance from a DateTime one. * @method bool isImmutable() Returns true if the current class/instance is immutable. * @method bool isModifiableUnit($unit) Returns true if a property can be changed via setter. * @method bool isMutable() Returns true if the current class/instance is mutable. * @method bool localeHasDiffOneDayWords(string $locale) Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow). * Support is considered enabled if the 3 words are translated in the given locale. * @method bool localeHasDiffSyntax(string $locale) Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after). * Support is considered enabled if the 4 sentences are translated in the given locale. * @method bool localeHasDiffTwoDayWords(string $locale) Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow). * Support is considered enabled if the 2 words are translated in the given locale. * @method bool localeHasPeriodSyntax($locale) Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X). * Support is considered enabled if the 4 sentences are translated in the given locale. * @method bool localeHasShortUnits(string $locale) Returns true if the given locale is internally supported and has short-units support. * Support is considered enabled if either year, day or hour has a short variant translated. * @method ?Carbon make($var, DateTimeZone|string|null $timezone = null) Make a Carbon instance from given variable if possible. * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals * and recurrences). Throw an exception for invalid format, but otherwise return null. * @method void mixin(object|string $mixin) Mix another object into the class. * @method Carbon now(DateTimeZone|string|int|null $timezone = null) Get a Carbon instance for the current date and time. * @method Carbon parse(DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null) Create a carbon instance from a string. * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * @method Carbon parseFromLocale(string $time, ?string $locale = null, DateTimeZone|string|int|null $timezone = null) Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.). * @method string pluralUnit(string $unit) Returns standardized plural of a given singular/plural unit name (in English). * @method ?Carbon rawCreateFromFormat(string $format, string $time, $timezone = null) Create a Carbon instance from a specific format. * @method Carbon rawParse(DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null) Create a carbon instance from a string. * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * @method void setFallbackLocale(string $locale) Set the fallback locale. * @method void setLocale(string $locale) Set the current translator locale and indicate if the source locale file exists. * Pass 'auto' as locale to use the closest language to the current LC_TIME locale. * @method void setMidDayAt($hour) @deprecated To avoid conflict between different third-party libraries, static setters should not be used. * You should rather consider mid-day is always 12pm, then if you need to test if it's an other * hour, test it explicitly: * $date->format('G') == 13 * or to set explicitly to a given hour: * $date->setTime(13, 0, 0, 0) * Set midday/noon hour * @method string singularUnit(string $unit) Returns standardized singular of a given singular/plural unit name (in English). * @method void sleep(int|float $seconds) * @method Carbon today(DateTimeZone|string|int|null $timezone = null) Create a Carbon instance for today. * @method Carbon tomorrow(DateTimeZone|string|int|null $timezone = null) Create a Carbon instance for tomorrow. * @method string translateTimeString(string $timeString, ?string $from = null, ?string $to = null, int $mode = CarbonInterface::TRANSLATE_ALL) Translate a time string from a locale to an other. * @method string translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null) Translate using translation string or callback available. * @method Carbon yesterday(DateTimeZone|string|int|null $timezone = null) Create a Carbon instance for yesterday. * * </autodoc> */ class Factory { protected string $className = Carbon::class; protected array $settings = []; /** * A test Carbon instance to be returned when now instances are created. */ protected Closure|CarbonInterface|null $testNow = null; /** * The timezone to restore to when clearing the time mock. */ protected ?string $testDefaultTimezone = null; /** * Is true when test-now is generated by a closure and timezone should be taken on the fly from it. */ protected bool $useTimezoneFromTestNow = false; /** * Default translator. */ protected TranslatorInterface $translator; /** * Days of weekend. */ protected array $weekendDays = [ CarbonInterface::SATURDAY, CarbonInterface::SUNDAY, ]; /** * Format regex patterns. * * @var array<string, string> */ protected array $regexFormats = [ 'd' => '(3[01]|[12][0-9]|0[1-9])', 'D' => '(Sun|Mon|Tue|Wed|Thu|Fri|Sat)', 'j' => '([123][0-9]|[1-9])', 'l' => '([a-zA-Z]{2,})', 'N' => '([1-7])', 'S' => '(st|nd|rd|th)', 'w' => '([0-6])', 'z' => '(36[0-5]|3[0-5][0-9]|[12][0-9]{2}|[1-9]?[0-9])', 'W' => '(5[012]|[1-4][0-9]|0?[1-9])', 'F' => '([a-zA-Z]{2,})', 'm' => '(1[012]|0[1-9])', 'M' => '([a-zA-Z]{3})', 'n' => '(1[012]|[1-9])', 't' => '(2[89]|3[01])', 'L' => '(0|1)', 'o' => '([1-9][0-9]{0,4})', 'Y' => '([1-9]?[0-9]{4})', 'y' => '([0-9]{2})', 'a' => '(am|pm)', 'A' => '(AM|PM)', 'B' => '([0-9]{3})', 'g' => '(1[012]|[1-9])', 'G' => '(2[0-3]|1?[0-9])', 'h' => '(1[012]|0[1-9])', 'H' => '(2[0-3]|[01][0-9])', 'i' => '([0-5][0-9])', 's' => '([0-5][0-9])', 'u' => '([0-9]{1,6})', 'v' => '([0-9]{1,3})', 'e' => '([a-zA-Z]{1,5})|([a-zA-Z]*\\/[a-zA-Z]*)', 'I' => '(0|1)', 'O' => '([+-](1[0123]|0[0-9])[0134][05])', 'P' => '([+-](1[0123]|0[0-9]):[0134][05])', 'p' => '(Z|[+-](1[0123]|0[0-9]):[0134][05])', 'T' => '([a-zA-Z]{1,5})', 'Z' => '(-?[1-5]?[0-9]{1,4})', 'U' => '([0-9]*)', // The formats below are combinations of the above formats. 'c' => '(([1-9]?[0-9]{4})-(1[012]|0[1-9])-(3[01]|[12][0-9]|0[1-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])[+-](1[012]|0[0-9]):([0134][05]))', // Y-m-dTH:i:sP 'r' => '(([a-zA-Z]{3}), ([123][0-9]|0[1-9]) ([a-zA-Z]{3}) ([1-9]?[0-9]{4}) (2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9]) [+-](1[012]|0[0-9])([0134][05]))', // D, d M Y H:i:s O ]; /** * Format modifiers (such as available in createFromFormat) regex patterns. * * @var array */ protected array $regexFormatModifiers = [ '*' => '.+', ' ' => '[ ]', '#' => '[;:\\/.,()-]', '?' => '([^a]|[a])', '!' => '', '|' => '', '+' => '', ]; public function __construct(array $settings = [], ?string $className = null) { if ($className) { $this->className = $className; } $this->settings = $settings; } public function getClassName(): string { return $this->className; } public function setClassName(string $className): self { $this->className = $className; return $this; } public function className(?string $className = null): self|string { return $className === null ? $this->getClassName() : $this->setClassName($className); } public function getSettings(): array { return $this->settings; } public function setSettings(array $settings): self { $this->settings = $settings; return $this; } public function settings(?array $settings = null): self|array { return $settings === null ? $this->getSettings() : $this->setSettings($settings); } public function mergeSettings(array $settings): self { $this->settings = array_merge($this->settings, $settings); return $this; } public function setHumanDiffOptions(int $humanDiffOptions): void { $this->mergeSettings([ 'humanDiffOptions' => $humanDiffOptions, ]); } public function enableHumanDiffOption($humanDiffOption): void { $this->setHumanDiffOptions($this->getHumanDiffOptions() | $humanDiffOption); } public function disableHumanDiffOption(int $humanDiffOption): void { $this->setHumanDiffOptions($this->getHumanDiffOptions() & ~$humanDiffOption); } public function getHumanDiffOptions(): int { return (int) ($this->getSettings()['humanDiffOptions'] ?? 0); } /** * Register a custom macro. * * Pass null macro to remove it. * * @example * ``` * $userSettings = [ * 'locale' => 'pt', * 'timezone' => 'America/Sao_Paulo', * ]; * $factory->macro('userFormat', function () use ($userSettings) { * return $this->copy()->locale($userSettings['locale'])->tz($userSettings['timezone'])->calendar(); * }); * echo $factory->yesterday()->hours(11)->userFormat(); * ``` * * @param-closure-this static $macro */ public function macro(string $name, ?callable $macro): void { $macros = $this->getSettings()['macros'] ?? []; $macros[$name] = $macro; $this->mergeSettings([ 'macros' => $macros, ]); } /** * Remove all macros and generic macros. */ public function resetMacros(): void { $this->mergeSettings([ 'macros' => null, 'genericMacros' => null, ]); } /** * Register a custom macro. * * @param callable $macro * @param int $priority marco with higher priority is tried first * * @return void */ public function genericMacro(callable $macro, int $priority = 0): void { $genericMacros = $this->getSettings()['genericMacros'] ?? []; if (!isset($genericMacros[$priority])) { $genericMacros[$priority] = []; krsort($genericMacros, SORT_NUMERIC); } $genericMacros[$priority][] = $macro; $this->mergeSettings([ 'genericMacros' => $genericMacros, ]); } /** * Checks if macro is registered globally. */ public function hasMacro(string $name): bool { return isset($this->getSettings()['macros'][$name]); } /** * Get the raw callable macro registered globally for a given name. */ public function getMacro(string $name): ?callable { return $this->getSettings()['macros'][$name] ?? null; } /** * Set the default translator instance to use. */ public function setTranslator(TranslatorInterface $translator): void { $this->translator = $translator; } /** * Initialize the default translator instance if necessary. */ public function getTranslator(): TranslatorInterface { return $this->translator ??= Translator::get(); } /** * Reset the format used to the default when type juggling a Carbon instance to a string * * @return void */ public function resetToStringFormat(): void { $this->setToStringFormat(null); } /** * Set the default format used when type juggling a Carbon instance to a string. */ public function setToStringFormat(string|Closure|null $format): void { $this->mergeSettings([ 'toStringFormat' => $format, ]); } /** * JSON serialize all Carbon instances using the given callback. */ public function serializeUsing(string|callable|null $format): void { $this->mergeSettings([ 'toJsonFormat' => $format, ]); } /** * Enable the strict mode (or disable with passing false). */ public function useStrictMode(bool $strictModeEnabled = true): void { $this->mergeSettings([ 'strictMode' => $strictModeEnabled, ]); } /** * Returns true if the strict mode is globally in use, false else. * (It can be overridden in specific instances.) */ public function isStrictModeEnabled(): bool { return $this->getSettings()['strictMode'] ?? true; } /** * Indicates if months should be calculated with overflow. */ public function useMonthsOverflow(bool $monthsOverflow = true): void { $this->mergeSettings([ 'monthOverflow' => $monthsOverflow, ]); } /** * Reset the month overflow behavior. */ public function resetMonthsOverflow(): void { $this->useMonthsOverflow(); } /** * Get the month overflow global behavior (can be overridden in specific instances). */ public function shouldOverflowMonths(): bool { return $this->getSettings()['monthOverflow'] ?? true; } /** * Indicates if years should be calculated with overflow. */ public function useYearsOverflow(bool $yearsOverflow = true): void { $this->mergeSettings([ 'yearOverflow' => $yearsOverflow, ]); } /** * Reset the month overflow behavior. */ public function resetYearsOverflow(): void { $this->useYearsOverflow(); } /** * Get the month overflow global behavior (can be overridden in specific instances). */ public function shouldOverflowYears(): bool { return $this->getSettings()['yearOverflow'] ?? true; } /** * Get weekend days * * @return array */ public function getWeekendDays(): array { return $this->weekendDays; } /** * Set weekend days */ public function setWeekendDays(array $days): void { $this->weekendDays = $days; } /** * Checks if the (date)time string is in a given format. * * @example * ``` * Carbon::hasFormat('11:12:45', 'h:i:s'); // true * Carbon::hasFormat('13:12:45', 'h:i:s'); // false * ``` */ public function hasFormat(string $date, string $format): bool { // createFromFormat() is known to handle edge cases silently. // E.g. "1975-5-1" (Y-n-j) will still be parsed correctly when "Y-m-d" is supplied as the format. // To ensure we're really testing against our desired format, perform an additional regex validation. return $this->matchFormatPattern($date, preg_quote($format, '/'), $this->regexFormats); } /** * Checks if the (date)time string is in a given format. * * @example * ``` * Carbon::hasFormatWithModifiers('31/08/2015', 'd#m#Y'); // true * Carbon::hasFormatWithModifiers('31/08/2015', 'm#d#Y'); // false * ``` */ public function hasFormatWithModifiers(string $date, string $format): bool { return $this->matchFormatPattern($date, $format, array_merge($this->regexFormats, $this->regexFormatModifiers)); } /** * Set a Carbon instance (real or mock) to be returned when a "now" * instance is created. The provided instance will be returned * specifically under the following conditions: * - A call to the static now() method, ex. Carbon::now() * - When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null) * - When the string "now" is passed to the constructor or parse(), ex. new Carbon('now') * - When a string containing the desired time is passed to Carbon::parse(). * * Note the timezone parameter was left out of the examples above and * has no affect as the mock value will be returned regardless of its value. * * Only the moment is mocked with setTestNow(), the timezone will still be the one passed * as parameter of date_default_timezone_get() as a fallback (see setTestNowAndTimezone()). * * To clear the test instance call this method using the default * parameter of null. * * /!\ Use this method for unit tests only. * * @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance */ public function setTestNow(mixed $testNow = null): void { $this->useTimezoneFromTestNow = false; $this->testNow = $testNow instanceof self || $testNow instanceof Closure ? $testNow : $this->make($testNow); } /** * Set a Carbon instance (real or mock) to be returned when a "now" * instance is created. The provided instance will be returned * specifically under the following conditions: * - A call to the static now() method, ex. Carbon::now() * - When a null (or blank string) is passed to the constructor or parse(), ex. new Carbon(null) * - When the string "now" is passed to the constructor or parse(), ex. new Carbon('now') * - When a string containing the desired time is passed to Carbon::parse(). * * It will also align default timezone (e.g. call date_default_timezone_set()) with * the second argument or if null, with the timezone of the given date object. * * To clear the test instance call this method using the default * parameter of null. * * /!\ Use this method for unit tests only. * * @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance */ public function setTestNowAndTimezone(mixed $testNow = null, $timezone = null): void { if ($testNow) { $this->testDefaultTimezone ??= date_default_timezone_get(); } $useDateInstanceTimezone = $testNow instanceof DateTimeInterface; if ($useDateInstanceTimezone) { $this->setDefaultTimezone($testNow->getTimezone()->getName(), $testNow); } $this->setTestNow($testNow); $this->useTimezoneFromTestNow = ($timezone === null && $testNow instanceof Closure); if (!$useDateInstanceTimezone) { $now = $this->getMockedTestNow(\func_num_args() === 1 ? null : $timezone); $this->setDefaultTimezone($now?->tzName ?? $this->testDefaultTimezone ?? 'UTC', $now); } if (!$testNow) { $this->testDefaultTimezone = null; } } /** * Temporarily sets a static date to be used within the callback. * Using setTestNow to set the date, executing the callback, then * clearing the test instance. * * /!\ Use this method for unit tests only. * * @template T * * @param DateTimeInterface|Closure|static|string|false|null $testNow real or mock Carbon instance * @param Closure(): T $callback * * @return T */ public function withTestNow(mixed $testNow, callable $callback): mixed { $this->setTestNow($testNow); try { $result = $callback(); } finally { $this->setTestNow(); } return $result; } /** * Get the Carbon instance (real or mock) to be returned when a "now" * instance is created. * * @return Closure|CarbonInterface|null the current instance used for testing */ public function getTestNow(): Closure|CarbonInterface|null { if ($this->testNow === null) { $factory = FactoryImmutable::getDefaultInstance(); if ($factory !== $this) { return $factory->getTestNow(); } } return $this->testNow; } public function handleTestNowClosure( Closure|CarbonInterface|null $testNow, DateTimeZone|string|int|null $timezone = null, ): ?CarbonInterface { if ($testNow instanceof Closure) { $callback = Callback::fromClosure($testNow); $realNow = new DateTimeImmutable('now'); $testNow = $testNow($callback->prepareParameter($this->parse( $realNow->format('Y-m-d H:i:s.u'), $timezone ?? $realNow->getTimezone(), ))); if ($testNow !== null && !($testNow instanceof DateTimeInterface)) { $function = $callback->getReflectionFunction(); $type = \is_object($testNow) ? $testNow::class : \gettype($testNow); throw new RuntimeException( 'The test closure defined in '.$function->getFileName(). ' at line '.$function->getStartLine().' returned '.$type. '; expected '.CarbonInterface::class.'|null', ); } if (!($testNow instanceof CarbonInterface)) { $timezone ??= $this->useTimezoneFromTestNow ? $testNow->getTimezone() : null; $testNow = $this->__call('instance', [$testNow, $timezone]); } } return $testNow; } /** * Determine if there is a valid test instance set. A valid test instance * is anything that is not null. * * @return bool true if there is a test instance, otherwise false */ public function hasTestNow(): bool { return $this->getTestNow() !== null; } public function withTimeZone(DateTimeZone|string|int|null $timezone): static { $factory = clone $this; $factory->settings['timezone'] = $timezone; return $factory; } public function __call(string $name, array $arguments): mixed { $method = new ReflectionMethod($this->className, $name); $settings = $this->settings; if ($settings && isset($settings['timezone'])) { $timezoneParameters = array_filter($method->getParameters(), function ($parameter) { return \in_array($parameter->getName(), ['tz', 'timezone'], true); }); $timezoneSetting = $settings['timezone']; if (isset($arguments[0]) && \in_array($name, ['instance', 'make', 'create', 'parse'], true)) { if ($arguments[0] instanceof DateTimeInterface) { $settings['innerTimezone'] = $settings['timezone']; } elseif (\is_string($arguments[0]) && date_parse($arguments[0])['is_localtime']) { unset($settings['timezone'], $settings['innerTimezone']); } } if (\count($timezoneParameters)) { $index = key($timezoneParameters); if (!isset($arguments[$index])) { array_splice($arguments, key($timezoneParameters), 0, [$timezoneSetting]); } unset($settings['timezone']); } } $clock = FactoryImmutable::getCurrentClock(); FactoryImmutable::setCurrentClock($this); try { $result = $this->className::$name(...$arguments); } finally { FactoryImmutable::setCurrentClock($clock); } if (isset($this->translator)) { $settings['translator'] = $this->translator; } return $result instanceof CarbonInterface && !empty($settings) ? $result->settings($settings) : $result; } /** * Get the mocked date passed in setTestNow() and if it's a Closure, execute it. */ protected function getMockedTestNow(DateTimeZone|string|int|null $timezone): ?CarbonInterface { $testNow = $this->handleTestNowClosure($this->getTestNow()); if ($testNow instanceof CarbonInterface) { $testNow = $testNow->avoidMutation(); if ($timezone !== null) { return $testNow->setTimezone($timezone); } } return $testNow; } /** * Checks if the (date)time string is in a given format with * given list of pattern replacements. * * @example * ``` * Carbon::hasFormat('11:12:45', 'h:i:s'); // true * Carbon::hasFormat('13:12:45', 'h:i:s'); // false * ``` * * @param string $date * @param string $format * @param array $replacements * * @return bool */ private function matchFormatPattern(string $date, string $format, array $replacements): bool { // Preg quote, but remove escaped backslashes since we'll deal with escaped characters in the format string. $regex = str_replace('\\\\', '\\', $format); // Replace not-escaped letters $regex = preg_replace_callback( '/(?<!\\\\)((?:\\\\{2})*)(['.implode('', array_keys($replacements)).'])/', static fn ($match) => $match[1].strtr($match[2], $replacements), $regex, ); // Replace escaped letters by the letter itself $regex = preg_replace('/(?<!\\\\)((?:\\\\{2})*)\\\\(\w)/', '$1$2', $regex); // Escape not escaped slashes $regex = preg_replace('#(?<!\\\\)((?:\\\\{2})*)/#', '$1\\/', $regex); return (bool) @preg_match('/^'.$regex.'$/', $date); } private function setDefaultTimezone(string $timezone, ?DateTimeInterface $date = null): void { $previous = null; $success = false; try { $success = date_default_timezone_set($timezone); } catch (Throwable $exception) { $previous = $exception; } if (!$success) { $suggestion = @CarbonTimeZone::create($timezone)->toRegionName($date); throw new InvalidArgumentException( "Timezone ID '$timezone' is invalid". ($suggestion && $suggestion !== $timezone ? ", did you mean '$suggestion'?" : '.')."\n". "It must be one of the IDs from DateTimeZone::listIdentifiers(),\n". 'For the record, hours/minutes offset are relevant only for a particular moment, '. 'but not as a default timezone.', 0, $previous ); } } }
PHP
{ "end_line": 369, "name": "genericMacro", "signature": "public function genericMacro(callable $macro, int $priority = 0): void", "start_line": 355 }
{ "class_name": "Factory", "class_signature": "class Factory", "namespace": "Carbon" }
fromName
Carbon/src/Carbon/Month.php
public static function fromName(string $name, ?string $locale = null): self { try { return self::from(CarbonImmutable::parseFromLocale("$name 1", $locale)->month); } catch (InvalidFormatException $exception) { // Possibly current language expect a dot after short name, but it's missing if ($locale !== null && !mb_strlen($name) < 4 && !str_ends_with($name, '.')) { try { return self::from(CarbonImmutable::parseFromLocale("$name. 1", $locale)->month); } catch (InvalidFormatException $e) { // Throw previous error } } throw $exception; } }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Exceptions\InvalidFormatException; enum Month: int { // Using constants is only safe starting from PHP 8.2 case January = 1; // CarbonInterface::JANUARY case February = 2; // CarbonInterface::FEBRUARY case March = 3; // CarbonInterface::MARCH case April = 4; // CarbonInterface::APRIL case May = 5; // CarbonInterface::MAY case June = 6; // CarbonInterface::JUNE case July = 7; // CarbonInterface::JULY case August = 8; // CarbonInterface::AUGUST case September = 9; // CarbonInterface::SEPTEMBER case October = 10; // CarbonInterface::OCTOBER case November = 11; // CarbonInterface::NOVEMBER case December = 12; // CarbonInterface::DECEMBER public static function int(self|int|null $value): ?int { return $value instanceof self ? $value->value : $value; } public static function fromNumber(int $number): self { $month = $number % CarbonInterface::MONTHS_PER_YEAR; return self::from($month + ($month < 1 ? CarbonInterface::MONTHS_PER_YEAR : 0)); } public static function fromName(string $name, ?string $locale = null): self { try { return self::from(CarbonImmutable::parseFromLocale("$name 1", $locale)->month); } catch (InvalidFormatException $exception) { // Possibly current language expect a dot after short name, but it's missing if ($locale !== null && !mb_strlen($name) < 4 && !str_ends_with($name, '.')) { try { return self::from(CarbonImmutable::parseFromLocale("$name. 1", $locale)->month); } catch (InvalidFormatException $e) { // Throw previous error } } throw $exception; } } public function ofTheYear(CarbonImmutable|int|null $now = null): CarbonImmutable { if (\is_int($now)) { return CarbonImmutable::create($now, $this->value); } $modifier = $this->name.' 1st'; return $now?->modify($modifier) ?? new CarbonImmutable($modifier); } public function locale(string $locale, ?CarbonImmutable $now = null): CarbonImmutable { return $this->ofTheYear($now)->locale($locale); } }
PHP
{ "end_line": 62, "name": "fromName", "signature": "public static function fromName(string $name, ?string $locale = null): self", "start_line": 46 }
{ "class_name": "", "class_signature": "", "namespace": "Carbon" }
fromName
Carbon/src/Carbon/Unit.php
public static function fromName(string $name, ?string $locale = null): self { if ($locale !== null) { $messages = Translator::get($locale)->getMessages($locale) ?? []; if ($messages !== []) { $lowerName = mb_strtolower($name); foreach (self::cases() as $unit) { foreach (['', '_from_now', '_ago', '_after', '_before'] as $suffix) { $message = $messages[$unit->value.$suffix] ?? null; if (\is_string($message)) { $words = explode('|', mb_strtolower(preg_replace( '/[{\[\]].+?[}\[\]]/', '', str_replace(':count', '', $message), ))); foreach ($words as $word) { if (trim($word) === $lowerName) { return $unit; } } } } } } } return self::from(CarbonImmutable::singularUnit($name)); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; enum Unit: string { case Microsecond = 'microsecond'; case Millisecond = 'millisecond'; case Second = 'second'; case Minute = 'minute'; case Hour = 'hour'; case Day = 'day'; case Week = 'week'; case Month = 'month'; case Quarter = 'quarter'; case Year = 'year'; case Decade = 'decade'; case Century = 'century'; case Millennium = 'millennium'; public static function toName(self|string $unit): string { return $unit instanceof self ? $unit->value : $unit; } /** @internal */ public static function toNameIfUnit(mixed $unit): mixed { return $unit instanceof self ? $unit->value : $unit; } public static function fromName(string $name, ?string $locale = null): self { if ($locale !== null) { $messages = Translator::get($locale)->getMessages($locale) ?? []; if ($messages !== []) { $lowerName = mb_strtolower($name); foreach (self::cases() as $unit) { foreach (['', '_from_now', '_ago', '_after', '_before'] as $suffix) { $message = $messages[$unit->value.$suffix] ?? null; if (\is_string($message)) { $words = explode('|', mb_strtolower(preg_replace( '/[{\[\]].+?[}\[\]]/', '', str_replace(':count', '', $message), ))); foreach ($words as $word) { if (trim($word) === $lowerName) { return $unit; } } } } } } } return self::from(CarbonImmutable::singularUnit($name)); } public function singular(?string $locale = null): string { if ($locale !== null) { return trim(Translator::get($locale)->trans($this->value, [ '%count%' => 1, ':count' => 1, ]), "1 \n\r\t\v\0"); } return $this->value; } public function plural(?string $locale = null): string { if ($locale !== null) { return trim(Translator::get($locale)->trans($this->value, [ '%count%' => 9, ':count' => 9, ]), "9 \n\r\t\v\0"); } return CarbonImmutable::pluralUnit($this->value); } public function interval(int|float $value = 1): CarbonInterval { return CarbonInterval::fromString("$value $this->name"); } public function locale(string $locale): CarbonInterval { return $this->interval()->locale($locale); } public function toPeriod(...$params): CarbonPeriod { return $this->interval()->toPeriod(...$params); } public function stepBy(mixed $interval, Unit|string|null $unit = null): CarbonPeriod { return $this->interval()->stepBy($interval, $unit); } }
PHP
{ "end_line": 74, "name": "fromName", "signature": "public static function fromName(string $name, ?string $locale = null): self", "start_line": 43 }
{ "class_name": "", "class_signature": "", "namespace": "Carbon" }
singular
Carbon/src/Carbon/Unit.php
public function singular(?string $locale = null): string { if ($locale !== null) { return trim(Translator::get($locale)->trans($this->value, [ '%count%' => 1, ':count' => 1, ]), "1 \n\r\t\v\0"); } return $this->value; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; enum Unit: string { case Microsecond = 'microsecond'; case Millisecond = 'millisecond'; case Second = 'second'; case Minute = 'minute'; case Hour = 'hour'; case Day = 'day'; case Week = 'week'; case Month = 'month'; case Quarter = 'quarter'; case Year = 'year'; case Decade = 'decade'; case Century = 'century'; case Millennium = 'millennium'; public static function toName(self|string $unit): string { return $unit instanceof self ? $unit->value : $unit; } /** @internal */ public static function toNameIfUnit(mixed $unit): mixed { return $unit instanceof self ? $unit->value : $unit; } public static function fromName(string $name, ?string $locale = null): self { if ($locale !== null) { $messages = Translator::get($locale)->getMessages($locale) ?? []; if ($messages !== []) { $lowerName = mb_strtolower($name); foreach (self::cases() as $unit) { foreach (['', '_from_now', '_ago', '_after', '_before'] as $suffix) { $message = $messages[$unit->value.$suffix] ?? null; if (\is_string($message)) { $words = explode('|', mb_strtolower(preg_replace( '/[{\[\]].+?[}\[\]]/', '', str_replace(':count', '', $message), ))); foreach ($words as $word) { if (trim($word) === $lowerName) { return $unit; } } } } } } } return self::from(CarbonImmutable::singularUnit($name)); } public function singular(?string $locale = null): string { if ($locale !== null) { return trim(Translator::get($locale)->trans($this->value, [ '%count%' => 1, ':count' => 1, ]), "1 \n\r\t\v\0"); } return $this->value; } public function plural(?string $locale = null): string { if ($locale !== null) { return trim(Translator::get($locale)->trans($this->value, [ '%count%' => 9, ':count' => 9, ]), "9 \n\r\t\v\0"); } return CarbonImmutable::pluralUnit($this->value); } public function interval(int|float $value = 1): CarbonInterval { return CarbonInterval::fromString("$value $this->name"); } public function locale(string $locale): CarbonInterval { return $this->interval()->locale($locale); } public function toPeriod(...$params): CarbonPeriod { return $this->interval()->toPeriod(...$params); } public function stepBy(mixed $interval, Unit|string|null $unit = null): CarbonPeriod { return $this->interval()->stepBy($interval, $unit); } }
PHP
{ "end_line": 86, "name": "singular", "signature": "public function singular(?string $locale = null): string", "start_line": 76 }
{ "class_name": "", "class_signature": "", "namespace": "Carbon" }
plural
Carbon/src/Carbon/Unit.php
public function plural(?string $locale = null): string { if ($locale !== null) { return trim(Translator::get($locale)->trans($this->value, [ '%count%' => 9, ':count' => 9, ]), "9 \n\r\t\v\0"); } return CarbonImmutable::pluralUnit($this->value); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; enum Unit: string { case Microsecond = 'microsecond'; case Millisecond = 'millisecond'; case Second = 'second'; case Minute = 'minute'; case Hour = 'hour'; case Day = 'day'; case Week = 'week'; case Month = 'month'; case Quarter = 'quarter'; case Year = 'year'; case Decade = 'decade'; case Century = 'century'; case Millennium = 'millennium'; public static function toName(self|string $unit): string { return $unit instanceof self ? $unit->value : $unit; } /** @internal */ public static function toNameIfUnit(mixed $unit): mixed { return $unit instanceof self ? $unit->value : $unit; } public static function fromName(string $name, ?string $locale = null): self { if ($locale !== null) { $messages = Translator::get($locale)->getMessages($locale) ?? []; if ($messages !== []) { $lowerName = mb_strtolower($name); foreach (self::cases() as $unit) { foreach (['', '_from_now', '_ago', '_after', '_before'] as $suffix) { $message = $messages[$unit->value.$suffix] ?? null; if (\is_string($message)) { $words = explode('|', mb_strtolower(preg_replace( '/[{\[\]].+?[}\[\]]/', '', str_replace(':count', '', $message), ))); foreach ($words as $word) { if (trim($word) === $lowerName) { return $unit; } } } } } } } return self::from(CarbonImmutable::singularUnit($name)); } public function singular(?string $locale = null): string { if ($locale !== null) { return trim(Translator::get($locale)->trans($this->value, [ '%count%' => 1, ':count' => 1, ]), "1 \n\r\t\v\0"); } return $this->value; } public function plural(?string $locale = null): string { if ($locale !== null) { return trim(Translator::get($locale)->trans($this->value, [ '%count%' => 9, ':count' => 9, ]), "9 \n\r\t\v\0"); } return CarbonImmutable::pluralUnit($this->value); } public function interval(int|float $value = 1): CarbonInterval { return CarbonInterval::fromString("$value $this->name"); } public function locale(string $locale): CarbonInterval { return $this->interval()->locale($locale); } public function toPeriod(...$params): CarbonPeriod { return $this->interval()->toPeriod(...$params); } public function stepBy(mixed $interval, Unit|string|null $unit = null): CarbonPeriod { return $this->interval()->stepBy($interval, $unit); } }
PHP
{ "end_line": 98, "name": "plural", "signature": "public function plural(?string $locale = null): string", "start_line": 88 }
{ "class_name": "", "class_signature": "", "namespace": "Carbon" }
fromName
Carbon/src/Carbon/WeekDay.php
public static function fromName(string $name, ?string $locale = null): self { try { return self::from(CarbonImmutable::parseFromLocale($name, $locale)->dayOfWeek); } catch (InvalidFormatException $exception) { // Possibly current language expect a dot after short name, but it's missing if ($locale !== null && !mb_strlen($name) < 4 && !str_ends_with($name, '.')) { try { return self::from(CarbonImmutable::parseFromLocale($name.'.', $locale)->dayOfWeek); } catch (InvalidFormatException) { // Throw previous error } } throw $exception; } }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use Carbon\Exceptions\InvalidFormatException; enum WeekDay: int { // Using constants is only safe starting from PHP 8.2 case Sunday = 0; // CarbonInterface::SUNDAY case Monday = 1; // CarbonInterface::MONDAY case Tuesday = 2; // CarbonInterface::TUESDAY case Wednesday = 3; // CarbonInterface::WEDNESDAY case Thursday = 4; // CarbonInterface::THURSDAY case Friday = 5; // CarbonInterface::FRIDAY case Saturday = 6; // CarbonInterface::SATURDAY public static function int(self|int|null $value): ?int { return $value instanceof self ? $value->value : $value; } public static function fromNumber(int $number): self { $day = $number % CarbonInterface::DAYS_PER_WEEK; return self::from($day + ($day < 0 ? CarbonInterface::DAYS_PER_WEEK : 0)); } public static function fromName(string $name, ?string $locale = null): self { try { return self::from(CarbonImmutable::parseFromLocale($name, $locale)->dayOfWeek); } catch (InvalidFormatException $exception) { // Possibly current language expect a dot after short name, but it's missing if ($locale !== null && !mb_strlen($name) < 4 && !str_ends_with($name, '.')) { try { return self::from(CarbonImmutable::parseFromLocale($name.'.', $locale)->dayOfWeek); } catch (InvalidFormatException) { // Throw previous error } } throw $exception; } } public function next(?CarbonImmutable $now = null): CarbonImmutable { return $now?->modify($this->name) ?? new CarbonImmutable($this->name); } public function locale(string $locale, ?CarbonImmutable $now = null): CarbonImmutable { return $this->next($now)->locale($locale); } }
PHP
{ "end_line": 57, "name": "fromName", "signature": "public static function fromName(string $name, ?string $locale = null): self", "start_line": 41 }
{ "class_name": "", "class_signature": "", "namespace": "Carbon" }
sleep
Carbon/src/Carbon/WrapperClock.php
public function sleep(float|int $seconds): void { if ($seconds === 0 || $seconds === 0.0) { return; } if ($seconds < 0) { throw new RuntimeException('Expected positive number of seconds, '.$seconds.' given'); } if ($this->currentClock instanceof DateTimeInterface) { $this->currentClock = $this->addSeconds($this->currentClock, $seconds); return; } if ($this->currentClock instanceof ClockInterface) { $this->currentClock->sleep($seconds); return; } $this->currentClock = $this->addSeconds($this->currentClock->now(), $seconds); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Psr\Clock\ClockInterface as PsrClockInterface; use RuntimeException; use Symfony\Component\Clock\ClockInterface; final class WrapperClock implements ClockInterface { public function __construct( private PsrClockInterface|Factory|DateTimeInterface $currentClock, ) { } public function unwrap(): PsrClockInterface|Factory|DateTimeInterface { return $this->currentClock; } public function getFactory(): Factory { if ($this->currentClock instanceof Factory) { return $this->currentClock; } if ($this->currentClock instanceof DateTime) { $factory = new Factory(); $factory->setTestNowAndTimezone($this->currentClock); return $factory; } if ($this->currentClock instanceof DateTimeImmutable) { $factory = new FactoryImmutable(); $factory->setTestNowAndTimezone($this->currentClock); return $factory; } $factory = new FactoryImmutable(); $factory->setTestNowAndTimezone(fn () => $this->currentClock->now()); return $factory; } private function nowRaw(): DateTimeInterface { if ($this->currentClock instanceof DateTimeInterface) { return $this->currentClock; } if ($this->currentClock instanceof Factory) { return $this->currentClock->__call('now', []); } return $this->currentClock->now(); } public function now(): DateTimeImmutable { $now = $this->nowRaw(); return $now instanceof DateTimeImmutable ? $now : new CarbonImmutable($now); } /** * @template T of CarbonInterface * * @param class-string<T> $class * * @return T */ public function nowAs(string $class, DateTimeZone|string|int|null $timezone = null): CarbonInterface { $now = $this->nowRaw(); $date = $now instanceof $class ? $now : $class::instance($now); return $timezone === null ? $date : $date->setTimezone($timezone); } public function nowAsCarbon(DateTimeZone|string|int|null $timezone = null): CarbonInterface { $now = $this->nowRaw(); return $now instanceof CarbonInterface ? ($timezone === null ? $now : $now->setTimezone($timezone)) : $this->dateAsCarbon($now, $timezone); } private function dateAsCarbon(DateTimeInterface $date, DateTimeZone|string|int|null $timezone): CarbonInterface { return $date instanceof DateTimeImmutable ? new CarbonImmutable($date, $timezone) : new Carbon($date, $timezone); } public function sleep(float|int $seconds): void { if ($seconds === 0 || $seconds === 0.0) { return; } if ($seconds < 0) { throw new RuntimeException('Expected positive number of seconds, '.$seconds.' given'); } if ($this->currentClock instanceof DateTimeInterface) { $this->currentClock = $this->addSeconds($this->currentClock, $seconds); return; } if ($this->currentClock instanceof ClockInterface) { $this->currentClock->sleep($seconds); return; } $this->currentClock = $this->addSeconds($this->currentClock->now(), $seconds); } public function withTimeZone(DateTimeZone|string $timezone): static { if ($this->currentClock instanceof ClockInterface) { return new self($this->currentClock->withTimeZone($timezone)); } $now = $this->currentClock instanceof DateTimeInterface ? $this->currentClock : $this->currentClock->now(); if (!($now instanceof DateTimeImmutable)) { $now = clone $now; } if (\is_string($timezone)) { $timezone = new DateTimeZone($timezone); } return new self($now->setTimezone($timezone)); } private function addSeconds(DateTimeInterface $date, float|int $seconds): DateTimeInterface { $secondsPerHour = CarbonInterface::SECONDS_PER_MINUTE * CarbonInterface::MINUTES_PER_HOUR; $hours = number_format( floor($seconds / $secondsPerHour), thousands_separator: '', ); $microseconds = number_format( ($seconds - $hours * $secondsPerHour) * CarbonInterface::MICROSECONDS_PER_SECOND, thousands_separator: '', ); if (!($date instanceof DateTimeImmutable)) { $date = clone $date; } if ($hours !== '0') { $date = $date->modify("$hours hours"); } if ($microseconds !== '0') { $date = $date->modify("$microseconds microseconds"); } return $date; } }
PHP
{ "end_line": 138, "name": "sleep", "signature": "public function sleep(float|int $seconds): void", "start_line": 115 }
{ "class_name": "WrapperClock", "class_signature": "class WrapperClock implements ClockInterface", "namespace": "Carbon" }
withTimeZone
Carbon/src/Carbon/WrapperClock.php
public function withTimeZone(DateTimeZone|string $timezone): static { if ($this->currentClock instanceof ClockInterface) { return new self($this->currentClock->withTimeZone($timezone)); } $now = $this->currentClock instanceof DateTimeInterface ? $this->currentClock : $this->currentClock->now(); if (!($now instanceof DateTimeImmutable)) { $now = clone $now; } if (\is_string($timezone)) { $timezone = new DateTimeZone($timezone); } return new self($now->setTimezone($timezone)); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Psr\Clock\ClockInterface as PsrClockInterface; use RuntimeException; use Symfony\Component\Clock\ClockInterface; final class WrapperClock implements ClockInterface { public function __construct( private PsrClockInterface|Factory|DateTimeInterface $currentClock, ) { } public function unwrap(): PsrClockInterface|Factory|DateTimeInterface { return $this->currentClock; } public function getFactory(): Factory { if ($this->currentClock instanceof Factory) { return $this->currentClock; } if ($this->currentClock instanceof DateTime) { $factory = new Factory(); $factory->setTestNowAndTimezone($this->currentClock); return $factory; } if ($this->currentClock instanceof DateTimeImmutable) { $factory = new FactoryImmutable(); $factory->setTestNowAndTimezone($this->currentClock); return $factory; } $factory = new FactoryImmutable(); $factory->setTestNowAndTimezone(fn () => $this->currentClock->now()); return $factory; } private function nowRaw(): DateTimeInterface { if ($this->currentClock instanceof DateTimeInterface) { return $this->currentClock; } if ($this->currentClock instanceof Factory) { return $this->currentClock->__call('now', []); } return $this->currentClock->now(); } public function now(): DateTimeImmutable { $now = $this->nowRaw(); return $now instanceof DateTimeImmutable ? $now : new CarbonImmutable($now); } /** * @template T of CarbonInterface * * @param class-string<T> $class * * @return T */ public function nowAs(string $class, DateTimeZone|string|int|null $timezone = null): CarbonInterface { $now = $this->nowRaw(); $date = $now instanceof $class ? $now : $class::instance($now); return $timezone === null ? $date : $date->setTimezone($timezone); } public function nowAsCarbon(DateTimeZone|string|int|null $timezone = null): CarbonInterface { $now = $this->nowRaw(); return $now instanceof CarbonInterface ? ($timezone === null ? $now : $now->setTimezone($timezone)) : $this->dateAsCarbon($now, $timezone); } private function dateAsCarbon(DateTimeInterface $date, DateTimeZone|string|int|null $timezone): CarbonInterface { return $date instanceof DateTimeImmutable ? new CarbonImmutable($date, $timezone) : new Carbon($date, $timezone); } public function sleep(float|int $seconds): void { if ($seconds === 0 || $seconds === 0.0) { return; } if ($seconds < 0) { throw new RuntimeException('Expected positive number of seconds, '.$seconds.' given'); } if ($this->currentClock instanceof DateTimeInterface) { $this->currentClock = $this->addSeconds($this->currentClock, $seconds); return; } if ($this->currentClock instanceof ClockInterface) { $this->currentClock->sleep($seconds); return; } $this->currentClock = $this->addSeconds($this->currentClock->now(), $seconds); } public function withTimeZone(DateTimeZone|string $timezone): static { if ($this->currentClock instanceof ClockInterface) { return new self($this->currentClock->withTimeZone($timezone)); } $now = $this->currentClock instanceof DateTimeInterface ? $this->currentClock : $this->currentClock->now(); if (!($now instanceof DateTimeImmutable)) { $now = clone $now; } if (\is_string($timezone)) { $timezone = new DateTimeZone($timezone); } return new self($now->setTimezone($timezone)); } private function addSeconds(DateTimeInterface $date, float|int $seconds): DateTimeInterface { $secondsPerHour = CarbonInterface::SECONDS_PER_MINUTE * CarbonInterface::MINUTES_PER_HOUR; $hours = number_format( floor($seconds / $secondsPerHour), thousands_separator: '', ); $microseconds = number_format( ($seconds - $hours * $secondsPerHour) * CarbonInterface::MICROSECONDS_PER_SECOND, thousands_separator: '', ); if (!($date instanceof DateTimeImmutable)) { $date = clone $date; } if ($hours !== '0') { $date = $date->modify("$hours hours"); } if ($microseconds !== '0') { $date = $date->modify("$microseconds microseconds"); } return $date; } }
PHP
{ "end_line": 159, "name": "withTimeZone", "signature": "public function withTimeZone(DateTimeZone|string $timezone): static", "start_line": 140 }
{ "class_name": "WrapperClock", "class_signature": "class WrapperClock implements ClockInterface", "namespace": "Carbon" }
boot
Carbon/src/Carbon/Laravel/ServiceProvider.php
public function boot() { $this->updateLocale(); $this->updateFallbackLocale(); if (!$this->app->bound('events')) { return; } $service = $this; $events = $this->app['events']; if ($this->isEventDispatcher($events)) { $events->listen(class_exists('Illuminate\Foundation\Events\LocaleUpdated') ? 'Illuminate\Foundation\Events\LocaleUpdated' : 'locale.changed', function () use ($service) { $service->updateLocale(); }); } }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Laravel; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Illuminate\Contracts\Events\Dispatcher as DispatcherContract; use Illuminate\Events\Dispatcher; use Illuminate\Events\EventDispatcher; use Illuminate\Support\Carbon as IlluminateCarbon; use Illuminate\Support\Facades\Date; use Throwable; class ServiceProvider extends \Illuminate\Support\ServiceProvider { /** @var callable|null */ protected $appGetter = null; /** @var callable|null */ protected $localeGetter = null; /** @var callable|null */ protected $fallbackLocaleGetter = null; public function setAppGetter(?callable $appGetter): void { $this->appGetter = $appGetter; } public function setLocaleGetter(?callable $localeGetter): void { $this->localeGetter = $localeGetter; } public function setFallbackLocaleGetter(?callable $fallbackLocaleGetter): void { $this->fallbackLocaleGetter = $fallbackLocaleGetter; } public function boot() { $this->updateLocale(); $this->updateFallbackLocale(); if (!$this->app->bound('events')) { return; } $service = $this; $events = $this->app['events']; if ($this->isEventDispatcher($events)) { $events->listen(class_exists('Illuminate\Foundation\Events\LocaleUpdated') ? 'Illuminate\Foundation\Events\LocaleUpdated' : 'locale.changed', function () use ($service) { $service->updateLocale(); }); } } public function updateLocale() { $locale = $this->getLocale(); if ($locale === null) { return; } Carbon::setLocale($locale); CarbonImmutable::setLocale($locale); CarbonPeriod::setLocale($locale); CarbonInterval::setLocale($locale); if (class_exists(IlluminateCarbon::class)) { IlluminateCarbon::setLocale($locale); } if (class_exists(Date::class)) { try { $root = Date::getFacadeRoot(); $root->setLocale($locale); } catch (Throwable) { // Non Carbon class in use in Date facade } } } public function updateFallbackLocale() { $locale = $this->getFallbackLocale(); if ($locale === null) { return; } Carbon::setFallbackLocale($locale); CarbonImmutable::setFallbackLocale($locale); CarbonPeriod::setFallbackLocale($locale); CarbonInterval::setFallbackLocale($locale); if (class_exists(IlluminateCarbon::class) && method_exists(IlluminateCarbon::class, 'setFallbackLocale')) { IlluminateCarbon::setFallbackLocale($locale); } if (class_exists(Date::class)) { try { $root = Date::getFacadeRoot(); $root->setFallbackLocale($locale); } catch (Throwable) { // @codeCoverageIgnore // Non Carbon class in use in Date facade } } } public function register() { // Needed for Laravel < 5.3 compatibility } protected function getLocale() { if ($this->localeGetter) { return ($this->localeGetter)(); } $app = $this->getApp(); $app = $app && method_exists($app, 'getLocale') ? $app : $this->getGlobalApp('translator'); return $app ? $app->getLocale() : null; } protected function getFallbackLocale() { if ($this->fallbackLocaleGetter) { return ($this->fallbackLocaleGetter)(); } $app = $this->getApp(); return $app && method_exists($app, 'getFallbackLocale') ? $app->getFallbackLocale() : $this->getGlobalApp('translator')?->getFallback(); } protected function getApp() { if ($this->appGetter) { return ($this->appGetter)(); } return $this->app ?? $this->getGlobalApp(); } protected function getGlobalApp(...$args) { return \function_exists('app') ? \app(...$args) : null; } protected function isEventDispatcher($instance) { return $instance instanceof EventDispatcher || $instance instanceof Dispatcher || $instance instanceof DispatcherContract; } }
PHP
{ "end_line": 70, "name": "boot", "signature": "public function boot()", "start_line": 53 }
{ "class_name": "ServiceProvider", "class_signature": "class ServiceProvider", "namespace": "Carbon\\Laravel" }
updateLocale
Carbon/src/Carbon/Laravel/ServiceProvider.php
public function updateLocale() { $locale = $this->getLocale(); if ($locale === null) { return; } Carbon::setLocale($locale); CarbonImmutable::setLocale($locale); CarbonPeriod::setLocale($locale); CarbonInterval::setLocale($locale); if (class_exists(IlluminateCarbon::class)) { IlluminateCarbon::setLocale($locale); } if (class_exists(Date::class)) { try { $root = Date::getFacadeRoot(); $root->setLocale($locale); } catch (Throwable) { // Non Carbon class in use in Date facade } } }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Laravel; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Illuminate\Contracts\Events\Dispatcher as DispatcherContract; use Illuminate\Events\Dispatcher; use Illuminate\Events\EventDispatcher; use Illuminate\Support\Carbon as IlluminateCarbon; use Illuminate\Support\Facades\Date; use Throwable; class ServiceProvider extends \Illuminate\Support\ServiceProvider { /** @var callable|null */ protected $appGetter = null; /** @var callable|null */ protected $localeGetter = null; /** @var callable|null */ protected $fallbackLocaleGetter = null; public function setAppGetter(?callable $appGetter): void { $this->appGetter = $appGetter; } public function setLocaleGetter(?callable $localeGetter): void { $this->localeGetter = $localeGetter; } public function setFallbackLocaleGetter(?callable $fallbackLocaleGetter): void { $this->fallbackLocaleGetter = $fallbackLocaleGetter; } public function boot() { $this->updateLocale(); $this->updateFallbackLocale(); if (!$this->app->bound('events')) { return; } $service = $this; $events = $this->app['events']; if ($this->isEventDispatcher($events)) { $events->listen(class_exists('Illuminate\Foundation\Events\LocaleUpdated') ? 'Illuminate\Foundation\Events\LocaleUpdated' : 'locale.changed', function () use ($service) { $service->updateLocale(); }); } } public function updateLocale() { $locale = $this->getLocale(); if ($locale === null) { return; } Carbon::setLocale($locale); CarbonImmutable::setLocale($locale); CarbonPeriod::setLocale($locale); CarbonInterval::setLocale($locale); if (class_exists(IlluminateCarbon::class)) { IlluminateCarbon::setLocale($locale); } if (class_exists(Date::class)) { try { $root = Date::getFacadeRoot(); $root->setLocale($locale); } catch (Throwable) { // Non Carbon class in use in Date facade } } } public function updateFallbackLocale() { $locale = $this->getFallbackLocale(); if ($locale === null) { return; } Carbon::setFallbackLocale($locale); CarbonImmutable::setFallbackLocale($locale); CarbonPeriod::setFallbackLocale($locale); CarbonInterval::setFallbackLocale($locale); if (class_exists(IlluminateCarbon::class) && method_exists(IlluminateCarbon::class, 'setFallbackLocale')) { IlluminateCarbon::setFallbackLocale($locale); } if (class_exists(Date::class)) { try { $root = Date::getFacadeRoot(); $root->setFallbackLocale($locale); } catch (Throwable) { // @codeCoverageIgnore // Non Carbon class in use in Date facade } } } public function register() { // Needed for Laravel < 5.3 compatibility } protected function getLocale() { if ($this->localeGetter) { return ($this->localeGetter)(); } $app = $this->getApp(); $app = $app && method_exists($app, 'getLocale') ? $app : $this->getGlobalApp('translator'); return $app ? $app->getLocale() : null; } protected function getFallbackLocale() { if ($this->fallbackLocaleGetter) { return ($this->fallbackLocaleGetter)(); } $app = $this->getApp(); return $app && method_exists($app, 'getFallbackLocale') ? $app->getFallbackLocale() : $this->getGlobalApp('translator')?->getFallback(); } protected function getApp() { if ($this->appGetter) { return ($this->appGetter)(); } return $this->app ?? $this->getGlobalApp(); } protected function getGlobalApp(...$args) { return \function_exists('app') ? \app(...$args) : null; } protected function isEventDispatcher($instance) { return $instance instanceof EventDispatcher || $instance instanceof Dispatcher || $instance instanceof DispatcherContract; } }
PHP
{ "end_line": 97, "name": "updateLocale", "signature": "public function updateLocale()", "start_line": 72 }
{ "class_name": "ServiceProvider", "class_signature": "class ServiceProvider", "namespace": "Carbon\\Laravel" }
updateFallbackLocale
Carbon/src/Carbon/Laravel/ServiceProvider.php
public function updateFallbackLocale() { $locale = $this->getFallbackLocale(); if ($locale === null) { return; } Carbon::setFallbackLocale($locale); CarbonImmutable::setFallbackLocale($locale); CarbonPeriod::setFallbackLocale($locale); CarbonInterval::setFallbackLocale($locale); if (class_exists(IlluminateCarbon::class) && method_exists(IlluminateCarbon::class, 'setFallbackLocale')) { IlluminateCarbon::setFallbackLocale($locale); } if (class_exists(Date::class)) { try { $root = Date::getFacadeRoot(); $root->setFallbackLocale($locale); } catch (Throwable) { // @codeCoverageIgnore // Non Carbon class in use in Date facade } } }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Laravel; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Illuminate\Contracts\Events\Dispatcher as DispatcherContract; use Illuminate\Events\Dispatcher; use Illuminate\Events\EventDispatcher; use Illuminate\Support\Carbon as IlluminateCarbon; use Illuminate\Support\Facades\Date; use Throwable; class ServiceProvider extends \Illuminate\Support\ServiceProvider { /** @var callable|null */ protected $appGetter = null; /** @var callable|null */ protected $localeGetter = null; /** @var callable|null */ protected $fallbackLocaleGetter = null; public function setAppGetter(?callable $appGetter): void { $this->appGetter = $appGetter; } public function setLocaleGetter(?callable $localeGetter): void { $this->localeGetter = $localeGetter; } public function setFallbackLocaleGetter(?callable $fallbackLocaleGetter): void { $this->fallbackLocaleGetter = $fallbackLocaleGetter; } public function boot() { $this->updateLocale(); $this->updateFallbackLocale(); if (!$this->app->bound('events')) { return; } $service = $this; $events = $this->app['events']; if ($this->isEventDispatcher($events)) { $events->listen(class_exists('Illuminate\Foundation\Events\LocaleUpdated') ? 'Illuminate\Foundation\Events\LocaleUpdated' : 'locale.changed', function () use ($service) { $service->updateLocale(); }); } } public function updateLocale() { $locale = $this->getLocale(); if ($locale === null) { return; } Carbon::setLocale($locale); CarbonImmutable::setLocale($locale); CarbonPeriod::setLocale($locale); CarbonInterval::setLocale($locale); if (class_exists(IlluminateCarbon::class)) { IlluminateCarbon::setLocale($locale); } if (class_exists(Date::class)) { try { $root = Date::getFacadeRoot(); $root->setLocale($locale); } catch (Throwable) { // Non Carbon class in use in Date facade } } } public function updateFallbackLocale() { $locale = $this->getFallbackLocale(); if ($locale === null) { return; } Carbon::setFallbackLocale($locale); CarbonImmutable::setFallbackLocale($locale); CarbonPeriod::setFallbackLocale($locale); CarbonInterval::setFallbackLocale($locale); if (class_exists(IlluminateCarbon::class) && method_exists(IlluminateCarbon::class, 'setFallbackLocale')) { IlluminateCarbon::setFallbackLocale($locale); } if (class_exists(Date::class)) { try { $root = Date::getFacadeRoot(); $root->setFallbackLocale($locale); } catch (Throwable) { // @codeCoverageIgnore // Non Carbon class in use in Date facade } } } public function register() { // Needed for Laravel < 5.3 compatibility } protected function getLocale() { if ($this->localeGetter) { return ($this->localeGetter)(); } $app = $this->getApp(); $app = $app && method_exists($app, 'getLocale') ? $app : $this->getGlobalApp('translator'); return $app ? $app->getLocale() : null; } protected function getFallbackLocale() { if ($this->fallbackLocaleGetter) { return ($this->fallbackLocaleGetter)(); } $app = $this->getApp(); return $app && method_exists($app, 'getFallbackLocale') ? $app->getFallbackLocale() : $this->getGlobalApp('translator')?->getFallback(); } protected function getApp() { if ($this->appGetter) { return ($this->appGetter)(); } return $this->app ?? $this->getGlobalApp(); } protected function getGlobalApp(...$args) { return \function_exists('app') ? \app(...$args) : null; } protected function isEventDispatcher($instance) { return $instance instanceof EventDispatcher || $instance instanceof Dispatcher || $instance instanceof DispatcherContract; } }
PHP
{ "end_line": 124, "name": "updateFallbackLocale", "signature": "public function updateFallbackLocale()", "start_line": 99 }
{ "class_name": "ServiceProvider", "class_signature": "class ServiceProvider", "namespace": "Carbon\\Laravel" }
hasMethod
Carbon/src/Carbon/PHPStan/MacroExtension.php
public function hasMethod(ClassReflection $classReflection, string $methodName): bool { if ( $classReflection->getName() !== CarbonInterface::class && !$classReflection->isSubclassOf(CarbonInterface::class) ) { return false; } $className = $classReflection->getName(); return \is_callable([$className, 'hasMacro']) && $className::hasMacro($methodName); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\PHPStan; use Carbon\CarbonInterface; use Carbon\FactoryImmutable; use Closure; use InvalidArgumentException; use PHPStan\Reflection\ClassReflection; use PHPStan\Reflection\MethodReflection; use PHPStan\Reflection\MethodsClassReflectionExtension; use PHPStan\Reflection\ReflectionProvider; use PHPStan\Type\ClosureTypeFactory; use ReflectionFunction; use ReflectionMethod; use stdClass; use Throwable; /** * Class MacroExtension. * * @codeCoverageIgnore Pure PHPStan wrapper. */ final class MacroExtension implements MethodsClassReflectionExtension { /** * @var ReflectionProvider */ protected $reflectionProvider; /** * @var ClosureTypeFactory */ protected $closureTypeFactory; /** * Extension constructor. * * @param ReflectionProvider $reflectionProvider * @param ClosureTypeFactory $closureTypeFactory */ public function __construct( ReflectionProvider $reflectionProvider, ClosureTypeFactory $closureTypeFactory ) { $this->reflectionProvider = $reflectionProvider; $this->closureTypeFactory = $closureTypeFactory; } /** * {@inheritdoc} */ public function hasMethod(ClassReflection $classReflection, string $methodName): bool { if ( $classReflection->getName() !== CarbonInterface::class && !$classReflection->isSubclassOf(CarbonInterface::class) ) { return false; } $className = $classReflection->getName(); return \is_callable([$className, 'hasMacro']) && $className::hasMacro($methodName); } /** * {@inheritdoc} */ public function getMethod(ClassReflection $classReflection, string $methodName): MethodReflection { $macros = FactoryImmutable::getDefaultInstance()->getSettings()['macros'] ?? []; $macro = $macros[$methodName] ?? throw new InvalidArgumentException("Macro '$methodName' not found"); $static = false; $final = false; $deprecated = false; $docComment = null; if (\is_array($macro) && \count($macro) === 2 && \is_string($macro[1])) { \assert($macro[1] !== ''); $reflection = new ReflectionMethod($macro[0], $macro[1]); $closure = \is_object($macro[0]) ? $reflection->getClosure($macro[0]) : $reflection->getClosure(); $static = $reflection->isStatic(); $final = $reflection->isFinal(); $deprecated = $reflection->isDeprecated(); $docComment = $reflection->getDocComment() ?: null; } elseif (\is_string($macro)) { $reflection = new ReflectionFunction($macro); $closure = $reflection->getClosure(); $deprecated = $reflection->isDeprecated(); $docComment = $reflection->getDocComment() ?: null; } elseif ($macro instanceof Closure) { $closure = $macro; try { $boundClosure = Closure::bind($closure, new stdClass()); $static = (!$boundClosure || (new ReflectionFunction($boundClosure))->getClosureThis() === null); } catch (Throwable) { $static = true; } $reflection = new ReflectionFunction($macro); $deprecated = $reflection->isDeprecated(); $docComment = $reflection->getDocComment() ?: null; } if (!isset($closure)) { throw new InvalidArgumentException('Could not create reflection from the spec given'); // @codeCoverageIgnore } $closureType = $this->closureTypeFactory->fromClosureObject($closure); return new MacroMethodReflection( $classReflection, $methodName, $closureType, $static, $final, $deprecated, $docComment, ); } }
PHP
{ "end_line": 77, "name": "hasMethod", "signature": "public function hasMethod(ClassReflection $classReflection, string $methodName): bool", "start_line": 64 }
{ "class_name": "MacroExtension", "class_signature": "class MacroExtension implements MethodsClassReflectionExtension", "namespace": "Carbon\\PHPStan" }
cast
Carbon/src/Carbon/Traits/Cast.php
public function cast(string $className): mixed { if (!method_exists($className, 'instance')) { if (is_a($className, DateTimeInterface::class, true)) { return $className::createFromFormat('U.u', $this->rawFormat('U.u')) ->setTimezone($this->getTimezone()); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Exceptions\InvalidCastException; use DateTimeInterface; /** * Trait Cast. * * Utils to cast into an other class. */ trait Cast { /** * Cast the current instance into the given class. * * @template T * * @param class-string<T> $className The $className::instance() method will be called to cast the current object. * * @return T */ public function cast(string $className): mixed { if (!method_exists($className, 'instance')) { if (is_a($className, DateTimeInterface::class, true)) { return $className::createFromFormat('U.u', $this->rawFormat('U.u')) ->setTimezone($this->getTimezone()); } throw new InvalidCastException("$className has not the instance() method needed to cast the date."); } return $className::instance($this); } }
PHP
{ "end_line": 47, "name": "cast", "signature": "public function cast(string $className): mixed", "start_line": 35 }
{ "class_name": "Cast", "class_signature": "trait Cast", "namespace": "Carbon\\Traits" }
between
Carbon/src/Carbon/Traits/Comparison.php
public function between(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool { $date1 = $this->resolveCarbon($date1); $date2 = $this->resolveCarbon($date2); if ($date1->greaterThan($date2)) { [$date1, $date2] = [$date2, $date1]; } if ($equal) { return $this >= $date1 && $this <= $date2; } return $this > $date1 && $this < $date2; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use BackedEnum; use BadMethodCallException; use Carbon\CarbonConverterInterface; use Carbon\CarbonInterface; use Carbon\Exceptions\BadComparisonUnitException; use Carbon\FactoryImmutable; use Carbon\Month; use Carbon\Unit; use Carbon\WeekDay; use Closure; use DateInterval; use DateTimeInterface; use InvalidArgumentException; /** * Trait Comparison. * * Comparison utils and testers. All the following methods return booleans. * nowWithSameTz * * Depends on the following methods: * * @method static resolveCarbon($date) * @method static copy() * @method static nowWithSameTz() * @method static static yesterday($timezone = null) * @method static static tomorrow($timezone = null) */ trait Comparison { protected bool $endOfTime = false; protected bool $startOfTime = false; /** * Determines if the instance is equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->eq(Carbon::parse('2018-07-25 12:45:16')); // true * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:17'); // false * ``` * * @see equalTo() */ public function eq(DateTimeInterface|string $date): bool { return $this->equalTo($date); } /** * Determines if the instance is equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->equalTo(Carbon::parse('2018-07-25 12:45:16')); // true * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:17'); // false * ``` */ public function equalTo(DateTimeInterface|string $date): bool { return $this == $this->resolveCarbon($date); } /** * Determines if the instance is not equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->ne(Carbon::parse('2018-07-25 12:45:16')); // false * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:17'); // true * ``` * * @see notEqualTo() */ public function ne(DateTimeInterface|string $date): bool { return $this->notEqualTo($date); } /** * Determines if the instance is not equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->notEqualTo(Carbon::parse('2018-07-25 12:45:16')); // false * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:17'); // true * ``` */ public function notEqualTo(DateTimeInterface|string $date): bool { return !$this->equalTo($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:17'); // false * ``` * * @see greaterThan() */ public function gt(DateTimeInterface|string $date): bool { return $this->greaterThan($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:17'); // false * ``` */ public function greaterThan(DateTimeInterface|string $date): bool { return $this > $this->resolveCarbon($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:17'); // false * ``` * * @see greaterThan() */ public function isAfter(DateTimeInterface|string $date): bool { return $this->greaterThan($date); } /** * Determines if the instance is greater (after) than or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:17'); // false * ``` * * @see greaterThanOrEqualTo() */ public function gte(DateTimeInterface|string $date): bool { return $this->greaterThanOrEqualTo($date); } /** * Determines if the instance is greater (after) than or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:17'); // false * ``` */ public function greaterThanOrEqualTo(DateTimeInterface|string $date): bool { return $this >= $this->resolveCarbon($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:17'); // true * ``` * * @see lessThan() */ public function lt(DateTimeInterface|string $date): bool { return $this->lessThan($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:17'); // true * ``` */ public function lessThan(DateTimeInterface|string $date): bool { return $this < $this->resolveCarbon($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:17'); // true * ``` * * @see lessThan() */ public function isBefore(DateTimeInterface|string $date): bool { return $this->lessThan($date); } /** * Determines if the instance is less (before) or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:17'); // true * ``` * * @see lessThanOrEqualTo() */ public function lte(DateTimeInterface|string $date): bool { return $this->lessThanOrEqualTo($date); } /** * Determines if the instance is less (before) or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:17'); // true * ``` */ public function lessThanOrEqualTo(DateTimeInterface|string $date): bool { return $this <= $this->resolveCarbon($date); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * Carbon::parse('2018-07-25')->between('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->between('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01'); // true * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01', false); // false * ``` * * @param bool $equal Indicates if an equal to comparison should be done */ public function between(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool { $date1 = $this->resolveCarbon($date1); $date2 = $this->resolveCarbon($date2); if ($date1->greaterThan($date2)) { [$date1, $date2] = [$date2, $date1]; } if ($equal) { return $this >= $date1 && $this <= $date2; } return $this > $date1 && $this < $date2; } /** * Determines if the instance is between two others, bounds included. * * @example * ``` * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->betweenIncluded('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-25', '2018-08-01'); // true * ``` */ public function betweenIncluded(DateTimeInterface|string $date1, DateTimeInterface|string $date2): bool { return $this->between($date1, $date2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->betweenExcluded('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-25', '2018-08-01'); // false * ``` */ public function betweenExcluded(DateTimeInterface|string $date1, DateTimeInterface|string $date2): bool { return $this->between($date1, $date2, false); } /** * Determines if the instance is between two others * * @example * ``` * Carbon::parse('2018-07-25')->isBetween('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->isBetween('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01'); // true * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01', false); // false * ``` * * @param bool $equal Indicates if an equal to comparison should be done */ public function isBetween(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool { return $this->between($date1, $date2, $equal); } /** * Determines if the instance is a weekday. * * @example * ``` * Carbon::parse('2019-07-14')->isWeekday(); // false * Carbon::parse('2019-07-15')->isWeekday(); // true * ``` */ public function isWeekday(): bool { return !$this->isWeekend(); } /** * Determines if the instance is a weekend day. * * @example * ``` * Carbon::parse('2019-07-14')->isWeekend(); // true * Carbon::parse('2019-07-15')->isWeekend(); // false * ``` */ public function isWeekend(): bool { return \in_array( $this->dayOfWeek, $this->transmitFactory(static fn () => static::getWeekendDays()), true, ); } /** * Determines if the instance is yesterday. * * @example * ``` * Carbon::yesterday()->isYesterday(); // true * Carbon::tomorrow()->isYesterday(); // false * ``` */ public function isYesterday(): bool { return $this->toDateString() === $this->transmitFactory( fn () => static::yesterday($this->getTimezone())->toDateString(), ); } /** * Determines if the instance is today. * * @example * ``` * Carbon::today()->isToday(); // true * Carbon::tomorrow()->isToday(); // false * ``` */ public function isToday(): bool { return $this->toDateString() === $this->nowWithSameTz()->toDateString(); } /** * Determines if the instance is tomorrow. * * @example * ``` * Carbon::tomorrow()->isTomorrow(); // true * Carbon::yesterday()->isTomorrow(); // false * ``` */ public function isTomorrow(): bool { return $this->toDateString() === $this->transmitFactory( fn () => static::tomorrow($this->getTimezone())->toDateString(), ); } /** * Determines if the instance is in the future, ie. greater (after) than now. * * @example * ``` * Carbon::now()->addHours(5)->isFuture(); // true * Carbon::now()->subHours(5)->isFuture(); // false * ``` */ public function isFuture(): bool { return $this->greaterThan($this->nowWithSameTz()); } /** * Determines if the instance is in the past, ie. less (before) than now. * * @example * ``` * Carbon::now()->subHours(5)->isPast(); // true * Carbon::now()->addHours(5)->isPast(); // false * ``` */ public function isPast(): bool { return $this->lessThan($this->nowWithSameTz()); } /** * Determines if the instance is now or in the future, ie. greater (after) than or equal to now. * * @example * ``` * Carbon::now()->isNowOrFuture(); // true * Carbon::now()->addHours(5)->isNowOrFuture(); // true * Carbon::now()->subHours(5)->isNowOrFuture(); // false * ``` */ public function isNowOrFuture(): bool { return $this->greaterThanOrEqualTo($this->nowWithSameTz()); } /** * Determines if the instance is now or in the past, ie. less (before) than or equal to now. * * @example * ``` * Carbon::now()->isNowOrPast(); // true * Carbon::now()->subHours(5)->isNowOrPast(); // true * Carbon::now()->addHours(5)->isNowOrPast(); // false * ``` */ public function isNowOrPast(): bool { return $this->lessThanOrEqualTo($this->nowWithSameTz()); } /** * Determines if the instance is a leap year. * * @example * ``` * Carbon::parse('2020-01-01')->isLeapYear(); // true * Carbon::parse('2019-01-01')->isLeapYear(); // false * ``` */ public function isLeapYear(): bool { return $this->rawFormat('L') === '1'; } /** * Determines if the instance is a long year (using calendar year). * * ⚠️ This method completely ignores month and day to use the numeric year number, * it's not correct if the exact date matters. For instance as `2019-12-30` is already * in the first week of the 2020 year, if you want to know from this date if ISO week * year 2020 is a long year, use `isLongIsoYear` instead. * * @example * ``` * Carbon::create(2015)->isLongYear(); // true * Carbon::create(2016)->isLongYear(); // false * ``` * * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates */ public function isLongYear(): bool { return static::create($this->year, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === static::WEEKS_PER_YEAR + 1; } /** * Determines if the instance is a long year (using ISO 8601 year). * * @example * ``` * Carbon::parse('2015-01-01')->isLongIsoYear(); // true * Carbon::parse('2016-01-01')->isLongIsoYear(); // true * Carbon::parse('2016-01-03')->isLongIsoYear(); // false * Carbon::parse('2019-12-29')->isLongIsoYear(); // false * Carbon::parse('2019-12-30')->isLongIsoYear(); // true * ``` * * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates */ public function isLongIsoYear(): bool { return static::create($this->isoWeekYear, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === 53; } /** * Compares the formatted values of the two dates. * * @example * ``` * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-12-13')); // true * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-06-14')); // false * ``` * * @param string $format date formats to compare. * @param DateTimeInterface|string $date instance to compare with or null to use current day. */ public function isSameAs(string $format, DateTimeInterface|string $date): bool { return $this->rawFormat($format) === $this->resolveCarbon($date)->rawFormat($format); } /** * Determines if the instance is in the current unit given. * * @example * ``` * Carbon::parse('2019-01-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // true * Carbon::parse('2018-12-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // false * ``` * * @param string $unit singular unit string * @param DateTimeInterface|string $date instance to compare with or null to use current day. * * @throws BadComparisonUnitException * * @return bool */ public function isSameUnit(string $unit, DateTimeInterface|string $date): bool { if ($unit === /* @call isSameUnit */ 'quarter') { $other = $this->resolveCarbon($date); return $other->year === $this->year && $other->quarter === $this->quarter; } $units = [ // @call isSameUnit 'year' => 'Y', // @call isSameUnit 'month' => 'Y-n', // @call isSameUnit 'week' => 'o-W', // @call isSameUnit 'day' => 'Y-m-d', // @call isSameUnit 'hour' => 'Y-m-d H', // @call isSameUnit 'minute' => 'Y-m-d H:i', // @call isSameUnit 'second' => 'Y-m-d H:i:s', // @call isSameUnit 'milli' => 'Y-m-d H:i:s.v', // @call isSameUnit 'millisecond' => 'Y-m-d H:i:s.v', // @call isSameUnit 'micro' => 'Y-m-d H:i:s.u', // @call isSameUnit 'microsecond' => 'Y-m-d H:i:s.u', ]; if (isset($units[$unit])) { return $this->isSameAs($units[$unit], $date); } if (isset($this->$unit)) { return $this->resolveCarbon($date)->$unit === $this->$unit; } if ($this->isLocalStrictModeEnabled()) { throw new BadComparisonUnitException($unit); } return false; } /** * Determines if the instance is in the current unit given. * * @example * ``` * Carbon::now()->isCurrentUnit('hour'); // true * Carbon::now()->subHours(2)->isCurrentUnit('hour'); // false * ``` * * @param string $unit The unit to test. * * @throws BadMethodCallException */ public function isCurrentUnit(string $unit): bool { return $this->{'isSame'.ucfirst($unit)}('now'); } /** * Checks if the passed in date is in the same quarter as the instance quarter (and year if needed). * * @example * ``` * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-03-01')); // true * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-04-01')); // false * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01')); // false * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01'), false); // true * ``` * * @param DateTimeInterface|string $date The instance to compare with or null to use current day. * @param bool $ofSameYear Check if it is the same month in the same year. * * @return bool */ public function isSameQuarter(DateTimeInterface|string $date, bool $ofSameYear = true): bool { $date = $this->resolveCarbon($date); return $this->quarter === $date->quarter && (!$ofSameYear || $this->isSameYear($date)); } /** * Checks if the passed in date is in the same month as the instance´s month. * * @example * ``` * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-01-01')); // true * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-02-01')); // false * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01')); // false * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01'), false); // true * ``` * * @param DateTimeInterface|string $date The instance to compare with or null to use the current date. * @param bool $ofSameYear Check if it is the same month in the same year. * * @return bool */ public function isSameMonth(DateTimeInterface|string $date, bool $ofSameYear = true): bool { return $this->isSameAs($ofSameYear ? 'Y-m' : 'm', $date); } /** * Checks if this day is a specific day of the week. * * @example * ``` * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::WEDNESDAY); // true * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::FRIDAY); // false * Carbon::parse('2019-07-17')->isDayOfWeek('Wednesday'); // true * Carbon::parse('2019-07-17')->isDayOfWeek('Friday'); // false * ``` * * @param int|string $dayOfWeek * * @return bool */ public function isDayOfWeek($dayOfWeek): bool { if (\is_string($dayOfWeek) && \defined($constant = static::class.'::'.strtoupper($dayOfWeek))) { $dayOfWeek = \constant($constant); } return $this->dayOfWeek === $dayOfWeek; } /** * Check if its the birthday. Compares the date/month values of the two dates. * * @example * ``` * Carbon::now()->subYears(5)->isBirthday(); // true * Carbon::now()->subYears(5)->subDay()->isBirthday(); // false * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-05')); // true * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-06')); // false * ``` * * @param DateTimeInterface|string|null $date The instance to compare with or null to use current day. * * @return bool */ public function isBirthday(DateTimeInterface|string|null $date = null): bool { return $this->isSameAs('md', $date ?? 'now'); } /** * Check if today is the last day of the Month * * @example * ``` * Carbon::parse('2019-02-28')->isLastOfMonth(); // true * Carbon::parse('2019-03-28')->isLastOfMonth(); // false * Carbon::parse('2019-03-30')->isLastOfMonth(); // false * Carbon::parse('2019-03-31')->isLastOfMonth(); // true * Carbon::parse('2019-04-30')->isLastOfMonth(); // true * ``` */ public function isLastOfMonth(): bool { return $this->day === $this->daysInMonth; } /** * Check if the instance is start of a given unit (tolerating a given interval). * * @example * ``` * // Check if a date-time is the first 15 minutes of the hour it's in * Carbon::parse('2019-02-28 20:13:00')->isStartOfUnit(Unit::Hour, '15 minutes'); // true * ``` */ public function isStartOfUnit( Unit $unit, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, mixed ...$params, ): bool { $interval ??= match ($unit) { Unit::Day, Unit::Hour, Unit::Minute, Unit::Second, Unit::Millisecond, Unit::Microsecond => Unit::Microsecond, default => Unit::Day, }; $startOfUnit = $this->avoidMutation()->startOf($unit, ...$params); $startOfUnitDateTime = $startOfUnit->rawFormat('Y-m-d H:i:s.u'); $maximumDateTime = $startOfUnit ->add($interval instanceof Unit ? '1 '.$interval->value : $interval) ->rawFormat('Y-m-d H:i:s.u'); if ($maximumDateTime < $startOfUnitDateTime) { return false; } return $this->rawFormat('Y-m-d H:i:s.u') < $maximumDateTime; } /** * Check if the instance is end of a given unit (tolerating a given interval). * * @example * ``` * // Check if a date-time is the last 15 minutes of the hour it's in * Carbon::parse('2019-02-28 20:13:00')->isEndOfUnit(Unit::Hour, '15 minutes'); // false * ``` */ public function isEndOfUnit( Unit $unit, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, mixed ...$params, ): bool { $interval ??= match ($unit) { Unit::Day, Unit::Hour, Unit::Minute, Unit::Second, Unit::Millisecond, Unit::Microsecond => Unit::Microsecond, default => Unit::Day, }; $endOfUnit = $this->avoidMutation()->endOf($unit, ...$params); $endOfUnitDateTime = $endOfUnit->rawFormat('Y-m-d H:i:s.u'); $minimumDateTime = $endOfUnit ->sub($interval instanceof Unit ? '1 '.$interval->value : $interval) ->rawFormat('Y-m-d H:i:s.u'); if ($minimumDateTime > $endOfUnitDateTime) { return false; } return $this->rawFormat('Y-m-d H:i:s.u') > $minimumDateTime; } /** * Determines if the instance is start of millisecond (first microsecond by default but interval can be customized). */ public function isStartOfMillisecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Millisecond, $interval); } /** * Determines if the instance is end of millisecond (last microsecond by default but interval can be customized). */ public function isEndOfMillisecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Millisecond, $interval); } /** * Determines if the instance is start of second (first microsecond by default but interval can be customized). */ public function isStartOfSecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Second, $interval); } /** * Determines if the instance is end of second (last microsecond by default but interval can be customized). */ public function isEndOfSecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Second, $interval); } /** * Determines if the instance is start of minute (first microsecond by default but interval can be customized). */ public function isStartOfMinute( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Minute, $interval); } /** * Determines if the instance is end of minute (last microsecond by default but interval can be customized). */ public function isEndOfMinute( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Minute, $interval); } /** * Determines if the instance is start of hour (first microsecond by default but interval can be customized). */ public function isStartOfHour( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Hour, $interval); } /** * Determines if the instance is end of hour (last microsecond by default but interval can be customized). */ public function isEndOfHour( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Hour, $interval); } /** * Check if the instance is start of day / midnight. * * @example * ``` * Carbon::parse('2019-02-28 00:00:00')->isStartOfDay(); // true * Carbon::parse('2019-02-28 00:00:00.999999')->isStartOfDay(); // true * Carbon::parse('2019-02-28 00:00:01')->isStartOfDay(); // false * Carbon::parse('2019-02-28 00:00:00.000000')->isStartOfDay(true); // true * Carbon::parse('2019-02-28 00:00:00.000012')->isStartOfDay(true); // false * ``` * * @param bool $checkMicroseconds check time at microseconds precision * @param Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval if an interval is specified it will be used as precision * for instance with "15 minutes", it checks if current date-time * is in the last 15 minutes of the day, with Unit::Hour, it * checks if it's in the last hour of the day. */ public function isStartOfDay( Unit|DateInterval|Closure|CarbonConverterInterface|string|bool $checkMicroseconds = false, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { if ($checkMicroseconds === true) { @trigger_error( "Since 3.8.0, it's deprecated to use \$checkMicroseconds.\n". "It will be removed in 4.0.0.\n". "Instead, you should use either isStartOfDay(interval: Unit::Microsecond) or isStartOfDay(interval: Unit::Second)\n". 'And you can now use any custom interval as precision, such as isStartOfDay(interval: "15 minutes")', \E_USER_DEPRECATED, ); } if ($interval === null && !\is_bool($checkMicroseconds)) { $interval = $checkMicroseconds; } if ($interval !== null) { if ($interval instanceof Unit) { $interval = '1 '.$interval->value; } $date = $this->rawFormat('Y-m-d'); $time = $this->rawFormat('H:i:s.u'); $maximum = $this->avoidMutation()->startOfDay()->add($interval); $maximumDate = $maximum->rawFormat('Y-m-d'); if ($date === $maximumDate) { return $time < $maximum->rawFormat('H:i:s.u'); } return $maximumDate > $date; } /* @var CarbonInterface $this */ return $checkMicroseconds ? $this->rawFormat('H:i:s.u') === '00:00:00.000000' : $this->rawFormat('H:i:s') === '00:00:00'; } /** * Check if the instance is end of day. * * @example * ``` * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:58.999999')->isEndOfDay(); // false * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(true); // true * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(true); // false * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(true); // false * ``` * * @param bool $checkMicroseconds check time at microseconds precision * @param Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval if an interval is specified it will be used as precision * for instance with "15 minutes", it checks if current date-time * is in the last 15 minutes of the day, with Unit::Hour, it * checks if it's in the last hour of the day. */ public function isEndOfDay( Unit|DateInterval|Closure|CarbonConverterInterface|string|bool $checkMicroseconds = false, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { if ($checkMicroseconds === true) { @trigger_error( "Since 3.8.0, it's deprecated to use \$checkMicroseconds.\n". "It will be removed in 4.0.0.\n". "Instead, you should use either isEndOfDay(interval: Unit::Microsecond) or isEndOfDay(interval: Unit::Second)\n". 'And you can now use any custom interval as precision, such as isEndOfDay(interval: "15 minutes")', \E_USER_DEPRECATED, ); } if ($interval === null && !\is_bool($checkMicroseconds)) { $interval = $checkMicroseconds; } if ($interval !== null) { $date = $this->rawFormat('Y-m-d'); $time = $this->rawFormat('H:i:s.u'); $minimum = $this->avoidMutation() ->endOfDay() ->sub($interval instanceof Unit ? '1 '.$interval->value : $interval); $minimumDate = $minimum->rawFormat('Y-m-d'); if ($date === $minimumDate) { return $time > $minimum->rawFormat('H:i:s.u'); } return $minimumDate < $date; } /* @var CarbonInterface $this */ return $checkMicroseconds ? $this->rawFormat('H:i:s.u') === '23:59:59.999999' : $this->rawFormat('H:i:s') === '23:59:59'; } /** * Determines if the instance is start of week (first day by default but interval can be customized). * * @example * ``` * Carbon::parse('2024-08-31')->startOfWeek()->isStartOfWeek(); // true * Carbon::parse('2024-08-31')->isStartOfWeek(); // false * ``` */ public function isStartOfWeek( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, WeekDay|int|null $weekStartsAt = null, ): bool { return $this->isStartOfUnit(Unit::Week, $interval, $weekStartsAt); } /** * Determines if the instance is end of week (last day by default but interval can be customized). * * @example * ``` * Carbon::parse('2024-08-31')->endOfWeek()->isEndOfWeek(); // true * Carbon::parse('2024-08-31')->isEndOfWeek(); // false * ``` */ public function isEndOfWeek( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, WeekDay|int|null $weekEndsAt = null, ): bool { return $this->isEndOfUnit(Unit::Week, $interval, $weekEndsAt); } /** * Determines if the instance is start of month (first day by default but interval can be customized). */ public function isStartOfMonth( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Month, $interval); } /** * Determines if the instance is end of month (last day by default but interval can be customized). */ public function isEndOfMonth( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Month, $interval); } /** * Determines if the instance is start of quarter (first day by default but interval can be customized). */ public function isStartOfQuarter( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Quarter, $interval); } /** * Determines if the instance is end of quarter (last day by default but interval can be customized). */ public function isEndOfQuarter( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Quarter, $interval); } /** * Determines if the instance is start of year (first day by default but interval can be customized). */ public function isStartOfYear( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Year, $interval); } /** * Determines if the instance is end of year (last day by default but interval can be customized). */ public function isEndOfYear( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Year, $interval); } /** * Determines if the instance is start of decade (first day by default but interval can be customized). */ public function isStartOfDecade( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Decade, $interval); } /** * Determines if the instance is end of decade (last day by default but interval can be customized). */ public function isEndOfDecade( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Decade, $interval); } /** * Determines if the instance is start of century (first day by default but interval can be customized). */ public function isStartOfCentury( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Century, $interval); } /** * Determines if the instance is end of century (last day by default but interval can be customized). */ public function isEndOfCentury( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Century, $interval); } /** * Determines if the instance is start of millennium (first day by default but interval can be customized). */ public function isStartOfMillennium( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Millennium, $interval); } /** * Determines if the instance is end of millennium (last day by default but interval can be customized). */ public function isEndOfMillennium( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Millennium, $interval); } /** * Check if the instance is start of day / midnight. * * @example * ``` * Carbon::parse('2019-02-28 00:00:00')->isMidnight(); // true * Carbon::parse('2019-02-28 00:00:00.999999')->isMidnight(); // true * Carbon::parse('2019-02-28 00:00:01')->isMidnight(); // false * ``` */ public function isMidnight(): bool { return $this->isStartOfDay(); } /** * Check if the instance is midday. * * @example * ``` * Carbon::parse('2019-02-28 11:59:59.999999')->isMidday(); // false * Carbon::parse('2019-02-28 12:00:00')->isMidday(); // true * Carbon::parse('2019-02-28 12:00:00.999999')->isMidday(); // true * Carbon::parse('2019-02-28 12:00:01')->isMidday(); // false * ``` */ public function isMidday(): bool { /* @var CarbonInterface $this */ return $this->rawFormat('G:i:s') === static::$midDayAt.':00:00'; } /** * Checks if the (date)time string is in a given format. * * @example * ``` * Carbon::hasFormat('11:12:45', 'h:i:s'); // true * Carbon::hasFormat('13:12:45', 'h:i:s'); // false * ``` */ public static function hasFormat(string $date, string $format): bool { return FactoryImmutable::getInstance()->hasFormat($date, $format); } /** * Checks if the (date)time string is in a given format. * * @example * ``` * Carbon::hasFormatWithModifiers('31/08/2015', 'd#m#Y'); // true * Carbon::hasFormatWithModifiers('31/08/2015', 'm#d#Y'); // false * ``` * * @param string $date * @param string $format * * @return bool */ public static function hasFormatWithModifiers(?string $date, string $format): bool { return FactoryImmutable::getInstance()->hasFormatWithModifiers($date, $format); } /** * Checks if the (date)time string is in a given format and valid to create a * new instance. * * @example * ``` * Carbon::canBeCreatedFromFormat('11:12:45', 'h:i:s'); // true * Carbon::canBeCreatedFromFormat('13:12:45', 'h:i:s'); // false * ``` */ public static function canBeCreatedFromFormat(?string $date, string $format): bool { if ($date === null) { return false; } try { // Try to create a DateTime object. Throws an InvalidArgumentException if the provided time string // doesn't match the format in any way. if (!static::rawCreateFromFormat($format, $date)) { return false; } } catch (InvalidArgumentException) { return false; } return static::hasFormatWithModifiers($date, $format); } /** * Returns true if the current date matches the given string. * * @example * ``` * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2018')); // false * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('06-02')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06-02')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('Sunday')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('June')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:45')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:00')); // false * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12h')); // true * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3pm')); // true * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3am')); // false * ``` * * @param string $tester day name, month name, hour, date, etc. as string */ public function is(WeekDay|Month|string $tester): bool { if ($tester instanceof BackedEnum) { $tester = $tester->name; } $tester = trim($tester); if (preg_match('/^\d+$/', $tester)) { return $this->year === (int) $tester; } if (preg_match('/^(?:Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|September|Oct|October|Nov|November|Dec|December)$/i', $tester)) { return $this->isSameMonth( $this->transmitFactory(static fn () => static::parse("$tester 1st")), false, ); } if (preg_match('/^\d{3,}-\d{1,2}$/', $tester)) { return $this->isSameMonth( $this->transmitFactory(static fn () => static::parse($tester)), ); } if (preg_match('/^(\d{1,2})-(\d{1,2})$/', $tester, $match)) { return $this->month === (int) $match[1] && $this->day === (int) $match[2]; } $modifier = preg_replace('/(\d)h$/i', '$1:00', $tester); /* @var CarbonInterface $max */ $median = $this->transmitFactory(static fn () => static::parse('5555-06-15 12:30:30.555555')) ->modify($modifier); $current = $this->avoidMutation(); /* @var CarbonInterface $other */ $other = $this->avoidMutation()->modify($modifier); if ($current->eq($other)) { return true; } if (preg_match('/\d:\d{1,2}:\d{1,2}$/', $tester)) { return $current->startOfSecond()->eq($other); } if (preg_match('/\d:\d{1,2}$/', $tester)) { return $current->startOfMinute()->eq($other); } if (preg_match('/\d(?:h|am|pm)$/', $tester)) { return $current->startOfHour()->eq($other); } if (preg_match( '/^(?:january|february|march|april|may|june|july|august|september|october|november|december)(?:\s+\d+)?$/i', $tester, )) { return $current->startOfMonth()->eq($other->startOfMonth()); } $units = [ 'month' => [1, 'year'], 'day' => [1, 'month'], 'hour' => [0, 'day'], 'minute' => [0, 'hour'], 'second' => [0, 'minute'], 'microsecond' => [0, 'second'], ]; foreach ($units as $unit => [$minimum, $startUnit]) { if ($minimum === $median->$unit) { $current = $current->startOf($startUnit); break; } } return $current->eq($other); } /** * Returns true if the date was created using CarbonImmutable::startOfTime() * * @return bool */ public function isStartOfTime(): bool { return $this->startOfTime ?? false; } /** * Returns true if the date was created using CarbonImmutable::endOfTime() * * @return bool */ public function isEndOfTime(): bool { return $this->endOfTime ?? false; } }
PHP
{ "end_line": 307, "name": "between", "signature": "public function between(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool", "start_line": 293 }
{ "class_name": "Comparison", "class_signature": "trait Comparison", "namespace": "Carbon\\Traits" }
isSameUnit
Carbon/src/Carbon/Traits/Comparison.php
public function isSameUnit(string $unit, DateTimeInterface|string $date): bool { if ($unit === /* @call isSameUnit */ 'quarter') { $other = $this->resolveCarbon($date); return $other->year === $this->year && $other->quarter === $this->quarter; } $units = [ // @call isSameUnit 'year' => 'Y', // @call isSameUnit 'month' => 'Y-n', // @call isSameUnit 'week' => 'o-W', // @call isSameUnit 'day' => 'Y-m-d', // @call isSameUnit 'hour' => 'Y-m-d H', // @call isSameUnit 'minute' => 'Y-m-d H:i', // @call isSameUnit 'second' => 'Y-m-d H:i:s', // @call isSameUnit 'milli' => 'Y-m-d H:i:s.v', // @call isSameUnit 'millisecond' => 'Y-m-d H:i:s.v', // @call isSameUnit 'micro' => 'Y-m-d H:i:s.u', // @call isSameUnit 'microsecond' => 'Y-m-d H:i:s.u', ]; if (isset($units[$unit])) { return $this->isSameAs($units[$unit], $date); } if (isset($this->$unit)) { return $this->resolveCarbon($date)->$unit === $this->$unit; } if ($this->isLocalStrictModeEnabled()) { throw new BadComparisonUnitException($unit); } return false; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use BackedEnum; use BadMethodCallException; use Carbon\CarbonConverterInterface; use Carbon\CarbonInterface; use Carbon\Exceptions\BadComparisonUnitException; use Carbon\FactoryImmutable; use Carbon\Month; use Carbon\Unit; use Carbon\WeekDay; use Closure; use DateInterval; use DateTimeInterface; use InvalidArgumentException; /** * Trait Comparison. * * Comparison utils and testers. All the following methods return booleans. * nowWithSameTz * * Depends on the following methods: * * @method static resolveCarbon($date) * @method static copy() * @method static nowWithSameTz() * @method static static yesterday($timezone = null) * @method static static tomorrow($timezone = null) */ trait Comparison { protected bool $endOfTime = false; protected bool $startOfTime = false; /** * Determines if the instance is equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->eq(Carbon::parse('2018-07-25 12:45:16')); // true * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:17'); // false * ``` * * @see equalTo() */ public function eq(DateTimeInterface|string $date): bool { return $this->equalTo($date); } /** * Determines if the instance is equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->equalTo(Carbon::parse('2018-07-25 12:45:16')); // true * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:17'); // false * ``` */ public function equalTo(DateTimeInterface|string $date): bool { return $this == $this->resolveCarbon($date); } /** * Determines if the instance is not equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->ne(Carbon::parse('2018-07-25 12:45:16')); // false * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:17'); // true * ``` * * @see notEqualTo() */ public function ne(DateTimeInterface|string $date): bool { return $this->notEqualTo($date); } /** * Determines if the instance is not equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->notEqualTo(Carbon::parse('2018-07-25 12:45:16')); // false * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:17'); // true * ``` */ public function notEqualTo(DateTimeInterface|string $date): bool { return !$this->equalTo($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:17'); // false * ``` * * @see greaterThan() */ public function gt(DateTimeInterface|string $date): bool { return $this->greaterThan($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:17'); // false * ``` */ public function greaterThan(DateTimeInterface|string $date): bool { return $this > $this->resolveCarbon($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:17'); // false * ``` * * @see greaterThan() */ public function isAfter(DateTimeInterface|string $date): bool { return $this->greaterThan($date); } /** * Determines if the instance is greater (after) than or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:17'); // false * ``` * * @see greaterThanOrEqualTo() */ public function gte(DateTimeInterface|string $date): bool { return $this->greaterThanOrEqualTo($date); } /** * Determines if the instance is greater (after) than or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:17'); // false * ``` */ public function greaterThanOrEqualTo(DateTimeInterface|string $date): bool { return $this >= $this->resolveCarbon($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:17'); // true * ``` * * @see lessThan() */ public function lt(DateTimeInterface|string $date): bool { return $this->lessThan($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:17'); // true * ``` */ public function lessThan(DateTimeInterface|string $date): bool { return $this < $this->resolveCarbon($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:17'); // true * ``` * * @see lessThan() */ public function isBefore(DateTimeInterface|string $date): bool { return $this->lessThan($date); } /** * Determines if the instance is less (before) or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:17'); // true * ``` * * @see lessThanOrEqualTo() */ public function lte(DateTimeInterface|string $date): bool { return $this->lessThanOrEqualTo($date); } /** * Determines if the instance is less (before) or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:17'); // true * ``` */ public function lessThanOrEqualTo(DateTimeInterface|string $date): bool { return $this <= $this->resolveCarbon($date); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * Carbon::parse('2018-07-25')->between('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->between('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01'); // true * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01', false); // false * ``` * * @param bool $equal Indicates if an equal to comparison should be done */ public function between(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool { $date1 = $this->resolveCarbon($date1); $date2 = $this->resolveCarbon($date2); if ($date1->greaterThan($date2)) { [$date1, $date2] = [$date2, $date1]; } if ($equal) { return $this >= $date1 && $this <= $date2; } return $this > $date1 && $this < $date2; } /** * Determines if the instance is between two others, bounds included. * * @example * ``` * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->betweenIncluded('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-25', '2018-08-01'); // true * ``` */ public function betweenIncluded(DateTimeInterface|string $date1, DateTimeInterface|string $date2): bool { return $this->between($date1, $date2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->betweenExcluded('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-25', '2018-08-01'); // false * ``` */ public function betweenExcluded(DateTimeInterface|string $date1, DateTimeInterface|string $date2): bool { return $this->between($date1, $date2, false); } /** * Determines if the instance is between two others * * @example * ``` * Carbon::parse('2018-07-25')->isBetween('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->isBetween('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01'); // true * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01', false); // false * ``` * * @param bool $equal Indicates if an equal to comparison should be done */ public function isBetween(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool { return $this->between($date1, $date2, $equal); } /** * Determines if the instance is a weekday. * * @example * ``` * Carbon::parse('2019-07-14')->isWeekday(); // false * Carbon::parse('2019-07-15')->isWeekday(); // true * ``` */ public function isWeekday(): bool { return !$this->isWeekend(); } /** * Determines if the instance is a weekend day. * * @example * ``` * Carbon::parse('2019-07-14')->isWeekend(); // true * Carbon::parse('2019-07-15')->isWeekend(); // false * ``` */ public function isWeekend(): bool { return \in_array( $this->dayOfWeek, $this->transmitFactory(static fn () => static::getWeekendDays()), true, ); } /** * Determines if the instance is yesterday. * * @example * ``` * Carbon::yesterday()->isYesterday(); // true * Carbon::tomorrow()->isYesterday(); // false * ``` */ public function isYesterday(): bool { return $this->toDateString() === $this->transmitFactory( fn () => static::yesterday($this->getTimezone())->toDateString(), ); } /** * Determines if the instance is today. * * @example * ``` * Carbon::today()->isToday(); // true * Carbon::tomorrow()->isToday(); // false * ``` */ public function isToday(): bool { return $this->toDateString() === $this->nowWithSameTz()->toDateString(); } /** * Determines if the instance is tomorrow. * * @example * ``` * Carbon::tomorrow()->isTomorrow(); // true * Carbon::yesterday()->isTomorrow(); // false * ``` */ public function isTomorrow(): bool { return $this->toDateString() === $this->transmitFactory( fn () => static::tomorrow($this->getTimezone())->toDateString(), ); } /** * Determines if the instance is in the future, ie. greater (after) than now. * * @example * ``` * Carbon::now()->addHours(5)->isFuture(); // true * Carbon::now()->subHours(5)->isFuture(); // false * ``` */ public function isFuture(): bool { return $this->greaterThan($this->nowWithSameTz()); } /** * Determines if the instance is in the past, ie. less (before) than now. * * @example * ``` * Carbon::now()->subHours(5)->isPast(); // true * Carbon::now()->addHours(5)->isPast(); // false * ``` */ public function isPast(): bool { return $this->lessThan($this->nowWithSameTz()); } /** * Determines if the instance is now or in the future, ie. greater (after) than or equal to now. * * @example * ``` * Carbon::now()->isNowOrFuture(); // true * Carbon::now()->addHours(5)->isNowOrFuture(); // true * Carbon::now()->subHours(5)->isNowOrFuture(); // false * ``` */ public function isNowOrFuture(): bool { return $this->greaterThanOrEqualTo($this->nowWithSameTz()); } /** * Determines if the instance is now or in the past, ie. less (before) than or equal to now. * * @example * ``` * Carbon::now()->isNowOrPast(); // true * Carbon::now()->subHours(5)->isNowOrPast(); // true * Carbon::now()->addHours(5)->isNowOrPast(); // false * ``` */ public function isNowOrPast(): bool { return $this->lessThanOrEqualTo($this->nowWithSameTz()); } /** * Determines if the instance is a leap year. * * @example * ``` * Carbon::parse('2020-01-01')->isLeapYear(); // true * Carbon::parse('2019-01-01')->isLeapYear(); // false * ``` */ public function isLeapYear(): bool { return $this->rawFormat('L') === '1'; } /** * Determines if the instance is a long year (using calendar year). * * ⚠️ This method completely ignores month and day to use the numeric year number, * it's not correct if the exact date matters. For instance as `2019-12-30` is already * in the first week of the 2020 year, if you want to know from this date if ISO week * year 2020 is a long year, use `isLongIsoYear` instead. * * @example * ``` * Carbon::create(2015)->isLongYear(); // true * Carbon::create(2016)->isLongYear(); // false * ``` * * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates */ public function isLongYear(): bool { return static::create($this->year, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === static::WEEKS_PER_YEAR + 1; } /** * Determines if the instance is a long year (using ISO 8601 year). * * @example * ``` * Carbon::parse('2015-01-01')->isLongIsoYear(); // true * Carbon::parse('2016-01-01')->isLongIsoYear(); // true * Carbon::parse('2016-01-03')->isLongIsoYear(); // false * Carbon::parse('2019-12-29')->isLongIsoYear(); // false * Carbon::parse('2019-12-30')->isLongIsoYear(); // true * ``` * * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates */ public function isLongIsoYear(): bool { return static::create($this->isoWeekYear, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === 53; } /** * Compares the formatted values of the two dates. * * @example * ``` * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-12-13')); // true * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-06-14')); // false * ``` * * @param string $format date formats to compare. * @param DateTimeInterface|string $date instance to compare with or null to use current day. */ public function isSameAs(string $format, DateTimeInterface|string $date): bool { return $this->rawFormat($format) === $this->resolveCarbon($date)->rawFormat($format); } /** * Determines if the instance is in the current unit given. * * @example * ``` * Carbon::parse('2019-01-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // true * Carbon::parse('2018-12-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // false * ``` * * @param string $unit singular unit string * @param DateTimeInterface|string $date instance to compare with or null to use current day. * * @throws BadComparisonUnitException * * @return bool */ public function isSameUnit(string $unit, DateTimeInterface|string $date): bool { if ($unit === /* @call isSameUnit */ 'quarter') { $other = $this->resolveCarbon($date); return $other->year === $this->year && $other->quarter === $this->quarter; } $units = [ // @call isSameUnit 'year' => 'Y', // @call isSameUnit 'month' => 'Y-n', // @call isSameUnit 'week' => 'o-W', // @call isSameUnit 'day' => 'Y-m-d', // @call isSameUnit 'hour' => 'Y-m-d H', // @call isSameUnit 'minute' => 'Y-m-d H:i', // @call isSameUnit 'second' => 'Y-m-d H:i:s', // @call isSameUnit 'milli' => 'Y-m-d H:i:s.v', // @call isSameUnit 'millisecond' => 'Y-m-d H:i:s.v', // @call isSameUnit 'micro' => 'Y-m-d H:i:s.u', // @call isSameUnit 'microsecond' => 'Y-m-d H:i:s.u', ]; if (isset($units[$unit])) { return $this->isSameAs($units[$unit], $date); } if (isset($this->$unit)) { return $this->resolveCarbon($date)->$unit === $this->$unit; } if ($this->isLocalStrictModeEnabled()) { throw new BadComparisonUnitException($unit); } return false; } /** * Determines if the instance is in the current unit given. * * @example * ``` * Carbon::now()->isCurrentUnit('hour'); // true * Carbon::now()->subHours(2)->isCurrentUnit('hour'); // false * ``` * * @param string $unit The unit to test. * * @throws BadMethodCallException */ public function isCurrentUnit(string $unit): bool { return $this->{'isSame'.ucfirst($unit)}('now'); } /** * Checks if the passed in date is in the same quarter as the instance quarter (and year if needed). * * @example * ``` * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-03-01')); // true * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-04-01')); // false * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01')); // false * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01'), false); // true * ``` * * @param DateTimeInterface|string $date The instance to compare with or null to use current day. * @param bool $ofSameYear Check if it is the same month in the same year. * * @return bool */ public function isSameQuarter(DateTimeInterface|string $date, bool $ofSameYear = true): bool { $date = $this->resolveCarbon($date); return $this->quarter === $date->quarter && (!$ofSameYear || $this->isSameYear($date)); } /** * Checks if the passed in date is in the same month as the instance´s month. * * @example * ``` * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-01-01')); // true * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-02-01')); // false * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01')); // false * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01'), false); // true * ``` * * @param DateTimeInterface|string $date The instance to compare with or null to use the current date. * @param bool $ofSameYear Check if it is the same month in the same year. * * @return bool */ public function isSameMonth(DateTimeInterface|string $date, bool $ofSameYear = true): bool { return $this->isSameAs($ofSameYear ? 'Y-m' : 'm', $date); } /** * Checks if this day is a specific day of the week. * * @example * ``` * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::WEDNESDAY); // true * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::FRIDAY); // false * Carbon::parse('2019-07-17')->isDayOfWeek('Wednesday'); // true * Carbon::parse('2019-07-17')->isDayOfWeek('Friday'); // false * ``` * * @param int|string $dayOfWeek * * @return bool */ public function isDayOfWeek($dayOfWeek): bool { if (\is_string($dayOfWeek) && \defined($constant = static::class.'::'.strtoupper($dayOfWeek))) { $dayOfWeek = \constant($constant); } return $this->dayOfWeek === $dayOfWeek; } /** * Check if its the birthday. Compares the date/month values of the two dates. * * @example * ``` * Carbon::now()->subYears(5)->isBirthday(); // true * Carbon::now()->subYears(5)->subDay()->isBirthday(); // false * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-05')); // true * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-06')); // false * ``` * * @param DateTimeInterface|string|null $date The instance to compare with or null to use current day. * * @return bool */ public function isBirthday(DateTimeInterface|string|null $date = null): bool { return $this->isSameAs('md', $date ?? 'now'); } /** * Check if today is the last day of the Month * * @example * ``` * Carbon::parse('2019-02-28')->isLastOfMonth(); // true * Carbon::parse('2019-03-28')->isLastOfMonth(); // false * Carbon::parse('2019-03-30')->isLastOfMonth(); // false * Carbon::parse('2019-03-31')->isLastOfMonth(); // true * Carbon::parse('2019-04-30')->isLastOfMonth(); // true * ``` */ public function isLastOfMonth(): bool { return $this->day === $this->daysInMonth; } /** * Check if the instance is start of a given unit (tolerating a given interval). * * @example * ``` * // Check if a date-time is the first 15 minutes of the hour it's in * Carbon::parse('2019-02-28 20:13:00')->isStartOfUnit(Unit::Hour, '15 minutes'); // true * ``` */ public function isStartOfUnit( Unit $unit, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, mixed ...$params, ): bool { $interval ??= match ($unit) { Unit::Day, Unit::Hour, Unit::Minute, Unit::Second, Unit::Millisecond, Unit::Microsecond => Unit::Microsecond, default => Unit::Day, }; $startOfUnit = $this->avoidMutation()->startOf($unit, ...$params); $startOfUnitDateTime = $startOfUnit->rawFormat('Y-m-d H:i:s.u'); $maximumDateTime = $startOfUnit ->add($interval instanceof Unit ? '1 '.$interval->value : $interval) ->rawFormat('Y-m-d H:i:s.u'); if ($maximumDateTime < $startOfUnitDateTime) { return false; } return $this->rawFormat('Y-m-d H:i:s.u') < $maximumDateTime; } /** * Check if the instance is end of a given unit (tolerating a given interval). * * @example * ``` * // Check if a date-time is the last 15 minutes of the hour it's in * Carbon::parse('2019-02-28 20:13:00')->isEndOfUnit(Unit::Hour, '15 minutes'); // false * ``` */ public function isEndOfUnit( Unit $unit, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, mixed ...$params, ): bool { $interval ??= match ($unit) { Unit::Day, Unit::Hour, Unit::Minute, Unit::Second, Unit::Millisecond, Unit::Microsecond => Unit::Microsecond, default => Unit::Day, }; $endOfUnit = $this->avoidMutation()->endOf($unit, ...$params); $endOfUnitDateTime = $endOfUnit->rawFormat('Y-m-d H:i:s.u'); $minimumDateTime = $endOfUnit ->sub($interval instanceof Unit ? '1 '.$interval->value : $interval) ->rawFormat('Y-m-d H:i:s.u'); if ($minimumDateTime > $endOfUnitDateTime) { return false; } return $this->rawFormat('Y-m-d H:i:s.u') > $minimumDateTime; } /** * Determines if the instance is start of millisecond (first microsecond by default but interval can be customized). */ public function isStartOfMillisecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Millisecond, $interval); } /** * Determines if the instance is end of millisecond (last microsecond by default but interval can be customized). */ public function isEndOfMillisecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Millisecond, $interval); } /** * Determines if the instance is start of second (first microsecond by default but interval can be customized). */ public function isStartOfSecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Second, $interval); } /** * Determines if the instance is end of second (last microsecond by default but interval can be customized). */ public function isEndOfSecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Second, $interval); } /** * Determines if the instance is start of minute (first microsecond by default but interval can be customized). */ public function isStartOfMinute( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Minute, $interval); } /** * Determines if the instance is end of minute (last microsecond by default but interval can be customized). */ public function isEndOfMinute( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Minute, $interval); } /** * Determines if the instance is start of hour (first microsecond by default but interval can be customized). */ public function isStartOfHour( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Hour, $interval); } /** * Determines if the instance is end of hour (last microsecond by default but interval can be customized). */ public function isEndOfHour( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Hour, $interval); } /** * Check if the instance is start of day / midnight. * * @example * ``` * Carbon::parse('2019-02-28 00:00:00')->isStartOfDay(); // true * Carbon::parse('2019-02-28 00:00:00.999999')->isStartOfDay(); // true * Carbon::parse('2019-02-28 00:00:01')->isStartOfDay(); // false * Carbon::parse('2019-02-28 00:00:00.000000')->isStartOfDay(true); // true * Carbon::parse('2019-02-28 00:00:00.000012')->isStartOfDay(true); // false * ``` * * @param bool $checkMicroseconds check time at microseconds precision * @param Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval if an interval is specified it will be used as precision * for instance with "15 minutes", it checks if current date-time * is in the last 15 minutes of the day, with Unit::Hour, it * checks if it's in the last hour of the day. */ public function isStartOfDay( Unit|DateInterval|Closure|CarbonConverterInterface|string|bool $checkMicroseconds = false, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { if ($checkMicroseconds === true) { @trigger_error( "Since 3.8.0, it's deprecated to use \$checkMicroseconds.\n". "It will be removed in 4.0.0.\n". "Instead, you should use either isStartOfDay(interval: Unit::Microsecond) or isStartOfDay(interval: Unit::Second)\n". 'And you can now use any custom interval as precision, such as isStartOfDay(interval: "15 minutes")', \E_USER_DEPRECATED, ); } if ($interval === null && !\is_bool($checkMicroseconds)) { $interval = $checkMicroseconds; } if ($interval !== null) { if ($interval instanceof Unit) { $interval = '1 '.$interval->value; } $date = $this->rawFormat('Y-m-d'); $time = $this->rawFormat('H:i:s.u'); $maximum = $this->avoidMutation()->startOfDay()->add($interval); $maximumDate = $maximum->rawFormat('Y-m-d'); if ($date === $maximumDate) { return $time < $maximum->rawFormat('H:i:s.u'); } return $maximumDate > $date; } /* @var CarbonInterface $this */ return $checkMicroseconds ? $this->rawFormat('H:i:s.u') === '00:00:00.000000' : $this->rawFormat('H:i:s') === '00:00:00'; } /** * Check if the instance is end of day. * * @example * ``` * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:58.999999')->isEndOfDay(); // false * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(true); // true * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(true); // false * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(true); // false * ``` * * @param bool $checkMicroseconds check time at microseconds precision * @param Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval if an interval is specified it will be used as precision * for instance with "15 minutes", it checks if current date-time * is in the last 15 minutes of the day, with Unit::Hour, it * checks if it's in the last hour of the day. */ public function isEndOfDay( Unit|DateInterval|Closure|CarbonConverterInterface|string|bool $checkMicroseconds = false, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { if ($checkMicroseconds === true) { @trigger_error( "Since 3.8.0, it's deprecated to use \$checkMicroseconds.\n". "It will be removed in 4.0.0.\n". "Instead, you should use either isEndOfDay(interval: Unit::Microsecond) or isEndOfDay(interval: Unit::Second)\n". 'And you can now use any custom interval as precision, such as isEndOfDay(interval: "15 minutes")', \E_USER_DEPRECATED, ); } if ($interval === null && !\is_bool($checkMicroseconds)) { $interval = $checkMicroseconds; } if ($interval !== null) { $date = $this->rawFormat('Y-m-d'); $time = $this->rawFormat('H:i:s.u'); $minimum = $this->avoidMutation() ->endOfDay() ->sub($interval instanceof Unit ? '1 '.$interval->value : $interval); $minimumDate = $minimum->rawFormat('Y-m-d'); if ($date === $minimumDate) { return $time > $minimum->rawFormat('H:i:s.u'); } return $minimumDate < $date; } /* @var CarbonInterface $this */ return $checkMicroseconds ? $this->rawFormat('H:i:s.u') === '23:59:59.999999' : $this->rawFormat('H:i:s') === '23:59:59'; } /** * Determines if the instance is start of week (first day by default but interval can be customized). * * @example * ``` * Carbon::parse('2024-08-31')->startOfWeek()->isStartOfWeek(); // true * Carbon::parse('2024-08-31')->isStartOfWeek(); // false * ``` */ public function isStartOfWeek( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, WeekDay|int|null $weekStartsAt = null, ): bool { return $this->isStartOfUnit(Unit::Week, $interval, $weekStartsAt); } /** * Determines if the instance is end of week (last day by default but interval can be customized). * * @example * ``` * Carbon::parse('2024-08-31')->endOfWeek()->isEndOfWeek(); // true * Carbon::parse('2024-08-31')->isEndOfWeek(); // false * ``` */ public function isEndOfWeek( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, WeekDay|int|null $weekEndsAt = null, ): bool { return $this->isEndOfUnit(Unit::Week, $interval, $weekEndsAt); } /** * Determines if the instance is start of month (first day by default but interval can be customized). */ public function isStartOfMonth( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Month, $interval); } /** * Determines if the instance is end of month (last day by default but interval can be customized). */ public function isEndOfMonth( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Month, $interval); } /** * Determines if the instance is start of quarter (first day by default but interval can be customized). */ public function isStartOfQuarter( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Quarter, $interval); } /** * Determines if the instance is end of quarter (last day by default but interval can be customized). */ public function isEndOfQuarter( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Quarter, $interval); } /** * Determines if the instance is start of year (first day by default but interval can be customized). */ public function isStartOfYear( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Year, $interval); } /** * Determines if the instance is end of year (last day by default but interval can be customized). */ public function isEndOfYear( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Year, $interval); } /** * Determines if the instance is start of decade (first day by default but interval can be customized). */ public function isStartOfDecade( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Decade, $interval); } /** * Determines if the instance is end of decade (last day by default but interval can be customized). */ public function isEndOfDecade( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Decade, $interval); } /** * Determines if the instance is start of century (first day by default but interval can be customized). */ public function isStartOfCentury( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Century, $interval); } /** * Determines if the instance is end of century (last day by default but interval can be customized). */ public function isEndOfCentury( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Century, $interval); } /** * Determines if the instance is start of millennium (first day by default but interval can be customized). */ public function isStartOfMillennium( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Millennium, $interval); } /** * Determines if the instance is end of millennium (last day by default but interval can be customized). */ public function isEndOfMillennium( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Millennium, $interval); } /** * Check if the instance is start of day / midnight. * * @example * ``` * Carbon::parse('2019-02-28 00:00:00')->isMidnight(); // true * Carbon::parse('2019-02-28 00:00:00.999999')->isMidnight(); // true * Carbon::parse('2019-02-28 00:00:01')->isMidnight(); // false * ``` */ public function isMidnight(): bool { return $this->isStartOfDay(); } /** * Check if the instance is midday. * * @example * ``` * Carbon::parse('2019-02-28 11:59:59.999999')->isMidday(); // false * Carbon::parse('2019-02-28 12:00:00')->isMidday(); // true * Carbon::parse('2019-02-28 12:00:00.999999')->isMidday(); // true * Carbon::parse('2019-02-28 12:00:01')->isMidday(); // false * ``` */ public function isMidday(): bool { /* @var CarbonInterface $this */ return $this->rawFormat('G:i:s') === static::$midDayAt.':00:00'; } /** * Checks if the (date)time string is in a given format. * * @example * ``` * Carbon::hasFormat('11:12:45', 'h:i:s'); // true * Carbon::hasFormat('13:12:45', 'h:i:s'); // false * ``` */ public static function hasFormat(string $date, string $format): bool { return FactoryImmutable::getInstance()->hasFormat($date, $format); } /** * Checks if the (date)time string is in a given format. * * @example * ``` * Carbon::hasFormatWithModifiers('31/08/2015', 'd#m#Y'); // true * Carbon::hasFormatWithModifiers('31/08/2015', 'm#d#Y'); // false * ``` * * @param string $date * @param string $format * * @return bool */ public static function hasFormatWithModifiers(?string $date, string $format): bool { return FactoryImmutable::getInstance()->hasFormatWithModifiers($date, $format); } /** * Checks if the (date)time string is in a given format and valid to create a * new instance. * * @example * ``` * Carbon::canBeCreatedFromFormat('11:12:45', 'h:i:s'); // true * Carbon::canBeCreatedFromFormat('13:12:45', 'h:i:s'); // false * ``` */ public static function canBeCreatedFromFormat(?string $date, string $format): bool { if ($date === null) { return false; } try { // Try to create a DateTime object. Throws an InvalidArgumentException if the provided time string // doesn't match the format in any way. if (!static::rawCreateFromFormat($format, $date)) { return false; } } catch (InvalidArgumentException) { return false; } return static::hasFormatWithModifiers($date, $format); } /** * Returns true if the current date matches the given string. * * @example * ``` * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2018')); // false * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('06-02')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06-02')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('Sunday')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('June')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:45')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:00')); // false * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12h')); // true * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3pm')); // true * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3am')); // false * ``` * * @param string $tester day name, month name, hour, date, etc. as string */ public function is(WeekDay|Month|string $tester): bool { if ($tester instanceof BackedEnum) { $tester = $tester->name; } $tester = trim($tester); if (preg_match('/^\d+$/', $tester)) { return $this->year === (int) $tester; } if (preg_match('/^(?:Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|September|Oct|October|Nov|November|Dec|December)$/i', $tester)) { return $this->isSameMonth( $this->transmitFactory(static fn () => static::parse("$tester 1st")), false, ); } if (preg_match('/^\d{3,}-\d{1,2}$/', $tester)) { return $this->isSameMonth( $this->transmitFactory(static fn () => static::parse($tester)), ); } if (preg_match('/^(\d{1,2})-(\d{1,2})$/', $tester, $match)) { return $this->month === (int) $match[1] && $this->day === (int) $match[2]; } $modifier = preg_replace('/(\d)h$/i', '$1:00', $tester); /* @var CarbonInterface $max */ $median = $this->transmitFactory(static fn () => static::parse('5555-06-15 12:30:30.555555')) ->modify($modifier); $current = $this->avoidMutation(); /* @var CarbonInterface $other */ $other = $this->avoidMutation()->modify($modifier); if ($current->eq($other)) { return true; } if (preg_match('/\d:\d{1,2}:\d{1,2}$/', $tester)) { return $current->startOfSecond()->eq($other); } if (preg_match('/\d:\d{1,2}$/', $tester)) { return $current->startOfMinute()->eq($other); } if (preg_match('/\d(?:h|am|pm)$/', $tester)) { return $current->startOfHour()->eq($other); } if (preg_match( '/^(?:january|february|march|april|may|june|july|august|september|october|november|december)(?:\s+\d+)?$/i', $tester, )) { return $current->startOfMonth()->eq($other->startOfMonth()); } $units = [ 'month' => [1, 'year'], 'day' => [1, 'month'], 'hour' => [0, 'day'], 'minute' => [0, 'hour'], 'second' => [0, 'minute'], 'microsecond' => [0, 'second'], ]; foreach ($units as $unit => [$minimum, $startUnit]) { if ($minimum === $median->$unit) { $current = $current->startOf($startUnit); break; } } return $current->eq($other); } /** * Returns true if the date was created using CarbonImmutable::startOfTime() * * @return bool */ public function isStartOfTime(): bool { return $this->startOfTime ?? false; } /** * Returns true if the date was created using CarbonImmutable::endOfTime() * * @return bool */ public function isEndOfTime(): bool { return $this->endOfTime ?? false; } }
PHP
{ "end_line": 626, "name": "isSameUnit", "signature": "public function isSameUnit(string $unit, DateTimeInterface|string $date): bool", "start_line": 580 }
{ "class_name": "Comparison", "class_signature": "trait Comparison", "namespace": "Carbon\\Traits" }
isStartOfUnit
Carbon/src/Carbon/Traits/Comparison.php
public function isStartOfUnit( Unit $unit, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, mixed ...$params, ): bool { $interval ??= match ($unit) { Unit::Day, Unit::Hour, Unit::Minute, Unit::Second, Unit::Millisecond, Unit::Microsecond => Unit::Microsecond, default => Unit::Day, }; $startOfUnit = $this->avoidMutation()->startOf($unit, ...$params); $startOfUnitDateTime = $startOfUnit->rawFormat('Y-m-d H:i:s.u'); $maximumDateTime = $startOfUnit ->add($interval instanceof Unit ? '1 '.$interval->value : $interval) ->rawFormat('Y-m-d H:i:s.u'); if ($maximumDateTime < $startOfUnitDateTime) { return false; } return $this->rawFormat('Y-m-d H:i:s.u') < $maximumDateTime; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use BackedEnum; use BadMethodCallException; use Carbon\CarbonConverterInterface; use Carbon\CarbonInterface; use Carbon\Exceptions\BadComparisonUnitException; use Carbon\FactoryImmutable; use Carbon\Month; use Carbon\Unit; use Carbon\WeekDay; use Closure; use DateInterval; use DateTimeInterface; use InvalidArgumentException; /** * Trait Comparison. * * Comparison utils and testers. All the following methods return booleans. * nowWithSameTz * * Depends on the following methods: * * @method static resolveCarbon($date) * @method static copy() * @method static nowWithSameTz() * @method static static yesterday($timezone = null) * @method static static tomorrow($timezone = null) */ trait Comparison { protected bool $endOfTime = false; protected bool $startOfTime = false; /** * Determines if the instance is equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->eq(Carbon::parse('2018-07-25 12:45:16')); // true * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:17'); // false * ``` * * @see equalTo() */ public function eq(DateTimeInterface|string $date): bool { return $this->equalTo($date); } /** * Determines if the instance is equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->equalTo(Carbon::parse('2018-07-25 12:45:16')); // true * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:17'); // false * ``` */ public function equalTo(DateTimeInterface|string $date): bool { return $this == $this->resolveCarbon($date); } /** * Determines if the instance is not equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->ne(Carbon::parse('2018-07-25 12:45:16')); // false * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:17'); // true * ``` * * @see notEqualTo() */ public function ne(DateTimeInterface|string $date): bool { return $this->notEqualTo($date); } /** * Determines if the instance is not equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->notEqualTo(Carbon::parse('2018-07-25 12:45:16')); // false * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:17'); // true * ``` */ public function notEqualTo(DateTimeInterface|string $date): bool { return !$this->equalTo($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:17'); // false * ``` * * @see greaterThan() */ public function gt(DateTimeInterface|string $date): bool { return $this->greaterThan($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:17'); // false * ``` */ public function greaterThan(DateTimeInterface|string $date): bool { return $this > $this->resolveCarbon($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:17'); // false * ``` * * @see greaterThan() */ public function isAfter(DateTimeInterface|string $date): bool { return $this->greaterThan($date); } /** * Determines if the instance is greater (after) than or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:17'); // false * ``` * * @see greaterThanOrEqualTo() */ public function gte(DateTimeInterface|string $date): bool { return $this->greaterThanOrEqualTo($date); } /** * Determines if the instance is greater (after) than or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:17'); // false * ``` */ public function greaterThanOrEqualTo(DateTimeInterface|string $date): bool { return $this >= $this->resolveCarbon($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:17'); // true * ``` * * @see lessThan() */ public function lt(DateTimeInterface|string $date): bool { return $this->lessThan($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:17'); // true * ``` */ public function lessThan(DateTimeInterface|string $date): bool { return $this < $this->resolveCarbon($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:17'); // true * ``` * * @see lessThan() */ public function isBefore(DateTimeInterface|string $date): bool { return $this->lessThan($date); } /** * Determines if the instance is less (before) or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:17'); // true * ``` * * @see lessThanOrEqualTo() */ public function lte(DateTimeInterface|string $date): bool { return $this->lessThanOrEqualTo($date); } /** * Determines if the instance is less (before) or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:17'); // true * ``` */ public function lessThanOrEqualTo(DateTimeInterface|string $date): bool { return $this <= $this->resolveCarbon($date); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * Carbon::parse('2018-07-25')->between('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->between('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01'); // true * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01', false); // false * ``` * * @param bool $equal Indicates if an equal to comparison should be done */ public function between(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool { $date1 = $this->resolveCarbon($date1); $date2 = $this->resolveCarbon($date2); if ($date1->greaterThan($date2)) { [$date1, $date2] = [$date2, $date1]; } if ($equal) { return $this >= $date1 && $this <= $date2; } return $this > $date1 && $this < $date2; } /** * Determines if the instance is between two others, bounds included. * * @example * ``` * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->betweenIncluded('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-25', '2018-08-01'); // true * ``` */ public function betweenIncluded(DateTimeInterface|string $date1, DateTimeInterface|string $date2): bool { return $this->between($date1, $date2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->betweenExcluded('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-25', '2018-08-01'); // false * ``` */ public function betweenExcluded(DateTimeInterface|string $date1, DateTimeInterface|string $date2): bool { return $this->between($date1, $date2, false); } /** * Determines if the instance is between two others * * @example * ``` * Carbon::parse('2018-07-25')->isBetween('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->isBetween('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01'); // true * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01', false); // false * ``` * * @param bool $equal Indicates if an equal to comparison should be done */ public function isBetween(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool { return $this->between($date1, $date2, $equal); } /** * Determines if the instance is a weekday. * * @example * ``` * Carbon::parse('2019-07-14')->isWeekday(); // false * Carbon::parse('2019-07-15')->isWeekday(); // true * ``` */ public function isWeekday(): bool { return !$this->isWeekend(); } /** * Determines if the instance is a weekend day. * * @example * ``` * Carbon::parse('2019-07-14')->isWeekend(); // true * Carbon::parse('2019-07-15')->isWeekend(); // false * ``` */ public function isWeekend(): bool { return \in_array( $this->dayOfWeek, $this->transmitFactory(static fn () => static::getWeekendDays()), true, ); } /** * Determines if the instance is yesterday. * * @example * ``` * Carbon::yesterday()->isYesterday(); // true * Carbon::tomorrow()->isYesterday(); // false * ``` */ public function isYesterday(): bool { return $this->toDateString() === $this->transmitFactory( fn () => static::yesterday($this->getTimezone())->toDateString(), ); } /** * Determines if the instance is today. * * @example * ``` * Carbon::today()->isToday(); // true * Carbon::tomorrow()->isToday(); // false * ``` */ public function isToday(): bool { return $this->toDateString() === $this->nowWithSameTz()->toDateString(); } /** * Determines if the instance is tomorrow. * * @example * ``` * Carbon::tomorrow()->isTomorrow(); // true * Carbon::yesterday()->isTomorrow(); // false * ``` */ public function isTomorrow(): bool { return $this->toDateString() === $this->transmitFactory( fn () => static::tomorrow($this->getTimezone())->toDateString(), ); } /** * Determines if the instance is in the future, ie. greater (after) than now. * * @example * ``` * Carbon::now()->addHours(5)->isFuture(); // true * Carbon::now()->subHours(5)->isFuture(); // false * ``` */ public function isFuture(): bool { return $this->greaterThan($this->nowWithSameTz()); } /** * Determines if the instance is in the past, ie. less (before) than now. * * @example * ``` * Carbon::now()->subHours(5)->isPast(); // true * Carbon::now()->addHours(5)->isPast(); // false * ``` */ public function isPast(): bool { return $this->lessThan($this->nowWithSameTz()); } /** * Determines if the instance is now or in the future, ie. greater (after) than or equal to now. * * @example * ``` * Carbon::now()->isNowOrFuture(); // true * Carbon::now()->addHours(5)->isNowOrFuture(); // true * Carbon::now()->subHours(5)->isNowOrFuture(); // false * ``` */ public function isNowOrFuture(): bool { return $this->greaterThanOrEqualTo($this->nowWithSameTz()); } /** * Determines if the instance is now or in the past, ie. less (before) than or equal to now. * * @example * ``` * Carbon::now()->isNowOrPast(); // true * Carbon::now()->subHours(5)->isNowOrPast(); // true * Carbon::now()->addHours(5)->isNowOrPast(); // false * ``` */ public function isNowOrPast(): bool { return $this->lessThanOrEqualTo($this->nowWithSameTz()); } /** * Determines if the instance is a leap year. * * @example * ``` * Carbon::parse('2020-01-01')->isLeapYear(); // true * Carbon::parse('2019-01-01')->isLeapYear(); // false * ``` */ public function isLeapYear(): bool { return $this->rawFormat('L') === '1'; } /** * Determines if the instance is a long year (using calendar year). * * ⚠️ This method completely ignores month and day to use the numeric year number, * it's not correct if the exact date matters. For instance as `2019-12-30` is already * in the first week of the 2020 year, if you want to know from this date if ISO week * year 2020 is a long year, use `isLongIsoYear` instead. * * @example * ``` * Carbon::create(2015)->isLongYear(); // true * Carbon::create(2016)->isLongYear(); // false * ``` * * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates */ public function isLongYear(): bool { return static::create($this->year, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === static::WEEKS_PER_YEAR + 1; } /** * Determines if the instance is a long year (using ISO 8601 year). * * @example * ``` * Carbon::parse('2015-01-01')->isLongIsoYear(); // true * Carbon::parse('2016-01-01')->isLongIsoYear(); // true * Carbon::parse('2016-01-03')->isLongIsoYear(); // false * Carbon::parse('2019-12-29')->isLongIsoYear(); // false * Carbon::parse('2019-12-30')->isLongIsoYear(); // true * ``` * * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates */ public function isLongIsoYear(): bool { return static::create($this->isoWeekYear, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === 53; } /** * Compares the formatted values of the two dates. * * @example * ``` * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-12-13')); // true * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-06-14')); // false * ``` * * @param string $format date formats to compare. * @param DateTimeInterface|string $date instance to compare with or null to use current day. */ public function isSameAs(string $format, DateTimeInterface|string $date): bool { return $this->rawFormat($format) === $this->resolveCarbon($date)->rawFormat($format); } /** * Determines if the instance is in the current unit given. * * @example * ``` * Carbon::parse('2019-01-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // true * Carbon::parse('2018-12-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // false * ``` * * @param string $unit singular unit string * @param DateTimeInterface|string $date instance to compare with or null to use current day. * * @throws BadComparisonUnitException * * @return bool */ public function isSameUnit(string $unit, DateTimeInterface|string $date): bool { if ($unit === /* @call isSameUnit */ 'quarter') { $other = $this->resolveCarbon($date); return $other->year === $this->year && $other->quarter === $this->quarter; } $units = [ // @call isSameUnit 'year' => 'Y', // @call isSameUnit 'month' => 'Y-n', // @call isSameUnit 'week' => 'o-W', // @call isSameUnit 'day' => 'Y-m-d', // @call isSameUnit 'hour' => 'Y-m-d H', // @call isSameUnit 'minute' => 'Y-m-d H:i', // @call isSameUnit 'second' => 'Y-m-d H:i:s', // @call isSameUnit 'milli' => 'Y-m-d H:i:s.v', // @call isSameUnit 'millisecond' => 'Y-m-d H:i:s.v', // @call isSameUnit 'micro' => 'Y-m-d H:i:s.u', // @call isSameUnit 'microsecond' => 'Y-m-d H:i:s.u', ]; if (isset($units[$unit])) { return $this->isSameAs($units[$unit], $date); } if (isset($this->$unit)) { return $this->resolveCarbon($date)->$unit === $this->$unit; } if ($this->isLocalStrictModeEnabled()) { throw new BadComparisonUnitException($unit); } return false; } /** * Determines if the instance is in the current unit given. * * @example * ``` * Carbon::now()->isCurrentUnit('hour'); // true * Carbon::now()->subHours(2)->isCurrentUnit('hour'); // false * ``` * * @param string $unit The unit to test. * * @throws BadMethodCallException */ public function isCurrentUnit(string $unit): bool { return $this->{'isSame'.ucfirst($unit)}('now'); } /** * Checks if the passed in date is in the same quarter as the instance quarter (and year if needed). * * @example * ``` * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-03-01')); // true * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-04-01')); // false * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01')); // false * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01'), false); // true * ``` * * @param DateTimeInterface|string $date The instance to compare with or null to use current day. * @param bool $ofSameYear Check if it is the same month in the same year. * * @return bool */ public function isSameQuarter(DateTimeInterface|string $date, bool $ofSameYear = true): bool { $date = $this->resolveCarbon($date); return $this->quarter === $date->quarter && (!$ofSameYear || $this->isSameYear($date)); } /** * Checks if the passed in date is in the same month as the instance´s month. * * @example * ``` * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-01-01')); // true * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-02-01')); // false * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01')); // false * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01'), false); // true * ``` * * @param DateTimeInterface|string $date The instance to compare with or null to use the current date. * @param bool $ofSameYear Check if it is the same month in the same year. * * @return bool */ public function isSameMonth(DateTimeInterface|string $date, bool $ofSameYear = true): bool { return $this->isSameAs($ofSameYear ? 'Y-m' : 'm', $date); } /** * Checks if this day is a specific day of the week. * * @example * ``` * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::WEDNESDAY); // true * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::FRIDAY); // false * Carbon::parse('2019-07-17')->isDayOfWeek('Wednesday'); // true * Carbon::parse('2019-07-17')->isDayOfWeek('Friday'); // false * ``` * * @param int|string $dayOfWeek * * @return bool */ public function isDayOfWeek($dayOfWeek): bool { if (\is_string($dayOfWeek) && \defined($constant = static::class.'::'.strtoupper($dayOfWeek))) { $dayOfWeek = \constant($constant); } return $this->dayOfWeek === $dayOfWeek; } /** * Check if its the birthday. Compares the date/month values of the two dates. * * @example * ``` * Carbon::now()->subYears(5)->isBirthday(); // true * Carbon::now()->subYears(5)->subDay()->isBirthday(); // false * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-05')); // true * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-06')); // false * ``` * * @param DateTimeInterface|string|null $date The instance to compare with or null to use current day. * * @return bool */ public function isBirthday(DateTimeInterface|string|null $date = null): bool { return $this->isSameAs('md', $date ?? 'now'); } /** * Check if today is the last day of the Month * * @example * ``` * Carbon::parse('2019-02-28')->isLastOfMonth(); // true * Carbon::parse('2019-03-28')->isLastOfMonth(); // false * Carbon::parse('2019-03-30')->isLastOfMonth(); // false * Carbon::parse('2019-03-31')->isLastOfMonth(); // true * Carbon::parse('2019-04-30')->isLastOfMonth(); // true * ``` */ public function isLastOfMonth(): bool { return $this->day === $this->daysInMonth; } /** * Check if the instance is start of a given unit (tolerating a given interval). * * @example * ``` * // Check if a date-time is the first 15 minutes of the hour it's in * Carbon::parse('2019-02-28 20:13:00')->isStartOfUnit(Unit::Hour, '15 minutes'); // true * ``` */ public function isStartOfUnit( Unit $unit, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, mixed ...$params, ): bool { $interval ??= match ($unit) { Unit::Day, Unit::Hour, Unit::Minute, Unit::Second, Unit::Millisecond, Unit::Microsecond => Unit::Microsecond, default => Unit::Day, }; $startOfUnit = $this->avoidMutation()->startOf($unit, ...$params); $startOfUnitDateTime = $startOfUnit->rawFormat('Y-m-d H:i:s.u'); $maximumDateTime = $startOfUnit ->add($interval instanceof Unit ? '1 '.$interval->value : $interval) ->rawFormat('Y-m-d H:i:s.u'); if ($maximumDateTime < $startOfUnitDateTime) { return false; } return $this->rawFormat('Y-m-d H:i:s.u') < $maximumDateTime; } /** * Check if the instance is end of a given unit (tolerating a given interval). * * @example * ``` * // Check if a date-time is the last 15 minutes of the hour it's in * Carbon::parse('2019-02-28 20:13:00')->isEndOfUnit(Unit::Hour, '15 minutes'); // false * ``` */ public function isEndOfUnit( Unit $unit, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, mixed ...$params, ): bool { $interval ??= match ($unit) { Unit::Day, Unit::Hour, Unit::Minute, Unit::Second, Unit::Millisecond, Unit::Microsecond => Unit::Microsecond, default => Unit::Day, }; $endOfUnit = $this->avoidMutation()->endOf($unit, ...$params); $endOfUnitDateTime = $endOfUnit->rawFormat('Y-m-d H:i:s.u'); $minimumDateTime = $endOfUnit ->sub($interval instanceof Unit ? '1 '.$interval->value : $interval) ->rawFormat('Y-m-d H:i:s.u'); if ($minimumDateTime > $endOfUnitDateTime) { return false; } return $this->rawFormat('Y-m-d H:i:s.u') > $minimumDateTime; } /** * Determines if the instance is start of millisecond (first microsecond by default but interval can be customized). */ public function isStartOfMillisecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Millisecond, $interval); } /** * Determines if the instance is end of millisecond (last microsecond by default but interval can be customized). */ public function isEndOfMillisecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Millisecond, $interval); } /** * Determines if the instance is start of second (first microsecond by default but interval can be customized). */ public function isStartOfSecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Second, $interval); } /** * Determines if the instance is end of second (last microsecond by default but interval can be customized). */ public function isEndOfSecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Second, $interval); } /** * Determines if the instance is start of minute (first microsecond by default but interval can be customized). */ public function isStartOfMinute( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Minute, $interval); } /** * Determines if the instance is end of minute (last microsecond by default but interval can be customized). */ public function isEndOfMinute( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Minute, $interval); } /** * Determines if the instance is start of hour (first microsecond by default but interval can be customized). */ public function isStartOfHour( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Hour, $interval); } /** * Determines if the instance is end of hour (last microsecond by default but interval can be customized). */ public function isEndOfHour( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Hour, $interval); } /** * Check if the instance is start of day / midnight. * * @example * ``` * Carbon::parse('2019-02-28 00:00:00')->isStartOfDay(); // true * Carbon::parse('2019-02-28 00:00:00.999999')->isStartOfDay(); // true * Carbon::parse('2019-02-28 00:00:01')->isStartOfDay(); // false * Carbon::parse('2019-02-28 00:00:00.000000')->isStartOfDay(true); // true * Carbon::parse('2019-02-28 00:00:00.000012')->isStartOfDay(true); // false * ``` * * @param bool $checkMicroseconds check time at microseconds precision * @param Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval if an interval is specified it will be used as precision * for instance with "15 minutes", it checks if current date-time * is in the last 15 minutes of the day, with Unit::Hour, it * checks if it's in the last hour of the day. */ public function isStartOfDay( Unit|DateInterval|Closure|CarbonConverterInterface|string|bool $checkMicroseconds = false, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { if ($checkMicroseconds === true) { @trigger_error( "Since 3.8.0, it's deprecated to use \$checkMicroseconds.\n". "It will be removed in 4.0.0.\n". "Instead, you should use either isStartOfDay(interval: Unit::Microsecond) or isStartOfDay(interval: Unit::Second)\n". 'And you can now use any custom interval as precision, such as isStartOfDay(interval: "15 minutes")', \E_USER_DEPRECATED, ); } if ($interval === null && !\is_bool($checkMicroseconds)) { $interval = $checkMicroseconds; } if ($interval !== null) { if ($interval instanceof Unit) { $interval = '1 '.$interval->value; } $date = $this->rawFormat('Y-m-d'); $time = $this->rawFormat('H:i:s.u'); $maximum = $this->avoidMutation()->startOfDay()->add($interval); $maximumDate = $maximum->rawFormat('Y-m-d'); if ($date === $maximumDate) { return $time < $maximum->rawFormat('H:i:s.u'); } return $maximumDate > $date; } /* @var CarbonInterface $this */ return $checkMicroseconds ? $this->rawFormat('H:i:s.u') === '00:00:00.000000' : $this->rawFormat('H:i:s') === '00:00:00'; } /** * Check if the instance is end of day. * * @example * ``` * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:58.999999')->isEndOfDay(); // false * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(true); // true * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(true); // false * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(true); // false * ``` * * @param bool $checkMicroseconds check time at microseconds precision * @param Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval if an interval is specified it will be used as precision * for instance with "15 minutes", it checks if current date-time * is in the last 15 minutes of the day, with Unit::Hour, it * checks if it's in the last hour of the day. */ public function isEndOfDay( Unit|DateInterval|Closure|CarbonConverterInterface|string|bool $checkMicroseconds = false, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { if ($checkMicroseconds === true) { @trigger_error( "Since 3.8.0, it's deprecated to use \$checkMicroseconds.\n". "It will be removed in 4.0.0.\n". "Instead, you should use either isEndOfDay(interval: Unit::Microsecond) or isEndOfDay(interval: Unit::Second)\n". 'And you can now use any custom interval as precision, such as isEndOfDay(interval: "15 minutes")', \E_USER_DEPRECATED, ); } if ($interval === null && !\is_bool($checkMicroseconds)) { $interval = $checkMicroseconds; } if ($interval !== null) { $date = $this->rawFormat('Y-m-d'); $time = $this->rawFormat('H:i:s.u'); $minimum = $this->avoidMutation() ->endOfDay() ->sub($interval instanceof Unit ? '1 '.$interval->value : $interval); $minimumDate = $minimum->rawFormat('Y-m-d'); if ($date === $minimumDate) { return $time > $minimum->rawFormat('H:i:s.u'); } return $minimumDate < $date; } /* @var CarbonInterface $this */ return $checkMicroseconds ? $this->rawFormat('H:i:s.u') === '23:59:59.999999' : $this->rawFormat('H:i:s') === '23:59:59'; } /** * Determines if the instance is start of week (first day by default but interval can be customized). * * @example * ``` * Carbon::parse('2024-08-31')->startOfWeek()->isStartOfWeek(); // true * Carbon::parse('2024-08-31')->isStartOfWeek(); // false * ``` */ public function isStartOfWeek( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, WeekDay|int|null $weekStartsAt = null, ): bool { return $this->isStartOfUnit(Unit::Week, $interval, $weekStartsAt); } /** * Determines if the instance is end of week (last day by default but interval can be customized). * * @example * ``` * Carbon::parse('2024-08-31')->endOfWeek()->isEndOfWeek(); // true * Carbon::parse('2024-08-31')->isEndOfWeek(); // false * ``` */ public function isEndOfWeek( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, WeekDay|int|null $weekEndsAt = null, ): bool { return $this->isEndOfUnit(Unit::Week, $interval, $weekEndsAt); } /** * Determines if the instance is start of month (first day by default but interval can be customized). */ public function isStartOfMonth( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Month, $interval); } /** * Determines if the instance is end of month (last day by default but interval can be customized). */ public function isEndOfMonth( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Month, $interval); } /** * Determines if the instance is start of quarter (first day by default but interval can be customized). */ public function isStartOfQuarter( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Quarter, $interval); } /** * Determines if the instance is end of quarter (last day by default but interval can be customized). */ public function isEndOfQuarter( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Quarter, $interval); } /** * Determines if the instance is start of year (first day by default but interval can be customized). */ public function isStartOfYear( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Year, $interval); } /** * Determines if the instance is end of year (last day by default but interval can be customized). */ public function isEndOfYear( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Year, $interval); } /** * Determines if the instance is start of decade (first day by default but interval can be customized). */ public function isStartOfDecade( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Decade, $interval); } /** * Determines if the instance is end of decade (last day by default but interval can be customized). */ public function isEndOfDecade( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Decade, $interval); } /** * Determines if the instance is start of century (first day by default but interval can be customized). */ public function isStartOfCentury( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Century, $interval); } /** * Determines if the instance is end of century (last day by default but interval can be customized). */ public function isEndOfCentury( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Century, $interval); } /** * Determines if the instance is start of millennium (first day by default but interval can be customized). */ public function isStartOfMillennium( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Millennium, $interval); } /** * Determines if the instance is end of millennium (last day by default but interval can be customized). */ public function isEndOfMillennium( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Millennium, $interval); } /** * Check if the instance is start of day / midnight. * * @example * ``` * Carbon::parse('2019-02-28 00:00:00')->isMidnight(); // true * Carbon::parse('2019-02-28 00:00:00.999999')->isMidnight(); // true * Carbon::parse('2019-02-28 00:00:01')->isMidnight(); // false * ``` */ public function isMidnight(): bool { return $this->isStartOfDay(); } /** * Check if the instance is midday. * * @example * ``` * Carbon::parse('2019-02-28 11:59:59.999999')->isMidday(); // false * Carbon::parse('2019-02-28 12:00:00')->isMidday(); // true * Carbon::parse('2019-02-28 12:00:00.999999')->isMidday(); // true * Carbon::parse('2019-02-28 12:00:01')->isMidday(); // false * ``` */ public function isMidday(): bool { /* @var CarbonInterface $this */ return $this->rawFormat('G:i:s') === static::$midDayAt.':00:00'; } /** * Checks if the (date)time string is in a given format. * * @example * ``` * Carbon::hasFormat('11:12:45', 'h:i:s'); // true * Carbon::hasFormat('13:12:45', 'h:i:s'); // false * ``` */ public static function hasFormat(string $date, string $format): bool { return FactoryImmutable::getInstance()->hasFormat($date, $format); } /** * Checks if the (date)time string is in a given format. * * @example * ``` * Carbon::hasFormatWithModifiers('31/08/2015', 'd#m#Y'); // true * Carbon::hasFormatWithModifiers('31/08/2015', 'm#d#Y'); // false * ``` * * @param string $date * @param string $format * * @return bool */ public static function hasFormatWithModifiers(?string $date, string $format): bool { return FactoryImmutable::getInstance()->hasFormatWithModifiers($date, $format); } /** * Checks if the (date)time string is in a given format and valid to create a * new instance. * * @example * ``` * Carbon::canBeCreatedFromFormat('11:12:45', 'h:i:s'); // true * Carbon::canBeCreatedFromFormat('13:12:45', 'h:i:s'); // false * ``` */ public static function canBeCreatedFromFormat(?string $date, string $format): bool { if ($date === null) { return false; } try { // Try to create a DateTime object. Throws an InvalidArgumentException if the provided time string // doesn't match the format in any way. if (!static::rawCreateFromFormat($format, $date)) { return false; } } catch (InvalidArgumentException) { return false; } return static::hasFormatWithModifiers($date, $format); } /** * Returns true if the current date matches the given string. * * @example * ``` * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2018')); // false * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('06-02')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06-02')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('Sunday')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('June')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:45')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:00')); // false * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12h')); // true * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3pm')); // true * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3am')); // false * ``` * * @param string $tester day name, month name, hour, date, etc. as string */ public function is(WeekDay|Month|string $tester): bool { if ($tester instanceof BackedEnum) { $tester = $tester->name; } $tester = trim($tester); if (preg_match('/^\d+$/', $tester)) { return $this->year === (int) $tester; } if (preg_match('/^(?:Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|September|Oct|October|Nov|November|Dec|December)$/i', $tester)) { return $this->isSameMonth( $this->transmitFactory(static fn () => static::parse("$tester 1st")), false, ); } if (preg_match('/^\d{3,}-\d{1,2}$/', $tester)) { return $this->isSameMonth( $this->transmitFactory(static fn () => static::parse($tester)), ); } if (preg_match('/^(\d{1,2})-(\d{1,2})$/', $tester, $match)) { return $this->month === (int) $match[1] && $this->day === (int) $match[2]; } $modifier = preg_replace('/(\d)h$/i', '$1:00', $tester); /* @var CarbonInterface $max */ $median = $this->transmitFactory(static fn () => static::parse('5555-06-15 12:30:30.555555')) ->modify($modifier); $current = $this->avoidMutation(); /* @var CarbonInterface $other */ $other = $this->avoidMutation()->modify($modifier); if ($current->eq($other)) { return true; } if (preg_match('/\d:\d{1,2}:\d{1,2}$/', $tester)) { return $current->startOfSecond()->eq($other); } if (preg_match('/\d:\d{1,2}$/', $tester)) { return $current->startOfMinute()->eq($other); } if (preg_match('/\d(?:h|am|pm)$/', $tester)) { return $current->startOfHour()->eq($other); } if (preg_match( '/^(?:january|february|march|april|may|june|july|august|september|october|november|december)(?:\s+\d+)?$/i', $tester, )) { return $current->startOfMonth()->eq($other->startOfMonth()); } $units = [ 'month' => [1, 'year'], 'day' => [1, 'month'], 'hour' => [0, 'day'], 'minute' => [0, 'hour'], 'second' => [0, 'minute'], 'microsecond' => [0, 'second'], ]; foreach ($units as $unit => [$minimum, $startUnit]) { if ($minimum === $median->$unit) { $current = $current->startOf($startUnit); break; } } return $current->eq($other); } /** * Returns true if the date was created using CarbonImmutable::startOfTime() * * @return bool */ public function isStartOfTime(): bool { return $this->startOfTime ?? false; } /** * Returns true if the date was created using CarbonImmutable::endOfTime() * * @return bool */ public function isEndOfTime(): bool { return $this->endOfTime ?? false; } }
PHP
{ "end_line": 781, "name": "isStartOfUnit", "signature": "public function isStartOfUnit(", "start_line": 760 }
{ "class_name": "Comparison", "class_signature": "trait Comparison", "namespace": "Carbon\\Traits" }
isEndOfUnit
Carbon/src/Carbon/Traits/Comparison.php
public function isEndOfUnit( Unit $unit, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, mixed ...$params, ): bool { $interval ??= match ($unit) { Unit::Day, Unit::Hour, Unit::Minute, Unit::Second, Unit::Millisecond, Unit::Microsecond => Unit::Microsecond, default => Unit::Day, }; $endOfUnit = $this->avoidMutation()->endOf($unit, ...$params); $endOfUnitDateTime = $endOfUnit->rawFormat('Y-m-d H:i:s.u'); $minimumDateTime = $endOfUnit ->sub($interval instanceof Unit ? '1 '.$interval->value : $interval) ->rawFormat('Y-m-d H:i:s.u'); if ($minimumDateTime > $endOfUnitDateTime) { return false; } return $this->rawFormat('Y-m-d H:i:s.u') > $minimumDateTime; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use BackedEnum; use BadMethodCallException; use Carbon\CarbonConverterInterface; use Carbon\CarbonInterface; use Carbon\Exceptions\BadComparisonUnitException; use Carbon\FactoryImmutable; use Carbon\Month; use Carbon\Unit; use Carbon\WeekDay; use Closure; use DateInterval; use DateTimeInterface; use InvalidArgumentException; /** * Trait Comparison. * * Comparison utils and testers. All the following methods return booleans. * nowWithSameTz * * Depends on the following methods: * * @method static resolveCarbon($date) * @method static copy() * @method static nowWithSameTz() * @method static static yesterday($timezone = null) * @method static static tomorrow($timezone = null) */ trait Comparison { protected bool $endOfTime = false; protected bool $startOfTime = false; /** * Determines if the instance is equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->eq(Carbon::parse('2018-07-25 12:45:16')); // true * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:17'); // false * ``` * * @see equalTo() */ public function eq(DateTimeInterface|string $date): bool { return $this->equalTo($date); } /** * Determines if the instance is equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->equalTo(Carbon::parse('2018-07-25 12:45:16')); // true * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:17'); // false * ``` */ public function equalTo(DateTimeInterface|string $date): bool { return $this == $this->resolveCarbon($date); } /** * Determines if the instance is not equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->ne(Carbon::parse('2018-07-25 12:45:16')); // false * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:17'); // true * ``` * * @see notEqualTo() */ public function ne(DateTimeInterface|string $date): bool { return $this->notEqualTo($date); } /** * Determines if the instance is not equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->notEqualTo(Carbon::parse('2018-07-25 12:45:16')); // false * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:17'); // true * ``` */ public function notEqualTo(DateTimeInterface|string $date): bool { return !$this->equalTo($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:17'); // false * ``` * * @see greaterThan() */ public function gt(DateTimeInterface|string $date): bool { return $this->greaterThan($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:17'); // false * ``` */ public function greaterThan(DateTimeInterface|string $date): bool { return $this > $this->resolveCarbon($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:17'); // false * ``` * * @see greaterThan() */ public function isAfter(DateTimeInterface|string $date): bool { return $this->greaterThan($date); } /** * Determines if the instance is greater (after) than or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:17'); // false * ``` * * @see greaterThanOrEqualTo() */ public function gte(DateTimeInterface|string $date): bool { return $this->greaterThanOrEqualTo($date); } /** * Determines if the instance is greater (after) than or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:17'); // false * ``` */ public function greaterThanOrEqualTo(DateTimeInterface|string $date): bool { return $this >= $this->resolveCarbon($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:17'); // true * ``` * * @see lessThan() */ public function lt(DateTimeInterface|string $date): bool { return $this->lessThan($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:17'); // true * ``` */ public function lessThan(DateTimeInterface|string $date): bool { return $this < $this->resolveCarbon($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:17'); // true * ``` * * @see lessThan() */ public function isBefore(DateTimeInterface|string $date): bool { return $this->lessThan($date); } /** * Determines if the instance is less (before) or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:17'); // true * ``` * * @see lessThanOrEqualTo() */ public function lte(DateTimeInterface|string $date): bool { return $this->lessThanOrEqualTo($date); } /** * Determines if the instance is less (before) or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:17'); // true * ``` */ public function lessThanOrEqualTo(DateTimeInterface|string $date): bool { return $this <= $this->resolveCarbon($date); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * Carbon::parse('2018-07-25')->between('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->between('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01'); // true * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01', false); // false * ``` * * @param bool $equal Indicates if an equal to comparison should be done */ public function between(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool { $date1 = $this->resolveCarbon($date1); $date2 = $this->resolveCarbon($date2); if ($date1->greaterThan($date2)) { [$date1, $date2] = [$date2, $date1]; } if ($equal) { return $this >= $date1 && $this <= $date2; } return $this > $date1 && $this < $date2; } /** * Determines if the instance is between two others, bounds included. * * @example * ``` * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->betweenIncluded('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-25', '2018-08-01'); // true * ``` */ public function betweenIncluded(DateTimeInterface|string $date1, DateTimeInterface|string $date2): bool { return $this->between($date1, $date2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->betweenExcluded('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-25', '2018-08-01'); // false * ``` */ public function betweenExcluded(DateTimeInterface|string $date1, DateTimeInterface|string $date2): bool { return $this->between($date1, $date2, false); } /** * Determines if the instance is between two others * * @example * ``` * Carbon::parse('2018-07-25')->isBetween('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->isBetween('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01'); // true * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01', false); // false * ``` * * @param bool $equal Indicates if an equal to comparison should be done */ public function isBetween(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool { return $this->between($date1, $date2, $equal); } /** * Determines if the instance is a weekday. * * @example * ``` * Carbon::parse('2019-07-14')->isWeekday(); // false * Carbon::parse('2019-07-15')->isWeekday(); // true * ``` */ public function isWeekday(): bool { return !$this->isWeekend(); } /** * Determines if the instance is a weekend day. * * @example * ``` * Carbon::parse('2019-07-14')->isWeekend(); // true * Carbon::parse('2019-07-15')->isWeekend(); // false * ``` */ public function isWeekend(): bool { return \in_array( $this->dayOfWeek, $this->transmitFactory(static fn () => static::getWeekendDays()), true, ); } /** * Determines if the instance is yesterday. * * @example * ``` * Carbon::yesterday()->isYesterday(); // true * Carbon::tomorrow()->isYesterday(); // false * ``` */ public function isYesterday(): bool { return $this->toDateString() === $this->transmitFactory( fn () => static::yesterday($this->getTimezone())->toDateString(), ); } /** * Determines if the instance is today. * * @example * ``` * Carbon::today()->isToday(); // true * Carbon::tomorrow()->isToday(); // false * ``` */ public function isToday(): bool { return $this->toDateString() === $this->nowWithSameTz()->toDateString(); } /** * Determines if the instance is tomorrow. * * @example * ``` * Carbon::tomorrow()->isTomorrow(); // true * Carbon::yesterday()->isTomorrow(); // false * ``` */ public function isTomorrow(): bool { return $this->toDateString() === $this->transmitFactory( fn () => static::tomorrow($this->getTimezone())->toDateString(), ); } /** * Determines if the instance is in the future, ie. greater (after) than now. * * @example * ``` * Carbon::now()->addHours(5)->isFuture(); // true * Carbon::now()->subHours(5)->isFuture(); // false * ``` */ public function isFuture(): bool { return $this->greaterThan($this->nowWithSameTz()); } /** * Determines if the instance is in the past, ie. less (before) than now. * * @example * ``` * Carbon::now()->subHours(5)->isPast(); // true * Carbon::now()->addHours(5)->isPast(); // false * ``` */ public function isPast(): bool { return $this->lessThan($this->nowWithSameTz()); } /** * Determines if the instance is now or in the future, ie. greater (after) than or equal to now. * * @example * ``` * Carbon::now()->isNowOrFuture(); // true * Carbon::now()->addHours(5)->isNowOrFuture(); // true * Carbon::now()->subHours(5)->isNowOrFuture(); // false * ``` */ public function isNowOrFuture(): bool { return $this->greaterThanOrEqualTo($this->nowWithSameTz()); } /** * Determines if the instance is now or in the past, ie. less (before) than or equal to now. * * @example * ``` * Carbon::now()->isNowOrPast(); // true * Carbon::now()->subHours(5)->isNowOrPast(); // true * Carbon::now()->addHours(5)->isNowOrPast(); // false * ``` */ public function isNowOrPast(): bool { return $this->lessThanOrEqualTo($this->nowWithSameTz()); } /** * Determines if the instance is a leap year. * * @example * ``` * Carbon::parse('2020-01-01')->isLeapYear(); // true * Carbon::parse('2019-01-01')->isLeapYear(); // false * ``` */ public function isLeapYear(): bool { return $this->rawFormat('L') === '1'; } /** * Determines if the instance is a long year (using calendar year). * * ⚠️ This method completely ignores month and day to use the numeric year number, * it's not correct if the exact date matters. For instance as `2019-12-30` is already * in the first week of the 2020 year, if you want to know from this date if ISO week * year 2020 is a long year, use `isLongIsoYear` instead. * * @example * ``` * Carbon::create(2015)->isLongYear(); // true * Carbon::create(2016)->isLongYear(); // false * ``` * * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates */ public function isLongYear(): bool { return static::create($this->year, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === static::WEEKS_PER_YEAR + 1; } /** * Determines if the instance is a long year (using ISO 8601 year). * * @example * ``` * Carbon::parse('2015-01-01')->isLongIsoYear(); // true * Carbon::parse('2016-01-01')->isLongIsoYear(); // true * Carbon::parse('2016-01-03')->isLongIsoYear(); // false * Carbon::parse('2019-12-29')->isLongIsoYear(); // false * Carbon::parse('2019-12-30')->isLongIsoYear(); // true * ``` * * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates */ public function isLongIsoYear(): bool { return static::create($this->isoWeekYear, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === 53; } /** * Compares the formatted values of the two dates. * * @example * ``` * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-12-13')); // true * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-06-14')); // false * ``` * * @param string $format date formats to compare. * @param DateTimeInterface|string $date instance to compare with or null to use current day. */ public function isSameAs(string $format, DateTimeInterface|string $date): bool { return $this->rawFormat($format) === $this->resolveCarbon($date)->rawFormat($format); } /** * Determines if the instance is in the current unit given. * * @example * ``` * Carbon::parse('2019-01-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // true * Carbon::parse('2018-12-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // false * ``` * * @param string $unit singular unit string * @param DateTimeInterface|string $date instance to compare with or null to use current day. * * @throws BadComparisonUnitException * * @return bool */ public function isSameUnit(string $unit, DateTimeInterface|string $date): bool { if ($unit === /* @call isSameUnit */ 'quarter') { $other = $this->resolveCarbon($date); return $other->year === $this->year && $other->quarter === $this->quarter; } $units = [ // @call isSameUnit 'year' => 'Y', // @call isSameUnit 'month' => 'Y-n', // @call isSameUnit 'week' => 'o-W', // @call isSameUnit 'day' => 'Y-m-d', // @call isSameUnit 'hour' => 'Y-m-d H', // @call isSameUnit 'minute' => 'Y-m-d H:i', // @call isSameUnit 'second' => 'Y-m-d H:i:s', // @call isSameUnit 'milli' => 'Y-m-d H:i:s.v', // @call isSameUnit 'millisecond' => 'Y-m-d H:i:s.v', // @call isSameUnit 'micro' => 'Y-m-d H:i:s.u', // @call isSameUnit 'microsecond' => 'Y-m-d H:i:s.u', ]; if (isset($units[$unit])) { return $this->isSameAs($units[$unit], $date); } if (isset($this->$unit)) { return $this->resolveCarbon($date)->$unit === $this->$unit; } if ($this->isLocalStrictModeEnabled()) { throw new BadComparisonUnitException($unit); } return false; } /** * Determines if the instance is in the current unit given. * * @example * ``` * Carbon::now()->isCurrentUnit('hour'); // true * Carbon::now()->subHours(2)->isCurrentUnit('hour'); // false * ``` * * @param string $unit The unit to test. * * @throws BadMethodCallException */ public function isCurrentUnit(string $unit): bool { return $this->{'isSame'.ucfirst($unit)}('now'); } /** * Checks if the passed in date is in the same quarter as the instance quarter (and year if needed). * * @example * ``` * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-03-01')); // true * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-04-01')); // false * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01')); // false * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01'), false); // true * ``` * * @param DateTimeInterface|string $date The instance to compare with or null to use current day. * @param bool $ofSameYear Check if it is the same month in the same year. * * @return bool */ public function isSameQuarter(DateTimeInterface|string $date, bool $ofSameYear = true): bool { $date = $this->resolveCarbon($date); return $this->quarter === $date->quarter && (!$ofSameYear || $this->isSameYear($date)); } /** * Checks if the passed in date is in the same month as the instance´s month. * * @example * ``` * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-01-01')); // true * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-02-01')); // false * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01')); // false * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01'), false); // true * ``` * * @param DateTimeInterface|string $date The instance to compare with or null to use the current date. * @param bool $ofSameYear Check if it is the same month in the same year. * * @return bool */ public function isSameMonth(DateTimeInterface|string $date, bool $ofSameYear = true): bool { return $this->isSameAs($ofSameYear ? 'Y-m' : 'm', $date); } /** * Checks if this day is a specific day of the week. * * @example * ``` * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::WEDNESDAY); // true * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::FRIDAY); // false * Carbon::parse('2019-07-17')->isDayOfWeek('Wednesday'); // true * Carbon::parse('2019-07-17')->isDayOfWeek('Friday'); // false * ``` * * @param int|string $dayOfWeek * * @return bool */ public function isDayOfWeek($dayOfWeek): bool { if (\is_string($dayOfWeek) && \defined($constant = static::class.'::'.strtoupper($dayOfWeek))) { $dayOfWeek = \constant($constant); } return $this->dayOfWeek === $dayOfWeek; } /** * Check if its the birthday. Compares the date/month values of the two dates. * * @example * ``` * Carbon::now()->subYears(5)->isBirthday(); // true * Carbon::now()->subYears(5)->subDay()->isBirthday(); // false * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-05')); // true * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-06')); // false * ``` * * @param DateTimeInterface|string|null $date The instance to compare with or null to use current day. * * @return bool */ public function isBirthday(DateTimeInterface|string|null $date = null): bool { return $this->isSameAs('md', $date ?? 'now'); } /** * Check if today is the last day of the Month * * @example * ``` * Carbon::parse('2019-02-28')->isLastOfMonth(); // true * Carbon::parse('2019-03-28')->isLastOfMonth(); // false * Carbon::parse('2019-03-30')->isLastOfMonth(); // false * Carbon::parse('2019-03-31')->isLastOfMonth(); // true * Carbon::parse('2019-04-30')->isLastOfMonth(); // true * ``` */ public function isLastOfMonth(): bool { return $this->day === $this->daysInMonth; } /** * Check if the instance is start of a given unit (tolerating a given interval). * * @example * ``` * // Check if a date-time is the first 15 minutes of the hour it's in * Carbon::parse('2019-02-28 20:13:00')->isStartOfUnit(Unit::Hour, '15 minutes'); // true * ``` */ public function isStartOfUnit( Unit $unit, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, mixed ...$params, ): bool { $interval ??= match ($unit) { Unit::Day, Unit::Hour, Unit::Minute, Unit::Second, Unit::Millisecond, Unit::Microsecond => Unit::Microsecond, default => Unit::Day, }; $startOfUnit = $this->avoidMutation()->startOf($unit, ...$params); $startOfUnitDateTime = $startOfUnit->rawFormat('Y-m-d H:i:s.u'); $maximumDateTime = $startOfUnit ->add($interval instanceof Unit ? '1 '.$interval->value : $interval) ->rawFormat('Y-m-d H:i:s.u'); if ($maximumDateTime < $startOfUnitDateTime) { return false; } return $this->rawFormat('Y-m-d H:i:s.u') < $maximumDateTime; } /** * Check if the instance is end of a given unit (tolerating a given interval). * * @example * ``` * // Check if a date-time is the last 15 minutes of the hour it's in * Carbon::parse('2019-02-28 20:13:00')->isEndOfUnit(Unit::Hour, '15 minutes'); // false * ``` */ public function isEndOfUnit( Unit $unit, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, mixed ...$params, ): bool { $interval ??= match ($unit) { Unit::Day, Unit::Hour, Unit::Minute, Unit::Second, Unit::Millisecond, Unit::Microsecond => Unit::Microsecond, default => Unit::Day, }; $endOfUnit = $this->avoidMutation()->endOf($unit, ...$params); $endOfUnitDateTime = $endOfUnit->rawFormat('Y-m-d H:i:s.u'); $minimumDateTime = $endOfUnit ->sub($interval instanceof Unit ? '1 '.$interval->value : $interval) ->rawFormat('Y-m-d H:i:s.u'); if ($minimumDateTime > $endOfUnitDateTime) { return false; } return $this->rawFormat('Y-m-d H:i:s.u') > $minimumDateTime; } /** * Determines if the instance is start of millisecond (first microsecond by default but interval can be customized). */ public function isStartOfMillisecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Millisecond, $interval); } /** * Determines if the instance is end of millisecond (last microsecond by default but interval can be customized). */ public function isEndOfMillisecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Millisecond, $interval); } /** * Determines if the instance is start of second (first microsecond by default but interval can be customized). */ public function isStartOfSecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Second, $interval); } /** * Determines if the instance is end of second (last microsecond by default but interval can be customized). */ public function isEndOfSecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Second, $interval); } /** * Determines if the instance is start of minute (first microsecond by default but interval can be customized). */ public function isStartOfMinute( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Minute, $interval); } /** * Determines if the instance is end of minute (last microsecond by default but interval can be customized). */ public function isEndOfMinute( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Minute, $interval); } /** * Determines if the instance is start of hour (first microsecond by default but interval can be customized). */ public function isStartOfHour( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Hour, $interval); } /** * Determines if the instance is end of hour (last microsecond by default but interval can be customized). */ public function isEndOfHour( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Hour, $interval); } /** * Check if the instance is start of day / midnight. * * @example * ``` * Carbon::parse('2019-02-28 00:00:00')->isStartOfDay(); // true * Carbon::parse('2019-02-28 00:00:00.999999')->isStartOfDay(); // true * Carbon::parse('2019-02-28 00:00:01')->isStartOfDay(); // false * Carbon::parse('2019-02-28 00:00:00.000000')->isStartOfDay(true); // true * Carbon::parse('2019-02-28 00:00:00.000012')->isStartOfDay(true); // false * ``` * * @param bool $checkMicroseconds check time at microseconds precision * @param Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval if an interval is specified it will be used as precision * for instance with "15 minutes", it checks if current date-time * is in the last 15 minutes of the day, with Unit::Hour, it * checks if it's in the last hour of the day. */ public function isStartOfDay( Unit|DateInterval|Closure|CarbonConverterInterface|string|bool $checkMicroseconds = false, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { if ($checkMicroseconds === true) { @trigger_error( "Since 3.8.0, it's deprecated to use \$checkMicroseconds.\n". "It will be removed in 4.0.0.\n". "Instead, you should use either isStartOfDay(interval: Unit::Microsecond) or isStartOfDay(interval: Unit::Second)\n". 'And you can now use any custom interval as precision, such as isStartOfDay(interval: "15 minutes")', \E_USER_DEPRECATED, ); } if ($interval === null && !\is_bool($checkMicroseconds)) { $interval = $checkMicroseconds; } if ($interval !== null) { if ($interval instanceof Unit) { $interval = '1 '.$interval->value; } $date = $this->rawFormat('Y-m-d'); $time = $this->rawFormat('H:i:s.u'); $maximum = $this->avoidMutation()->startOfDay()->add($interval); $maximumDate = $maximum->rawFormat('Y-m-d'); if ($date === $maximumDate) { return $time < $maximum->rawFormat('H:i:s.u'); } return $maximumDate > $date; } /* @var CarbonInterface $this */ return $checkMicroseconds ? $this->rawFormat('H:i:s.u') === '00:00:00.000000' : $this->rawFormat('H:i:s') === '00:00:00'; } /** * Check if the instance is end of day. * * @example * ``` * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:58.999999')->isEndOfDay(); // false * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(true); // true * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(true); // false * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(true); // false * ``` * * @param bool $checkMicroseconds check time at microseconds precision * @param Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval if an interval is specified it will be used as precision * for instance with "15 minutes", it checks if current date-time * is in the last 15 minutes of the day, with Unit::Hour, it * checks if it's in the last hour of the day. */ public function isEndOfDay( Unit|DateInterval|Closure|CarbonConverterInterface|string|bool $checkMicroseconds = false, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { if ($checkMicroseconds === true) { @trigger_error( "Since 3.8.0, it's deprecated to use \$checkMicroseconds.\n". "It will be removed in 4.0.0.\n". "Instead, you should use either isEndOfDay(interval: Unit::Microsecond) or isEndOfDay(interval: Unit::Second)\n". 'And you can now use any custom interval as precision, such as isEndOfDay(interval: "15 minutes")', \E_USER_DEPRECATED, ); } if ($interval === null && !\is_bool($checkMicroseconds)) { $interval = $checkMicroseconds; } if ($interval !== null) { $date = $this->rawFormat('Y-m-d'); $time = $this->rawFormat('H:i:s.u'); $minimum = $this->avoidMutation() ->endOfDay() ->sub($interval instanceof Unit ? '1 '.$interval->value : $interval); $minimumDate = $minimum->rawFormat('Y-m-d'); if ($date === $minimumDate) { return $time > $minimum->rawFormat('H:i:s.u'); } return $minimumDate < $date; } /* @var CarbonInterface $this */ return $checkMicroseconds ? $this->rawFormat('H:i:s.u') === '23:59:59.999999' : $this->rawFormat('H:i:s') === '23:59:59'; } /** * Determines if the instance is start of week (first day by default but interval can be customized). * * @example * ``` * Carbon::parse('2024-08-31')->startOfWeek()->isStartOfWeek(); // true * Carbon::parse('2024-08-31')->isStartOfWeek(); // false * ``` */ public function isStartOfWeek( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, WeekDay|int|null $weekStartsAt = null, ): bool { return $this->isStartOfUnit(Unit::Week, $interval, $weekStartsAt); } /** * Determines if the instance is end of week (last day by default but interval can be customized). * * @example * ``` * Carbon::parse('2024-08-31')->endOfWeek()->isEndOfWeek(); // true * Carbon::parse('2024-08-31')->isEndOfWeek(); // false * ``` */ public function isEndOfWeek( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, WeekDay|int|null $weekEndsAt = null, ): bool { return $this->isEndOfUnit(Unit::Week, $interval, $weekEndsAt); } /** * Determines if the instance is start of month (first day by default but interval can be customized). */ public function isStartOfMonth( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Month, $interval); } /** * Determines if the instance is end of month (last day by default but interval can be customized). */ public function isEndOfMonth( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Month, $interval); } /** * Determines if the instance is start of quarter (first day by default but interval can be customized). */ public function isStartOfQuarter( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Quarter, $interval); } /** * Determines if the instance is end of quarter (last day by default but interval can be customized). */ public function isEndOfQuarter( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Quarter, $interval); } /** * Determines if the instance is start of year (first day by default but interval can be customized). */ public function isStartOfYear( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Year, $interval); } /** * Determines if the instance is end of year (last day by default but interval can be customized). */ public function isEndOfYear( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Year, $interval); } /** * Determines if the instance is start of decade (first day by default but interval can be customized). */ public function isStartOfDecade( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Decade, $interval); } /** * Determines if the instance is end of decade (last day by default but interval can be customized). */ public function isEndOfDecade( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Decade, $interval); } /** * Determines if the instance is start of century (first day by default but interval can be customized). */ public function isStartOfCentury( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Century, $interval); } /** * Determines if the instance is end of century (last day by default but interval can be customized). */ public function isEndOfCentury( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Century, $interval); } /** * Determines if the instance is start of millennium (first day by default but interval can be customized). */ public function isStartOfMillennium( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Millennium, $interval); } /** * Determines if the instance is end of millennium (last day by default but interval can be customized). */ public function isEndOfMillennium( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Millennium, $interval); } /** * Check if the instance is start of day / midnight. * * @example * ``` * Carbon::parse('2019-02-28 00:00:00')->isMidnight(); // true * Carbon::parse('2019-02-28 00:00:00.999999')->isMidnight(); // true * Carbon::parse('2019-02-28 00:00:01')->isMidnight(); // false * ``` */ public function isMidnight(): bool { return $this->isStartOfDay(); } /** * Check if the instance is midday. * * @example * ``` * Carbon::parse('2019-02-28 11:59:59.999999')->isMidday(); // false * Carbon::parse('2019-02-28 12:00:00')->isMidday(); // true * Carbon::parse('2019-02-28 12:00:00.999999')->isMidday(); // true * Carbon::parse('2019-02-28 12:00:01')->isMidday(); // false * ``` */ public function isMidday(): bool { /* @var CarbonInterface $this */ return $this->rawFormat('G:i:s') === static::$midDayAt.':00:00'; } /** * Checks if the (date)time string is in a given format. * * @example * ``` * Carbon::hasFormat('11:12:45', 'h:i:s'); // true * Carbon::hasFormat('13:12:45', 'h:i:s'); // false * ``` */ public static function hasFormat(string $date, string $format): bool { return FactoryImmutable::getInstance()->hasFormat($date, $format); } /** * Checks if the (date)time string is in a given format. * * @example * ``` * Carbon::hasFormatWithModifiers('31/08/2015', 'd#m#Y'); // true * Carbon::hasFormatWithModifiers('31/08/2015', 'm#d#Y'); // false * ``` * * @param string $date * @param string $format * * @return bool */ public static function hasFormatWithModifiers(?string $date, string $format): bool { return FactoryImmutable::getInstance()->hasFormatWithModifiers($date, $format); } /** * Checks if the (date)time string is in a given format and valid to create a * new instance. * * @example * ``` * Carbon::canBeCreatedFromFormat('11:12:45', 'h:i:s'); // true * Carbon::canBeCreatedFromFormat('13:12:45', 'h:i:s'); // false * ``` */ public static function canBeCreatedFromFormat(?string $date, string $format): bool { if ($date === null) { return false; } try { // Try to create a DateTime object. Throws an InvalidArgumentException if the provided time string // doesn't match the format in any way. if (!static::rawCreateFromFormat($format, $date)) { return false; } } catch (InvalidArgumentException) { return false; } return static::hasFormatWithModifiers($date, $format); } /** * Returns true if the current date matches the given string. * * @example * ``` * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2018')); // false * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('06-02')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06-02')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('Sunday')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('June')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:45')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:00')); // false * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12h')); // true * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3pm')); // true * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3am')); // false * ``` * * @param string $tester day name, month name, hour, date, etc. as string */ public function is(WeekDay|Month|string $tester): bool { if ($tester instanceof BackedEnum) { $tester = $tester->name; } $tester = trim($tester); if (preg_match('/^\d+$/', $tester)) { return $this->year === (int) $tester; } if (preg_match('/^(?:Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|September|Oct|October|Nov|November|Dec|December)$/i', $tester)) { return $this->isSameMonth( $this->transmitFactory(static fn () => static::parse("$tester 1st")), false, ); } if (preg_match('/^\d{3,}-\d{1,2}$/', $tester)) { return $this->isSameMonth( $this->transmitFactory(static fn () => static::parse($tester)), ); } if (preg_match('/^(\d{1,2})-(\d{1,2})$/', $tester, $match)) { return $this->month === (int) $match[1] && $this->day === (int) $match[2]; } $modifier = preg_replace('/(\d)h$/i', '$1:00', $tester); /* @var CarbonInterface $max */ $median = $this->transmitFactory(static fn () => static::parse('5555-06-15 12:30:30.555555')) ->modify($modifier); $current = $this->avoidMutation(); /* @var CarbonInterface $other */ $other = $this->avoidMutation()->modify($modifier); if ($current->eq($other)) { return true; } if (preg_match('/\d:\d{1,2}:\d{1,2}$/', $tester)) { return $current->startOfSecond()->eq($other); } if (preg_match('/\d:\d{1,2}$/', $tester)) { return $current->startOfMinute()->eq($other); } if (preg_match('/\d(?:h|am|pm)$/', $tester)) { return $current->startOfHour()->eq($other); } if (preg_match( '/^(?:january|february|march|april|may|june|july|august|september|october|november|december)(?:\s+\d+)?$/i', $tester, )) { return $current->startOfMonth()->eq($other->startOfMonth()); } $units = [ 'month' => [1, 'year'], 'day' => [1, 'month'], 'hour' => [0, 'day'], 'minute' => [0, 'hour'], 'second' => [0, 'minute'], 'microsecond' => [0, 'second'], ]; foreach ($units as $unit => [$minimum, $startUnit]) { if ($minimum === $median->$unit) { $current = $current->startOf($startUnit); break; } } return $current->eq($other); } /** * Returns true if the date was created using CarbonImmutable::startOfTime() * * @return bool */ public function isStartOfTime(): bool { return $this->startOfTime ?? false; } /** * Returns true if the date was created using CarbonImmutable::endOfTime() * * @return bool */ public function isEndOfTime(): bool { return $this->endOfTime ?? false; } }
PHP
{ "end_line": 813, "name": "isEndOfUnit", "signature": "public function isEndOfUnit(", "start_line": 792 }
{ "class_name": "Comparison", "class_signature": "trait Comparison", "namespace": "Carbon\\Traits" }
isStartOfDay
Carbon/src/Carbon/Traits/Comparison.php
public function isStartOfDay( Unit|DateInterval|Closure|CarbonConverterInterface|string|bool $checkMicroseconds = false, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { if ($checkMicroseconds === true) { @trigger_error( "Since 3.8.0, it's deprecated to use \$checkMicroseconds.\n". "It will be removed in 4.0.0.\n". "Instead, you should use either isStartOfDay(interval: Unit::Microsecond) or isStartOfDay(interval: Unit::Second)\n". 'And you can now use any custom interval as precision, such as isStartOfDay(interval: "15 minutes")', \E_USER_DEPRECATED, ); } if ($interval === null && !\is_bool($checkMicroseconds)) { $interval = $checkMicroseconds; } if ($interval !== null) { if ($interval instanceof Unit) { $interval = '1 '.$interval->value; } $date = $this->rawFormat('Y-m-d'); $time = $this->rawFormat('H:i:s.u'); $maximum = $this->avoidMutation()->startOfDay()->add($interval); $maximumDate = $maximum->rawFormat('Y-m-d'); if ($date === $maximumDate) { return $time < $maximum->rawFormat('H:i:s.u'); } return $maximumDate > $date; } /* @var CarbonInterface $this */ return $checkMicroseconds ? $this->rawFormat('H:i:s.u') === '00:00:00.000000' : $this->rawFormat('H:i:s') === '00:00:00'; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use BackedEnum; use BadMethodCallException; use Carbon\CarbonConverterInterface; use Carbon\CarbonInterface; use Carbon\Exceptions\BadComparisonUnitException; use Carbon\FactoryImmutable; use Carbon\Month; use Carbon\Unit; use Carbon\WeekDay; use Closure; use DateInterval; use DateTimeInterface; use InvalidArgumentException; /** * Trait Comparison. * * Comparison utils and testers. All the following methods return booleans. * nowWithSameTz * * Depends on the following methods: * * @method static resolveCarbon($date) * @method static copy() * @method static nowWithSameTz() * @method static static yesterday($timezone = null) * @method static static tomorrow($timezone = null) */ trait Comparison { protected bool $endOfTime = false; protected bool $startOfTime = false; /** * Determines if the instance is equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->eq(Carbon::parse('2018-07-25 12:45:16')); // true * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:17'); // false * ``` * * @see equalTo() */ public function eq(DateTimeInterface|string $date): bool { return $this->equalTo($date); } /** * Determines if the instance is equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->equalTo(Carbon::parse('2018-07-25 12:45:16')); // true * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:17'); // false * ``` */ public function equalTo(DateTimeInterface|string $date): bool { return $this == $this->resolveCarbon($date); } /** * Determines if the instance is not equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->ne(Carbon::parse('2018-07-25 12:45:16')); // false * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:17'); // true * ``` * * @see notEqualTo() */ public function ne(DateTimeInterface|string $date): bool { return $this->notEqualTo($date); } /** * Determines if the instance is not equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->notEqualTo(Carbon::parse('2018-07-25 12:45:16')); // false * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:17'); // true * ``` */ public function notEqualTo(DateTimeInterface|string $date): bool { return !$this->equalTo($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:17'); // false * ``` * * @see greaterThan() */ public function gt(DateTimeInterface|string $date): bool { return $this->greaterThan($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:17'); // false * ``` */ public function greaterThan(DateTimeInterface|string $date): bool { return $this > $this->resolveCarbon($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:17'); // false * ``` * * @see greaterThan() */ public function isAfter(DateTimeInterface|string $date): bool { return $this->greaterThan($date); } /** * Determines if the instance is greater (after) than or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:17'); // false * ``` * * @see greaterThanOrEqualTo() */ public function gte(DateTimeInterface|string $date): bool { return $this->greaterThanOrEqualTo($date); } /** * Determines if the instance is greater (after) than or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:17'); // false * ``` */ public function greaterThanOrEqualTo(DateTimeInterface|string $date): bool { return $this >= $this->resolveCarbon($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:17'); // true * ``` * * @see lessThan() */ public function lt(DateTimeInterface|string $date): bool { return $this->lessThan($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:17'); // true * ``` */ public function lessThan(DateTimeInterface|string $date): bool { return $this < $this->resolveCarbon($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:17'); // true * ``` * * @see lessThan() */ public function isBefore(DateTimeInterface|string $date): bool { return $this->lessThan($date); } /** * Determines if the instance is less (before) or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:17'); // true * ``` * * @see lessThanOrEqualTo() */ public function lte(DateTimeInterface|string $date): bool { return $this->lessThanOrEqualTo($date); } /** * Determines if the instance is less (before) or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:17'); // true * ``` */ public function lessThanOrEqualTo(DateTimeInterface|string $date): bool { return $this <= $this->resolveCarbon($date); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * Carbon::parse('2018-07-25')->between('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->between('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01'); // true * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01', false); // false * ``` * * @param bool $equal Indicates if an equal to comparison should be done */ public function between(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool { $date1 = $this->resolveCarbon($date1); $date2 = $this->resolveCarbon($date2); if ($date1->greaterThan($date2)) { [$date1, $date2] = [$date2, $date1]; } if ($equal) { return $this >= $date1 && $this <= $date2; } return $this > $date1 && $this < $date2; } /** * Determines if the instance is between two others, bounds included. * * @example * ``` * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->betweenIncluded('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-25', '2018-08-01'); // true * ``` */ public function betweenIncluded(DateTimeInterface|string $date1, DateTimeInterface|string $date2): bool { return $this->between($date1, $date2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->betweenExcluded('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-25', '2018-08-01'); // false * ``` */ public function betweenExcluded(DateTimeInterface|string $date1, DateTimeInterface|string $date2): bool { return $this->between($date1, $date2, false); } /** * Determines if the instance is between two others * * @example * ``` * Carbon::parse('2018-07-25')->isBetween('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->isBetween('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01'); // true * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01', false); // false * ``` * * @param bool $equal Indicates if an equal to comparison should be done */ public function isBetween(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool { return $this->between($date1, $date2, $equal); } /** * Determines if the instance is a weekday. * * @example * ``` * Carbon::parse('2019-07-14')->isWeekday(); // false * Carbon::parse('2019-07-15')->isWeekday(); // true * ``` */ public function isWeekday(): bool { return !$this->isWeekend(); } /** * Determines if the instance is a weekend day. * * @example * ``` * Carbon::parse('2019-07-14')->isWeekend(); // true * Carbon::parse('2019-07-15')->isWeekend(); // false * ``` */ public function isWeekend(): bool { return \in_array( $this->dayOfWeek, $this->transmitFactory(static fn () => static::getWeekendDays()), true, ); } /** * Determines if the instance is yesterday. * * @example * ``` * Carbon::yesterday()->isYesterday(); // true * Carbon::tomorrow()->isYesterday(); // false * ``` */ public function isYesterday(): bool { return $this->toDateString() === $this->transmitFactory( fn () => static::yesterday($this->getTimezone())->toDateString(), ); } /** * Determines if the instance is today. * * @example * ``` * Carbon::today()->isToday(); // true * Carbon::tomorrow()->isToday(); // false * ``` */ public function isToday(): bool { return $this->toDateString() === $this->nowWithSameTz()->toDateString(); } /** * Determines if the instance is tomorrow. * * @example * ``` * Carbon::tomorrow()->isTomorrow(); // true * Carbon::yesterday()->isTomorrow(); // false * ``` */ public function isTomorrow(): bool { return $this->toDateString() === $this->transmitFactory( fn () => static::tomorrow($this->getTimezone())->toDateString(), ); } /** * Determines if the instance is in the future, ie. greater (after) than now. * * @example * ``` * Carbon::now()->addHours(5)->isFuture(); // true * Carbon::now()->subHours(5)->isFuture(); // false * ``` */ public function isFuture(): bool { return $this->greaterThan($this->nowWithSameTz()); } /** * Determines if the instance is in the past, ie. less (before) than now. * * @example * ``` * Carbon::now()->subHours(5)->isPast(); // true * Carbon::now()->addHours(5)->isPast(); // false * ``` */ public function isPast(): bool { return $this->lessThan($this->nowWithSameTz()); } /** * Determines if the instance is now or in the future, ie. greater (after) than or equal to now. * * @example * ``` * Carbon::now()->isNowOrFuture(); // true * Carbon::now()->addHours(5)->isNowOrFuture(); // true * Carbon::now()->subHours(5)->isNowOrFuture(); // false * ``` */ public function isNowOrFuture(): bool { return $this->greaterThanOrEqualTo($this->nowWithSameTz()); } /** * Determines if the instance is now or in the past, ie. less (before) than or equal to now. * * @example * ``` * Carbon::now()->isNowOrPast(); // true * Carbon::now()->subHours(5)->isNowOrPast(); // true * Carbon::now()->addHours(5)->isNowOrPast(); // false * ``` */ public function isNowOrPast(): bool { return $this->lessThanOrEqualTo($this->nowWithSameTz()); } /** * Determines if the instance is a leap year. * * @example * ``` * Carbon::parse('2020-01-01')->isLeapYear(); // true * Carbon::parse('2019-01-01')->isLeapYear(); // false * ``` */ public function isLeapYear(): bool { return $this->rawFormat('L') === '1'; } /** * Determines if the instance is a long year (using calendar year). * * ⚠️ This method completely ignores month and day to use the numeric year number, * it's not correct if the exact date matters. For instance as `2019-12-30` is already * in the first week of the 2020 year, if you want to know from this date if ISO week * year 2020 is a long year, use `isLongIsoYear` instead. * * @example * ``` * Carbon::create(2015)->isLongYear(); // true * Carbon::create(2016)->isLongYear(); // false * ``` * * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates */ public function isLongYear(): bool { return static::create($this->year, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === static::WEEKS_PER_YEAR + 1; } /** * Determines if the instance is a long year (using ISO 8601 year). * * @example * ``` * Carbon::parse('2015-01-01')->isLongIsoYear(); // true * Carbon::parse('2016-01-01')->isLongIsoYear(); // true * Carbon::parse('2016-01-03')->isLongIsoYear(); // false * Carbon::parse('2019-12-29')->isLongIsoYear(); // false * Carbon::parse('2019-12-30')->isLongIsoYear(); // true * ``` * * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates */ public function isLongIsoYear(): bool { return static::create($this->isoWeekYear, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === 53; } /** * Compares the formatted values of the two dates. * * @example * ``` * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-12-13')); // true * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-06-14')); // false * ``` * * @param string $format date formats to compare. * @param DateTimeInterface|string $date instance to compare with or null to use current day. */ public function isSameAs(string $format, DateTimeInterface|string $date): bool { return $this->rawFormat($format) === $this->resolveCarbon($date)->rawFormat($format); } /** * Determines if the instance is in the current unit given. * * @example * ``` * Carbon::parse('2019-01-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // true * Carbon::parse('2018-12-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // false * ``` * * @param string $unit singular unit string * @param DateTimeInterface|string $date instance to compare with or null to use current day. * * @throws BadComparisonUnitException * * @return bool */ public function isSameUnit(string $unit, DateTimeInterface|string $date): bool { if ($unit === /* @call isSameUnit */ 'quarter') { $other = $this->resolveCarbon($date); return $other->year === $this->year && $other->quarter === $this->quarter; } $units = [ // @call isSameUnit 'year' => 'Y', // @call isSameUnit 'month' => 'Y-n', // @call isSameUnit 'week' => 'o-W', // @call isSameUnit 'day' => 'Y-m-d', // @call isSameUnit 'hour' => 'Y-m-d H', // @call isSameUnit 'minute' => 'Y-m-d H:i', // @call isSameUnit 'second' => 'Y-m-d H:i:s', // @call isSameUnit 'milli' => 'Y-m-d H:i:s.v', // @call isSameUnit 'millisecond' => 'Y-m-d H:i:s.v', // @call isSameUnit 'micro' => 'Y-m-d H:i:s.u', // @call isSameUnit 'microsecond' => 'Y-m-d H:i:s.u', ]; if (isset($units[$unit])) { return $this->isSameAs($units[$unit], $date); } if (isset($this->$unit)) { return $this->resolveCarbon($date)->$unit === $this->$unit; } if ($this->isLocalStrictModeEnabled()) { throw new BadComparisonUnitException($unit); } return false; } /** * Determines if the instance is in the current unit given. * * @example * ``` * Carbon::now()->isCurrentUnit('hour'); // true * Carbon::now()->subHours(2)->isCurrentUnit('hour'); // false * ``` * * @param string $unit The unit to test. * * @throws BadMethodCallException */ public function isCurrentUnit(string $unit): bool { return $this->{'isSame'.ucfirst($unit)}('now'); } /** * Checks if the passed in date is in the same quarter as the instance quarter (and year if needed). * * @example * ``` * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-03-01')); // true * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-04-01')); // false * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01')); // false * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01'), false); // true * ``` * * @param DateTimeInterface|string $date The instance to compare with or null to use current day. * @param bool $ofSameYear Check if it is the same month in the same year. * * @return bool */ public function isSameQuarter(DateTimeInterface|string $date, bool $ofSameYear = true): bool { $date = $this->resolveCarbon($date); return $this->quarter === $date->quarter && (!$ofSameYear || $this->isSameYear($date)); } /** * Checks if the passed in date is in the same month as the instance´s month. * * @example * ``` * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-01-01')); // true * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-02-01')); // false * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01')); // false * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01'), false); // true * ``` * * @param DateTimeInterface|string $date The instance to compare with or null to use the current date. * @param bool $ofSameYear Check if it is the same month in the same year. * * @return bool */ public function isSameMonth(DateTimeInterface|string $date, bool $ofSameYear = true): bool { return $this->isSameAs($ofSameYear ? 'Y-m' : 'm', $date); } /** * Checks if this day is a specific day of the week. * * @example * ``` * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::WEDNESDAY); // true * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::FRIDAY); // false * Carbon::parse('2019-07-17')->isDayOfWeek('Wednesday'); // true * Carbon::parse('2019-07-17')->isDayOfWeek('Friday'); // false * ``` * * @param int|string $dayOfWeek * * @return bool */ public function isDayOfWeek($dayOfWeek): bool { if (\is_string($dayOfWeek) && \defined($constant = static::class.'::'.strtoupper($dayOfWeek))) { $dayOfWeek = \constant($constant); } return $this->dayOfWeek === $dayOfWeek; } /** * Check if its the birthday. Compares the date/month values of the two dates. * * @example * ``` * Carbon::now()->subYears(5)->isBirthday(); // true * Carbon::now()->subYears(5)->subDay()->isBirthday(); // false * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-05')); // true * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-06')); // false * ``` * * @param DateTimeInterface|string|null $date The instance to compare with or null to use current day. * * @return bool */ public function isBirthday(DateTimeInterface|string|null $date = null): bool { return $this->isSameAs('md', $date ?? 'now'); } /** * Check if today is the last day of the Month * * @example * ``` * Carbon::parse('2019-02-28')->isLastOfMonth(); // true * Carbon::parse('2019-03-28')->isLastOfMonth(); // false * Carbon::parse('2019-03-30')->isLastOfMonth(); // false * Carbon::parse('2019-03-31')->isLastOfMonth(); // true * Carbon::parse('2019-04-30')->isLastOfMonth(); // true * ``` */ public function isLastOfMonth(): bool { return $this->day === $this->daysInMonth; } /** * Check if the instance is start of a given unit (tolerating a given interval). * * @example * ``` * // Check if a date-time is the first 15 minutes of the hour it's in * Carbon::parse('2019-02-28 20:13:00')->isStartOfUnit(Unit::Hour, '15 minutes'); // true * ``` */ public function isStartOfUnit( Unit $unit, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, mixed ...$params, ): bool { $interval ??= match ($unit) { Unit::Day, Unit::Hour, Unit::Minute, Unit::Second, Unit::Millisecond, Unit::Microsecond => Unit::Microsecond, default => Unit::Day, }; $startOfUnit = $this->avoidMutation()->startOf($unit, ...$params); $startOfUnitDateTime = $startOfUnit->rawFormat('Y-m-d H:i:s.u'); $maximumDateTime = $startOfUnit ->add($interval instanceof Unit ? '1 '.$interval->value : $interval) ->rawFormat('Y-m-d H:i:s.u'); if ($maximumDateTime < $startOfUnitDateTime) { return false; } return $this->rawFormat('Y-m-d H:i:s.u') < $maximumDateTime; } /** * Check if the instance is end of a given unit (tolerating a given interval). * * @example * ``` * // Check if a date-time is the last 15 minutes of the hour it's in * Carbon::parse('2019-02-28 20:13:00')->isEndOfUnit(Unit::Hour, '15 minutes'); // false * ``` */ public function isEndOfUnit( Unit $unit, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, mixed ...$params, ): bool { $interval ??= match ($unit) { Unit::Day, Unit::Hour, Unit::Minute, Unit::Second, Unit::Millisecond, Unit::Microsecond => Unit::Microsecond, default => Unit::Day, }; $endOfUnit = $this->avoidMutation()->endOf($unit, ...$params); $endOfUnitDateTime = $endOfUnit->rawFormat('Y-m-d H:i:s.u'); $minimumDateTime = $endOfUnit ->sub($interval instanceof Unit ? '1 '.$interval->value : $interval) ->rawFormat('Y-m-d H:i:s.u'); if ($minimumDateTime > $endOfUnitDateTime) { return false; } return $this->rawFormat('Y-m-d H:i:s.u') > $minimumDateTime; } /** * Determines if the instance is start of millisecond (first microsecond by default but interval can be customized). */ public function isStartOfMillisecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Millisecond, $interval); } /** * Determines if the instance is end of millisecond (last microsecond by default but interval can be customized). */ public function isEndOfMillisecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Millisecond, $interval); } /** * Determines if the instance is start of second (first microsecond by default but interval can be customized). */ public function isStartOfSecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Second, $interval); } /** * Determines if the instance is end of second (last microsecond by default but interval can be customized). */ public function isEndOfSecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Second, $interval); } /** * Determines if the instance is start of minute (first microsecond by default but interval can be customized). */ public function isStartOfMinute( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Minute, $interval); } /** * Determines if the instance is end of minute (last microsecond by default but interval can be customized). */ public function isEndOfMinute( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Minute, $interval); } /** * Determines if the instance is start of hour (first microsecond by default but interval can be customized). */ public function isStartOfHour( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Hour, $interval); } /** * Determines if the instance is end of hour (last microsecond by default but interval can be customized). */ public function isEndOfHour( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Hour, $interval); } /** * Check if the instance is start of day / midnight. * * @example * ``` * Carbon::parse('2019-02-28 00:00:00')->isStartOfDay(); // true * Carbon::parse('2019-02-28 00:00:00.999999')->isStartOfDay(); // true * Carbon::parse('2019-02-28 00:00:01')->isStartOfDay(); // false * Carbon::parse('2019-02-28 00:00:00.000000')->isStartOfDay(true); // true * Carbon::parse('2019-02-28 00:00:00.000012')->isStartOfDay(true); // false * ``` * * @param bool $checkMicroseconds check time at microseconds precision * @param Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval if an interval is specified it will be used as precision * for instance with "15 minutes", it checks if current date-time * is in the last 15 minutes of the day, with Unit::Hour, it * checks if it's in the last hour of the day. */ public function isStartOfDay( Unit|DateInterval|Closure|CarbonConverterInterface|string|bool $checkMicroseconds = false, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { if ($checkMicroseconds === true) { @trigger_error( "Since 3.8.0, it's deprecated to use \$checkMicroseconds.\n". "It will be removed in 4.0.0.\n". "Instead, you should use either isStartOfDay(interval: Unit::Microsecond) or isStartOfDay(interval: Unit::Second)\n". 'And you can now use any custom interval as precision, such as isStartOfDay(interval: "15 minutes")', \E_USER_DEPRECATED, ); } if ($interval === null && !\is_bool($checkMicroseconds)) { $interval = $checkMicroseconds; } if ($interval !== null) { if ($interval instanceof Unit) { $interval = '1 '.$interval->value; } $date = $this->rawFormat('Y-m-d'); $time = $this->rawFormat('H:i:s.u'); $maximum = $this->avoidMutation()->startOfDay()->add($interval); $maximumDate = $maximum->rawFormat('Y-m-d'); if ($date === $maximumDate) { return $time < $maximum->rawFormat('H:i:s.u'); } return $maximumDate > $date; } /* @var CarbonInterface $this */ return $checkMicroseconds ? $this->rawFormat('H:i:s.u') === '00:00:00.000000' : $this->rawFormat('H:i:s') === '00:00:00'; } /** * Check if the instance is end of day. * * @example * ``` * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:58.999999')->isEndOfDay(); // false * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(true); // true * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(true); // false * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(true); // false * ``` * * @param bool $checkMicroseconds check time at microseconds precision * @param Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval if an interval is specified it will be used as precision * for instance with "15 minutes", it checks if current date-time * is in the last 15 minutes of the day, with Unit::Hour, it * checks if it's in the last hour of the day. */ public function isEndOfDay( Unit|DateInterval|Closure|CarbonConverterInterface|string|bool $checkMicroseconds = false, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { if ($checkMicroseconds === true) { @trigger_error( "Since 3.8.0, it's deprecated to use \$checkMicroseconds.\n". "It will be removed in 4.0.0.\n". "Instead, you should use either isEndOfDay(interval: Unit::Microsecond) or isEndOfDay(interval: Unit::Second)\n". 'And you can now use any custom interval as precision, such as isEndOfDay(interval: "15 minutes")', \E_USER_DEPRECATED, ); } if ($interval === null && !\is_bool($checkMicroseconds)) { $interval = $checkMicroseconds; } if ($interval !== null) { $date = $this->rawFormat('Y-m-d'); $time = $this->rawFormat('H:i:s.u'); $minimum = $this->avoidMutation() ->endOfDay() ->sub($interval instanceof Unit ? '1 '.$interval->value : $interval); $minimumDate = $minimum->rawFormat('Y-m-d'); if ($date === $minimumDate) { return $time > $minimum->rawFormat('H:i:s.u'); } return $minimumDate < $date; } /* @var CarbonInterface $this */ return $checkMicroseconds ? $this->rawFormat('H:i:s.u') === '23:59:59.999999' : $this->rawFormat('H:i:s') === '23:59:59'; } /** * Determines if the instance is start of week (first day by default but interval can be customized). * * @example * ``` * Carbon::parse('2024-08-31')->startOfWeek()->isStartOfWeek(); // true * Carbon::parse('2024-08-31')->isStartOfWeek(); // false * ``` */ public function isStartOfWeek( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, WeekDay|int|null $weekStartsAt = null, ): bool { return $this->isStartOfUnit(Unit::Week, $interval, $weekStartsAt); } /** * Determines if the instance is end of week (last day by default but interval can be customized). * * @example * ``` * Carbon::parse('2024-08-31')->endOfWeek()->isEndOfWeek(); // true * Carbon::parse('2024-08-31')->isEndOfWeek(); // false * ``` */ public function isEndOfWeek( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, WeekDay|int|null $weekEndsAt = null, ): bool { return $this->isEndOfUnit(Unit::Week, $interval, $weekEndsAt); } /** * Determines if the instance is start of month (first day by default but interval can be customized). */ public function isStartOfMonth( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Month, $interval); } /** * Determines if the instance is end of month (last day by default but interval can be customized). */ public function isEndOfMonth( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Month, $interval); } /** * Determines if the instance is start of quarter (first day by default but interval can be customized). */ public function isStartOfQuarter( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Quarter, $interval); } /** * Determines if the instance is end of quarter (last day by default but interval can be customized). */ public function isEndOfQuarter( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Quarter, $interval); } /** * Determines if the instance is start of year (first day by default but interval can be customized). */ public function isStartOfYear( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Year, $interval); } /** * Determines if the instance is end of year (last day by default but interval can be customized). */ public function isEndOfYear( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Year, $interval); } /** * Determines if the instance is start of decade (first day by default but interval can be customized). */ public function isStartOfDecade( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Decade, $interval); } /** * Determines if the instance is end of decade (last day by default but interval can be customized). */ public function isEndOfDecade( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Decade, $interval); } /** * Determines if the instance is start of century (first day by default but interval can be customized). */ public function isStartOfCentury( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Century, $interval); } /** * Determines if the instance is end of century (last day by default but interval can be customized). */ public function isEndOfCentury( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Century, $interval); } /** * Determines if the instance is start of millennium (first day by default but interval can be customized). */ public function isStartOfMillennium( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Millennium, $interval); } /** * Determines if the instance is end of millennium (last day by default but interval can be customized). */ public function isEndOfMillennium( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Millennium, $interval); } /** * Check if the instance is start of day / midnight. * * @example * ``` * Carbon::parse('2019-02-28 00:00:00')->isMidnight(); // true * Carbon::parse('2019-02-28 00:00:00.999999')->isMidnight(); // true * Carbon::parse('2019-02-28 00:00:01')->isMidnight(); // false * ``` */ public function isMidnight(): bool { return $this->isStartOfDay(); } /** * Check if the instance is midday. * * @example * ``` * Carbon::parse('2019-02-28 11:59:59.999999')->isMidday(); // false * Carbon::parse('2019-02-28 12:00:00')->isMidday(); // true * Carbon::parse('2019-02-28 12:00:00.999999')->isMidday(); // true * Carbon::parse('2019-02-28 12:00:01')->isMidday(); // false * ``` */ public function isMidday(): bool { /* @var CarbonInterface $this */ return $this->rawFormat('G:i:s') === static::$midDayAt.':00:00'; } /** * Checks if the (date)time string is in a given format. * * @example * ``` * Carbon::hasFormat('11:12:45', 'h:i:s'); // true * Carbon::hasFormat('13:12:45', 'h:i:s'); // false * ``` */ public static function hasFormat(string $date, string $format): bool { return FactoryImmutable::getInstance()->hasFormat($date, $format); } /** * Checks if the (date)time string is in a given format. * * @example * ``` * Carbon::hasFormatWithModifiers('31/08/2015', 'd#m#Y'); // true * Carbon::hasFormatWithModifiers('31/08/2015', 'm#d#Y'); // false * ``` * * @param string $date * @param string $format * * @return bool */ public static function hasFormatWithModifiers(?string $date, string $format): bool { return FactoryImmutable::getInstance()->hasFormatWithModifiers($date, $format); } /** * Checks if the (date)time string is in a given format and valid to create a * new instance. * * @example * ``` * Carbon::canBeCreatedFromFormat('11:12:45', 'h:i:s'); // true * Carbon::canBeCreatedFromFormat('13:12:45', 'h:i:s'); // false * ``` */ public static function canBeCreatedFromFormat(?string $date, string $format): bool { if ($date === null) { return false; } try { // Try to create a DateTime object. Throws an InvalidArgumentException if the provided time string // doesn't match the format in any way. if (!static::rawCreateFromFormat($format, $date)) { return false; } } catch (InvalidArgumentException) { return false; } return static::hasFormatWithModifiers($date, $format); } /** * Returns true if the current date matches the given string. * * @example * ``` * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2018')); // false * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('06-02')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06-02')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('Sunday')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('June')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:45')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:00')); // false * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12h')); // true * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3pm')); // true * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3am')); // false * ``` * * @param string $tester day name, month name, hour, date, etc. as string */ public function is(WeekDay|Month|string $tester): bool { if ($tester instanceof BackedEnum) { $tester = $tester->name; } $tester = trim($tester); if (preg_match('/^\d+$/', $tester)) { return $this->year === (int) $tester; } if (preg_match('/^(?:Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|September|Oct|October|Nov|November|Dec|December)$/i', $tester)) { return $this->isSameMonth( $this->transmitFactory(static fn () => static::parse("$tester 1st")), false, ); } if (preg_match('/^\d{3,}-\d{1,2}$/', $tester)) { return $this->isSameMonth( $this->transmitFactory(static fn () => static::parse($tester)), ); } if (preg_match('/^(\d{1,2})-(\d{1,2})$/', $tester, $match)) { return $this->month === (int) $match[1] && $this->day === (int) $match[2]; } $modifier = preg_replace('/(\d)h$/i', '$1:00', $tester); /* @var CarbonInterface $max */ $median = $this->transmitFactory(static fn () => static::parse('5555-06-15 12:30:30.555555')) ->modify($modifier); $current = $this->avoidMutation(); /* @var CarbonInterface $other */ $other = $this->avoidMutation()->modify($modifier); if ($current->eq($other)) { return true; } if (preg_match('/\d:\d{1,2}:\d{1,2}$/', $tester)) { return $current->startOfSecond()->eq($other); } if (preg_match('/\d:\d{1,2}$/', $tester)) { return $current->startOfMinute()->eq($other); } if (preg_match('/\d(?:h|am|pm)$/', $tester)) { return $current->startOfHour()->eq($other); } if (preg_match( '/^(?:january|february|march|april|may|june|july|august|september|october|november|december)(?:\s+\d+)?$/i', $tester, )) { return $current->startOfMonth()->eq($other->startOfMonth()); } $units = [ 'month' => [1, 'year'], 'day' => [1, 'month'], 'hour' => [0, 'day'], 'minute' => [0, 'hour'], 'second' => [0, 'minute'], 'microsecond' => [0, 'second'], ]; foreach ($units as $unit => [$minimum, $startUnit]) { if ($minimum === $median->$unit) { $current = $current->startOf($startUnit); break; } } return $current->eq($other); } /** * Returns true if the date was created using CarbonImmutable::startOfTime() * * @return bool */ public function isStartOfTime(): bool { return $this->startOfTime ?? false; } /** * Returns true if the date was created using CarbonImmutable::endOfTime() * * @return bool */ public function isEndOfTime(): bool { return $this->endOfTime ?? false; } }
PHP
{ "end_line": 944, "name": "isStartOfDay", "signature": "public function isStartOfDay(", "start_line": 905 }
{ "class_name": "Comparison", "class_signature": "trait Comparison", "namespace": "Carbon\\Traits" }
isEndOfDay
Carbon/src/Carbon/Traits/Comparison.php
public function isEndOfDay( Unit|DateInterval|Closure|CarbonConverterInterface|string|bool $checkMicroseconds = false, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { if ($checkMicroseconds === true) { @trigger_error( "Since 3.8.0, it's deprecated to use \$checkMicroseconds.\n". "It will be removed in 4.0.0.\n". "Instead, you should use either isEndOfDay(interval: Unit::Microsecond) or isEndOfDay(interval: Unit::Second)\n". 'And you can now use any custom interval as precision, such as isEndOfDay(interval: "15 minutes")', \E_USER_DEPRECATED, ); } if ($interval === null && !\is_bool($checkMicroseconds)) { $interval = $checkMicroseconds; } if ($interval !== null) { $date = $this->rawFormat('Y-m-d'); $time = $this->rawFormat('H:i:s.u'); $minimum = $this->avoidMutation() ->endOfDay() ->sub($interval instanceof Unit ? '1 '.$interval->value : $interval); $minimumDate = $minimum->rawFormat('Y-m-d'); if ($date === $minimumDate) { return $time > $minimum->rawFormat('H:i:s.u'); } return $minimumDate < $date; } /* @var CarbonInterface $this */ return $checkMicroseconds ? $this->rawFormat('H:i:s.u') === '23:59:59.999999' : $this->rawFormat('H:i:s') === '23:59:59'; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use BackedEnum; use BadMethodCallException; use Carbon\CarbonConverterInterface; use Carbon\CarbonInterface; use Carbon\Exceptions\BadComparisonUnitException; use Carbon\FactoryImmutable; use Carbon\Month; use Carbon\Unit; use Carbon\WeekDay; use Closure; use DateInterval; use DateTimeInterface; use InvalidArgumentException; /** * Trait Comparison. * * Comparison utils and testers. All the following methods return booleans. * nowWithSameTz * * Depends on the following methods: * * @method static resolveCarbon($date) * @method static copy() * @method static nowWithSameTz() * @method static static yesterday($timezone = null) * @method static static tomorrow($timezone = null) */ trait Comparison { protected bool $endOfTime = false; protected bool $startOfTime = false; /** * Determines if the instance is equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->eq(Carbon::parse('2018-07-25 12:45:16')); // true * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:17'); // false * ``` * * @see equalTo() */ public function eq(DateTimeInterface|string $date): bool { return $this->equalTo($date); } /** * Determines if the instance is equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->equalTo(Carbon::parse('2018-07-25 12:45:16')); // true * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:17'); // false * ``` */ public function equalTo(DateTimeInterface|string $date): bool { return $this == $this->resolveCarbon($date); } /** * Determines if the instance is not equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->ne(Carbon::parse('2018-07-25 12:45:16')); // false * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:17'); // true * ``` * * @see notEqualTo() */ public function ne(DateTimeInterface|string $date): bool { return $this->notEqualTo($date); } /** * Determines if the instance is not equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->notEqualTo(Carbon::parse('2018-07-25 12:45:16')); // false * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:17'); // true * ``` */ public function notEqualTo(DateTimeInterface|string $date): bool { return !$this->equalTo($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:17'); // false * ``` * * @see greaterThan() */ public function gt(DateTimeInterface|string $date): bool { return $this->greaterThan($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:17'); // false * ``` */ public function greaterThan(DateTimeInterface|string $date): bool { return $this > $this->resolveCarbon($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:17'); // false * ``` * * @see greaterThan() */ public function isAfter(DateTimeInterface|string $date): bool { return $this->greaterThan($date); } /** * Determines if the instance is greater (after) than or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:17'); // false * ``` * * @see greaterThanOrEqualTo() */ public function gte(DateTimeInterface|string $date): bool { return $this->greaterThanOrEqualTo($date); } /** * Determines if the instance is greater (after) than or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:17'); // false * ``` */ public function greaterThanOrEqualTo(DateTimeInterface|string $date): bool { return $this >= $this->resolveCarbon($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:17'); // true * ``` * * @see lessThan() */ public function lt(DateTimeInterface|string $date): bool { return $this->lessThan($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:17'); // true * ``` */ public function lessThan(DateTimeInterface|string $date): bool { return $this < $this->resolveCarbon($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:17'); // true * ``` * * @see lessThan() */ public function isBefore(DateTimeInterface|string $date): bool { return $this->lessThan($date); } /** * Determines if the instance is less (before) or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:17'); // true * ``` * * @see lessThanOrEqualTo() */ public function lte(DateTimeInterface|string $date): bool { return $this->lessThanOrEqualTo($date); } /** * Determines if the instance is less (before) or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:17'); // true * ``` */ public function lessThanOrEqualTo(DateTimeInterface|string $date): bool { return $this <= $this->resolveCarbon($date); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * Carbon::parse('2018-07-25')->between('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->between('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01'); // true * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01', false); // false * ``` * * @param bool $equal Indicates if an equal to comparison should be done */ public function between(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool { $date1 = $this->resolveCarbon($date1); $date2 = $this->resolveCarbon($date2); if ($date1->greaterThan($date2)) { [$date1, $date2] = [$date2, $date1]; } if ($equal) { return $this >= $date1 && $this <= $date2; } return $this > $date1 && $this < $date2; } /** * Determines if the instance is between two others, bounds included. * * @example * ``` * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->betweenIncluded('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-25', '2018-08-01'); // true * ``` */ public function betweenIncluded(DateTimeInterface|string $date1, DateTimeInterface|string $date2): bool { return $this->between($date1, $date2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->betweenExcluded('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-25', '2018-08-01'); // false * ``` */ public function betweenExcluded(DateTimeInterface|string $date1, DateTimeInterface|string $date2): bool { return $this->between($date1, $date2, false); } /** * Determines if the instance is between two others * * @example * ``` * Carbon::parse('2018-07-25')->isBetween('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->isBetween('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01'); // true * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01', false); // false * ``` * * @param bool $equal Indicates if an equal to comparison should be done */ public function isBetween(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool { return $this->between($date1, $date2, $equal); } /** * Determines if the instance is a weekday. * * @example * ``` * Carbon::parse('2019-07-14')->isWeekday(); // false * Carbon::parse('2019-07-15')->isWeekday(); // true * ``` */ public function isWeekday(): bool { return !$this->isWeekend(); } /** * Determines if the instance is a weekend day. * * @example * ``` * Carbon::parse('2019-07-14')->isWeekend(); // true * Carbon::parse('2019-07-15')->isWeekend(); // false * ``` */ public function isWeekend(): bool { return \in_array( $this->dayOfWeek, $this->transmitFactory(static fn () => static::getWeekendDays()), true, ); } /** * Determines if the instance is yesterday. * * @example * ``` * Carbon::yesterday()->isYesterday(); // true * Carbon::tomorrow()->isYesterday(); // false * ``` */ public function isYesterday(): bool { return $this->toDateString() === $this->transmitFactory( fn () => static::yesterday($this->getTimezone())->toDateString(), ); } /** * Determines if the instance is today. * * @example * ``` * Carbon::today()->isToday(); // true * Carbon::tomorrow()->isToday(); // false * ``` */ public function isToday(): bool { return $this->toDateString() === $this->nowWithSameTz()->toDateString(); } /** * Determines if the instance is tomorrow. * * @example * ``` * Carbon::tomorrow()->isTomorrow(); // true * Carbon::yesterday()->isTomorrow(); // false * ``` */ public function isTomorrow(): bool { return $this->toDateString() === $this->transmitFactory( fn () => static::tomorrow($this->getTimezone())->toDateString(), ); } /** * Determines if the instance is in the future, ie. greater (after) than now. * * @example * ``` * Carbon::now()->addHours(5)->isFuture(); // true * Carbon::now()->subHours(5)->isFuture(); // false * ``` */ public function isFuture(): bool { return $this->greaterThan($this->nowWithSameTz()); } /** * Determines if the instance is in the past, ie. less (before) than now. * * @example * ``` * Carbon::now()->subHours(5)->isPast(); // true * Carbon::now()->addHours(5)->isPast(); // false * ``` */ public function isPast(): bool { return $this->lessThan($this->nowWithSameTz()); } /** * Determines if the instance is now or in the future, ie. greater (after) than or equal to now. * * @example * ``` * Carbon::now()->isNowOrFuture(); // true * Carbon::now()->addHours(5)->isNowOrFuture(); // true * Carbon::now()->subHours(5)->isNowOrFuture(); // false * ``` */ public function isNowOrFuture(): bool { return $this->greaterThanOrEqualTo($this->nowWithSameTz()); } /** * Determines if the instance is now or in the past, ie. less (before) than or equal to now. * * @example * ``` * Carbon::now()->isNowOrPast(); // true * Carbon::now()->subHours(5)->isNowOrPast(); // true * Carbon::now()->addHours(5)->isNowOrPast(); // false * ``` */ public function isNowOrPast(): bool { return $this->lessThanOrEqualTo($this->nowWithSameTz()); } /** * Determines if the instance is a leap year. * * @example * ``` * Carbon::parse('2020-01-01')->isLeapYear(); // true * Carbon::parse('2019-01-01')->isLeapYear(); // false * ``` */ public function isLeapYear(): bool { return $this->rawFormat('L') === '1'; } /** * Determines if the instance is a long year (using calendar year). * * ⚠️ This method completely ignores month and day to use the numeric year number, * it's not correct if the exact date matters. For instance as `2019-12-30` is already * in the first week of the 2020 year, if you want to know from this date if ISO week * year 2020 is a long year, use `isLongIsoYear` instead. * * @example * ``` * Carbon::create(2015)->isLongYear(); // true * Carbon::create(2016)->isLongYear(); // false * ``` * * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates */ public function isLongYear(): bool { return static::create($this->year, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === static::WEEKS_PER_YEAR + 1; } /** * Determines if the instance is a long year (using ISO 8601 year). * * @example * ``` * Carbon::parse('2015-01-01')->isLongIsoYear(); // true * Carbon::parse('2016-01-01')->isLongIsoYear(); // true * Carbon::parse('2016-01-03')->isLongIsoYear(); // false * Carbon::parse('2019-12-29')->isLongIsoYear(); // false * Carbon::parse('2019-12-30')->isLongIsoYear(); // true * ``` * * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates */ public function isLongIsoYear(): bool { return static::create($this->isoWeekYear, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === 53; } /** * Compares the formatted values of the two dates. * * @example * ``` * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-12-13')); // true * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-06-14')); // false * ``` * * @param string $format date formats to compare. * @param DateTimeInterface|string $date instance to compare with or null to use current day. */ public function isSameAs(string $format, DateTimeInterface|string $date): bool { return $this->rawFormat($format) === $this->resolveCarbon($date)->rawFormat($format); } /** * Determines if the instance is in the current unit given. * * @example * ``` * Carbon::parse('2019-01-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // true * Carbon::parse('2018-12-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // false * ``` * * @param string $unit singular unit string * @param DateTimeInterface|string $date instance to compare with or null to use current day. * * @throws BadComparisonUnitException * * @return bool */ public function isSameUnit(string $unit, DateTimeInterface|string $date): bool { if ($unit === /* @call isSameUnit */ 'quarter') { $other = $this->resolveCarbon($date); return $other->year === $this->year && $other->quarter === $this->quarter; } $units = [ // @call isSameUnit 'year' => 'Y', // @call isSameUnit 'month' => 'Y-n', // @call isSameUnit 'week' => 'o-W', // @call isSameUnit 'day' => 'Y-m-d', // @call isSameUnit 'hour' => 'Y-m-d H', // @call isSameUnit 'minute' => 'Y-m-d H:i', // @call isSameUnit 'second' => 'Y-m-d H:i:s', // @call isSameUnit 'milli' => 'Y-m-d H:i:s.v', // @call isSameUnit 'millisecond' => 'Y-m-d H:i:s.v', // @call isSameUnit 'micro' => 'Y-m-d H:i:s.u', // @call isSameUnit 'microsecond' => 'Y-m-d H:i:s.u', ]; if (isset($units[$unit])) { return $this->isSameAs($units[$unit], $date); } if (isset($this->$unit)) { return $this->resolveCarbon($date)->$unit === $this->$unit; } if ($this->isLocalStrictModeEnabled()) { throw new BadComparisonUnitException($unit); } return false; } /** * Determines if the instance is in the current unit given. * * @example * ``` * Carbon::now()->isCurrentUnit('hour'); // true * Carbon::now()->subHours(2)->isCurrentUnit('hour'); // false * ``` * * @param string $unit The unit to test. * * @throws BadMethodCallException */ public function isCurrentUnit(string $unit): bool { return $this->{'isSame'.ucfirst($unit)}('now'); } /** * Checks if the passed in date is in the same quarter as the instance quarter (and year if needed). * * @example * ``` * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-03-01')); // true * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-04-01')); // false * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01')); // false * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01'), false); // true * ``` * * @param DateTimeInterface|string $date The instance to compare with or null to use current day. * @param bool $ofSameYear Check if it is the same month in the same year. * * @return bool */ public function isSameQuarter(DateTimeInterface|string $date, bool $ofSameYear = true): bool { $date = $this->resolveCarbon($date); return $this->quarter === $date->quarter && (!$ofSameYear || $this->isSameYear($date)); } /** * Checks if the passed in date is in the same month as the instance´s month. * * @example * ``` * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-01-01')); // true * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-02-01')); // false * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01')); // false * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01'), false); // true * ``` * * @param DateTimeInterface|string $date The instance to compare with or null to use the current date. * @param bool $ofSameYear Check if it is the same month in the same year. * * @return bool */ public function isSameMonth(DateTimeInterface|string $date, bool $ofSameYear = true): bool { return $this->isSameAs($ofSameYear ? 'Y-m' : 'm', $date); } /** * Checks if this day is a specific day of the week. * * @example * ``` * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::WEDNESDAY); // true * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::FRIDAY); // false * Carbon::parse('2019-07-17')->isDayOfWeek('Wednesday'); // true * Carbon::parse('2019-07-17')->isDayOfWeek('Friday'); // false * ``` * * @param int|string $dayOfWeek * * @return bool */ public function isDayOfWeek($dayOfWeek): bool { if (\is_string($dayOfWeek) && \defined($constant = static::class.'::'.strtoupper($dayOfWeek))) { $dayOfWeek = \constant($constant); } return $this->dayOfWeek === $dayOfWeek; } /** * Check if its the birthday. Compares the date/month values of the two dates. * * @example * ``` * Carbon::now()->subYears(5)->isBirthday(); // true * Carbon::now()->subYears(5)->subDay()->isBirthday(); // false * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-05')); // true * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-06')); // false * ``` * * @param DateTimeInterface|string|null $date The instance to compare with or null to use current day. * * @return bool */ public function isBirthday(DateTimeInterface|string|null $date = null): bool { return $this->isSameAs('md', $date ?? 'now'); } /** * Check if today is the last day of the Month * * @example * ``` * Carbon::parse('2019-02-28')->isLastOfMonth(); // true * Carbon::parse('2019-03-28')->isLastOfMonth(); // false * Carbon::parse('2019-03-30')->isLastOfMonth(); // false * Carbon::parse('2019-03-31')->isLastOfMonth(); // true * Carbon::parse('2019-04-30')->isLastOfMonth(); // true * ``` */ public function isLastOfMonth(): bool { return $this->day === $this->daysInMonth; } /** * Check if the instance is start of a given unit (tolerating a given interval). * * @example * ``` * // Check if a date-time is the first 15 minutes of the hour it's in * Carbon::parse('2019-02-28 20:13:00')->isStartOfUnit(Unit::Hour, '15 minutes'); // true * ``` */ public function isStartOfUnit( Unit $unit, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, mixed ...$params, ): bool { $interval ??= match ($unit) { Unit::Day, Unit::Hour, Unit::Minute, Unit::Second, Unit::Millisecond, Unit::Microsecond => Unit::Microsecond, default => Unit::Day, }; $startOfUnit = $this->avoidMutation()->startOf($unit, ...$params); $startOfUnitDateTime = $startOfUnit->rawFormat('Y-m-d H:i:s.u'); $maximumDateTime = $startOfUnit ->add($interval instanceof Unit ? '1 '.$interval->value : $interval) ->rawFormat('Y-m-d H:i:s.u'); if ($maximumDateTime < $startOfUnitDateTime) { return false; } return $this->rawFormat('Y-m-d H:i:s.u') < $maximumDateTime; } /** * Check if the instance is end of a given unit (tolerating a given interval). * * @example * ``` * // Check if a date-time is the last 15 minutes of the hour it's in * Carbon::parse('2019-02-28 20:13:00')->isEndOfUnit(Unit::Hour, '15 minutes'); // false * ``` */ public function isEndOfUnit( Unit $unit, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, mixed ...$params, ): bool { $interval ??= match ($unit) { Unit::Day, Unit::Hour, Unit::Minute, Unit::Second, Unit::Millisecond, Unit::Microsecond => Unit::Microsecond, default => Unit::Day, }; $endOfUnit = $this->avoidMutation()->endOf($unit, ...$params); $endOfUnitDateTime = $endOfUnit->rawFormat('Y-m-d H:i:s.u'); $minimumDateTime = $endOfUnit ->sub($interval instanceof Unit ? '1 '.$interval->value : $interval) ->rawFormat('Y-m-d H:i:s.u'); if ($minimumDateTime > $endOfUnitDateTime) { return false; } return $this->rawFormat('Y-m-d H:i:s.u') > $minimumDateTime; } /** * Determines if the instance is start of millisecond (first microsecond by default but interval can be customized). */ public function isStartOfMillisecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Millisecond, $interval); } /** * Determines if the instance is end of millisecond (last microsecond by default but interval can be customized). */ public function isEndOfMillisecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Millisecond, $interval); } /** * Determines if the instance is start of second (first microsecond by default but interval can be customized). */ public function isStartOfSecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Second, $interval); } /** * Determines if the instance is end of second (last microsecond by default but interval can be customized). */ public function isEndOfSecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Second, $interval); } /** * Determines if the instance is start of minute (first microsecond by default but interval can be customized). */ public function isStartOfMinute( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Minute, $interval); } /** * Determines if the instance is end of minute (last microsecond by default but interval can be customized). */ public function isEndOfMinute( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Minute, $interval); } /** * Determines if the instance is start of hour (first microsecond by default but interval can be customized). */ public function isStartOfHour( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Hour, $interval); } /** * Determines if the instance is end of hour (last microsecond by default but interval can be customized). */ public function isEndOfHour( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Hour, $interval); } /** * Check if the instance is start of day / midnight. * * @example * ``` * Carbon::parse('2019-02-28 00:00:00')->isStartOfDay(); // true * Carbon::parse('2019-02-28 00:00:00.999999')->isStartOfDay(); // true * Carbon::parse('2019-02-28 00:00:01')->isStartOfDay(); // false * Carbon::parse('2019-02-28 00:00:00.000000')->isStartOfDay(true); // true * Carbon::parse('2019-02-28 00:00:00.000012')->isStartOfDay(true); // false * ``` * * @param bool $checkMicroseconds check time at microseconds precision * @param Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval if an interval is specified it will be used as precision * for instance with "15 minutes", it checks if current date-time * is in the last 15 minutes of the day, with Unit::Hour, it * checks if it's in the last hour of the day. */ public function isStartOfDay( Unit|DateInterval|Closure|CarbonConverterInterface|string|bool $checkMicroseconds = false, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { if ($checkMicroseconds === true) { @trigger_error( "Since 3.8.0, it's deprecated to use \$checkMicroseconds.\n". "It will be removed in 4.0.0.\n". "Instead, you should use either isStartOfDay(interval: Unit::Microsecond) or isStartOfDay(interval: Unit::Second)\n". 'And you can now use any custom interval as precision, such as isStartOfDay(interval: "15 minutes")', \E_USER_DEPRECATED, ); } if ($interval === null && !\is_bool($checkMicroseconds)) { $interval = $checkMicroseconds; } if ($interval !== null) { if ($interval instanceof Unit) { $interval = '1 '.$interval->value; } $date = $this->rawFormat('Y-m-d'); $time = $this->rawFormat('H:i:s.u'); $maximum = $this->avoidMutation()->startOfDay()->add($interval); $maximumDate = $maximum->rawFormat('Y-m-d'); if ($date === $maximumDate) { return $time < $maximum->rawFormat('H:i:s.u'); } return $maximumDate > $date; } /* @var CarbonInterface $this */ return $checkMicroseconds ? $this->rawFormat('H:i:s.u') === '00:00:00.000000' : $this->rawFormat('H:i:s') === '00:00:00'; } /** * Check if the instance is end of day. * * @example * ``` * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:58.999999')->isEndOfDay(); // false * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(true); // true * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(true); // false * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(true); // false * ``` * * @param bool $checkMicroseconds check time at microseconds precision * @param Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval if an interval is specified it will be used as precision * for instance with "15 minutes", it checks if current date-time * is in the last 15 minutes of the day, with Unit::Hour, it * checks if it's in the last hour of the day. */ public function isEndOfDay( Unit|DateInterval|Closure|CarbonConverterInterface|string|bool $checkMicroseconds = false, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { if ($checkMicroseconds === true) { @trigger_error( "Since 3.8.0, it's deprecated to use \$checkMicroseconds.\n". "It will be removed in 4.0.0.\n". "Instead, you should use either isEndOfDay(interval: Unit::Microsecond) or isEndOfDay(interval: Unit::Second)\n". 'And you can now use any custom interval as precision, such as isEndOfDay(interval: "15 minutes")', \E_USER_DEPRECATED, ); } if ($interval === null && !\is_bool($checkMicroseconds)) { $interval = $checkMicroseconds; } if ($interval !== null) { $date = $this->rawFormat('Y-m-d'); $time = $this->rawFormat('H:i:s.u'); $minimum = $this->avoidMutation() ->endOfDay() ->sub($interval instanceof Unit ? '1 '.$interval->value : $interval); $minimumDate = $minimum->rawFormat('Y-m-d'); if ($date === $minimumDate) { return $time > $minimum->rawFormat('H:i:s.u'); } return $minimumDate < $date; } /* @var CarbonInterface $this */ return $checkMicroseconds ? $this->rawFormat('H:i:s.u') === '23:59:59.999999' : $this->rawFormat('H:i:s') === '23:59:59'; } /** * Determines if the instance is start of week (first day by default but interval can be customized). * * @example * ``` * Carbon::parse('2024-08-31')->startOfWeek()->isStartOfWeek(); // true * Carbon::parse('2024-08-31')->isStartOfWeek(); // false * ``` */ public function isStartOfWeek( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, WeekDay|int|null $weekStartsAt = null, ): bool { return $this->isStartOfUnit(Unit::Week, $interval, $weekStartsAt); } /** * Determines if the instance is end of week (last day by default but interval can be customized). * * @example * ``` * Carbon::parse('2024-08-31')->endOfWeek()->isEndOfWeek(); // true * Carbon::parse('2024-08-31')->isEndOfWeek(); // false * ``` */ public function isEndOfWeek( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, WeekDay|int|null $weekEndsAt = null, ): bool { return $this->isEndOfUnit(Unit::Week, $interval, $weekEndsAt); } /** * Determines if the instance is start of month (first day by default but interval can be customized). */ public function isStartOfMonth( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Month, $interval); } /** * Determines if the instance is end of month (last day by default but interval can be customized). */ public function isEndOfMonth( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Month, $interval); } /** * Determines if the instance is start of quarter (first day by default but interval can be customized). */ public function isStartOfQuarter( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Quarter, $interval); } /** * Determines if the instance is end of quarter (last day by default but interval can be customized). */ public function isEndOfQuarter( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Quarter, $interval); } /** * Determines if the instance is start of year (first day by default but interval can be customized). */ public function isStartOfYear( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Year, $interval); } /** * Determines if the instance is end of year (last day by default but interval can be customized). */ public function isEndOfYear( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Year, $interval); } /** * Determines if the instance is start of decade (first day by default but interval can be customized). */ public function isStartOfDecade( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Decade, $interval); } /** * Determines if the instance is end of decade (last day by default but interval can be customized). */ public function isEndOfDecade( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Decade, $interval); } /** * Determines if the instance is start of century (first day by default but interval can be customized). */ public function isStartOfCentury( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Century, $interval); } /** * Determines if the instance is end of century (last day by default but interval can be customized). */ public function isEndOfCentury( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Century, $interval); } /** * Determines if the instance is start of millennium (first day by default but interval can be customized). */ public function isStartOfMillennium( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Millennium, $interval); } /** * Determines if the instance is end of millennium (last day by default but interval can be customized). */ public function isEndOfMillennium( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Millennium, $interval); } /** * Check if the instance is start of day / midnight. * * @example * ``` * Carbon::parse('2019-02-28 00:00:00')->isMidnight(); // true * Carbon::parse('2019-02-28 00:00:00.999999')->isMidnight(); // true * Carbon::parse('2019-02-28 00:00:01')->isMidnight(); // false * ``` */ public function isMidnight(): bool { return $this->isStartOfDay(); } /** * Check if the instance is midday. * * @example * ``` * Carbon::parse('2019-02-28 11:59:59.999999')->isMidday(); // false * Carbon::parse('2019-02-28 12:00:00')->isMidday(); // true * Carbon::parse('2019-02-28 12:00:00.999999')->isMidday(); // true * Carbon::parse('2019-02-28 12:00:01')->isMidday(); // false * ``` */ public function isMidday(): bool { /* @var CarbonInterface $this */ return $this->rawFormat('G:i:s') === static::$midDayAt.':00:00'; } /** * Checks if the (date)time string is in a given format. * * @example * ``` * Carbon::hasFormat('11:12:45', 'h:i:s'); // true * Carbon::hasFormat('13:12:45', 'h:i:s'); // false * ``` */ public static function hasFormat(string $date, string $format): bool { return FactoryImmutable::getInstance()->hasFormat($date, $format); } /** * Checks if the (date)time string is in a given format. * * @example * ``` * Carbon::hasFormatWithModifiers('31/08/2015', 'd#m#Y'); // true * Carbon::hasFormatWithModifiers('31/08/2015', 'm#d#Y'); // false * ``` * * @param string $date * @param string $format * * @return bool */ public static function hasFormatWithModifiers(?string $date, string $format): bool { return FactoryImmutable::getInstance()->hasFormatWithModifiers($date, $format); } /** * Checks if the (date)time string is in a given format and valid to create a * new instance. * * @example * ``` * Carbon::canBeCreatedFromFormat('11:12:45', 'h:i:s'); // true * Carbon::canBeCreatedFromFormat('13:12:45', 'h:i:s'); // false * ``` */ public static function canBeCreatedFromFormat(?string $date, string $format): bool { if ($date === null) { return false; } try { // Try to create a DateTime object. Throws an InvalidArgumentException if the provided time string // doesn't match the format in any way. if (!static::rawCreateFromFormat($format, $date)) { return false; } } catch (InvalidArgumentException) { return false; } return static::hasFormatWithModifiers($date, $format); } /** * Returns true if the current date matches the given string. * * @example * ``` * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2018')); // false * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('06-02')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06-02')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('Sunday')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('June')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:45')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:00')); // false * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12h')); // true * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3pm')); // true * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3am')); // false * ``` * * @param string $tester day name, month name, hour, date, etc. as string */ public function is(WeekDay|Month|string $tester): bool { if ($tester instanceof BackedEnum) { $tester = $tester->name; } $tester = trim($tester); if (preg_match('/^\d+$/', $tester)) { return $this->year === (int) $tester; } if (preg_match('/^(?:Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|September|Oct|October|Nov|November|Dec|December)$/i', $tester)) { return $this->isSameMonth( $this->transmitFactory(static fn () => static::parse("$tester 1st")), false, ); } if (preg_match('/^\d{3,}-\d{1,2}$/', $tester)) { return $this->isSameMonth( $this->transmitFactory(static fn () => static::parse($tester)), ); } if (preg_match('/^(\d{1,2})-(\d{1,2})$/', $tester, $match)) { return $this->month === (int) $match[1] && $this->day === (int) $match[2]; } $modifier = preg_replace('/(\d)h$/i', '$1:00', $tester); /* @var CarbonInterface $max */ $median = $this->transmitFactory(static fn () => static::parse('5555-06-15 12:30:30.555555')) ->modify($modifier); $current = $this->avoidMutation(); /* @var CarbonInterface $other */ $other = $this->avoidMutation()->modify($modifier); if ($current->eq($other)) { return true; } if (preg_match('/\d:\d{1,2}:\d{1,2}$/', $tester)) { return $current->startOfSecond()->eq($other); } if (preg_match('/\d:\d{1,2}$/', $tester)) { return $current->startOfMinute()->eq($other); } if (preg_match('/\d(?:h|am|pm)$/', $tester)) { return $current->startOfHour()->eq($other); } if (preg_match( '/^(?:january|february|march|april|may|june|july|august|september|october|november|december)(?:\s+\d+)?$/i', $tester, )) { return $current->startOfMonth()->eq($other->startOfMonth()); } $units = [ 'month' => [1, 'year'], 'day' => [1, 'month'], 'hour' => [0, 'day'], 'minute' => [0, 'hour'], 'second' => [0, 'minute'], 'microsecond' => [0, 'second'], ]; foreach ($units as $unit => [$minimum, $startUnit]) { if ($minimum === $median->$unit) { $current = $current->startOf($startUnit); break; } } return $current->eq($other); } /** * Returns true if the date was created using CarbonImmutable::startOfTime() * * @return bool */ public function isStartOfTime(): bool { return $this->startOfTime ?? false; } /** * Returns true if the date was created using CarbonImmutable::endOfTime() * * @return bool */ public function isEndOfTime(): bool { return $this->endOfTime ?? false; } }
PHP
{ "end_line": 1003, "name": "isEndOfDay", "signature": "public function isEndOfDay(", "start_line": 966 }
{ "class_name": "Comparison", "class_signature": "trait Comparison", "namespace": "Carbon\\Traits" }
canBeCreatedFromFormat
Carbon/src/Carbon/Traits/Comparison.php
public static function canBeCreatedFromFormat(?string $date, string $format): bool { if ($date === null) { return false; } try { // Try to create a DateTime object. Throws an InvalidArgumentException if the provided time string // doesn't match the format in any way. if (!static::rawCreateFromFormat($format, $date)) { return false; } } catch (InvalidArgumentException) { return false; } return static::hasFormatWithModifiers($date, $format); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use BackedEnum; use BadMethodCallException; use Carbon\CarbonConverterInterface; use Carbon\CarbonInterface; use Carbon\Exceptions\BadComparisonUnitException; use Carbon\FactoryImmutable; use Carbon\Month; use Carbon\Unit; use Carbon\WeekDay; use Closure; use DateInterval; use DateTimeInterface; use InvalidArgumentException; /** * Trait Comparison. * * Comparison utils and testers. All the following methods return booleans. * nowWithSameTz * * Depends on the following methods: * * @method static resolveCarbon($date) * @method static copy() * @method static nowWithSameTz() * @method static static yesterday($timezone = null) * @method static static tomorrow($timezone = null) */ trait Comparison { protected bool $endOfTime = false; protected bool $startOfTime = false; /** * Determines if the instance is equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->eq(Carbon::parse('2018-07-25 12:45:16')); // true * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:17'); // false * ``` * * @see equalTo() */ public function eq(DateTimeInterface|string $date): bool { return $this->equalTo($date); } /** * Determines if the instance is equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->equalTo(Carbon::parse('2018-07-25 12:45:16')); // true * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:17'); // false * ``` */ public function equalTo(DateTimeInterface|string $date): bool { return $this == $this->resolveCarbon($date); } /** * Determines if the instance is not equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->ne(Carbon::parse('2018-07-25 12:45:16')); // false * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:17'); // true * ``` * * @see notEqualTo() */ public function ne(DateTimeInterface|string $date): bool { return $this->notEqualTo($date); } /** * Determines if the instance is not equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->notEqualTo(Carbon::parse('2018-07-25 12:45:16')); // false * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:17'); // true * ``` */ public function notEqualTo(DateTimeInterface|string $date): bool { return !$this->equalTo($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:17'); // false * ``` * * @see greaterThan() */ public function gt(DateTimeInterface|string $date): bool { return $this->greaterThan($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:17'); // false * ``` */ public function greaterThan(DateTimeInterface|string $date): bool { return $this > $this->resolveCarbon($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:17'); // false * ``` * * @see greaterThan() */ public function isAfter(DateTimeInterface|string $date): bool { return $this->greaterThan($date); } /** * Determines if the instance is greater (after) than or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:17'); // false * ``` * * @see greaterThanOrEqualTo() */ public function gte(DateTimeInterface|string $date): bool { return $this->greaterThanOrEqualTo($date); } /** * Determines if the instance is greater (after) than or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:17'); // false * ``` */ public function greaterThanOrEqualTo(DateTimeInterface|string $date): bool { return $this >= $this->resolveCarbon($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:17'); // true * ``` * * @see lessThan() */ public function lt(DateTimeInterface|string $date): bool { return $this->lessThan($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:17'); // true * ``` */ public function lessThan(DateTimeInterface|string $date): bool { return $this < $this->resolveCarbon($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:17'); // true * ``` * * @see lessThan() */ public function isBefore(DateTimeInterface|string $date): bool { return $this->lessThan($date); } /** * Determines if the instance is less (before) or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:17'); // true * ``` * * @see lessThanOrEqualTo() */ public function lte(DateTimeInterface|string $date): bool { return $this->lessThanOrEqualTo($date); } /** * Determines if the instance is less (before) or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:17'); // true * ``` */ public function lessThanOrEqualTo(DateTimeInterface|string $date): bool { return $this <= $this->resolveCarbon($date); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * Carbon::parse('2018-07-25')->between('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->between('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01'); // true * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01', false); // false * ``` * * @param bool $equal Indicates if an equal to comparison should be done */ public function between(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool { $date1 = $this->resolveCarbon($date1); $date2 = $this->resolveCarbon($date2); if ($date1->greaterThan($date2)) { [$date1, $date2] = [$date2, $date1]; } if ($equal) { return $this >= $date1 && $this <= $date2; } return $this > $date1 && $this < $date2; } /** * Determines if the instance is between two others, bounds included. * * @example * ``` * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->betweenIncluded('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-25', '2018-08-01'); // true * ``` */ public function betweenIncluded(DateTimeInterface|string $date1, DateTimeInterface|string $date2): bool { return $this->between($date1, $date2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->betweenExcluded('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-25', '2018-08-01'); // false * ``` */ public function betweenExcluded(DateTimeInterface|string $date1, DateTimeInterface|string $date2): bool { return $this->between($date1, $date2, false); } /** * Determines if the instance is between two others * * @example * ``` * Carbon::parse('2018-07-25')->isBetween('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->isBetween('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01'); // true * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01', false); // false * ``` * * @param bool $equal Indicates if an equal to comparison should be done */ public function isBetween(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool { return $this->between($date1, $date2, $equal); } /** * Determines if the instance is a weekday. * * @example * ``` * Carbon::parse('2019-07-14')->isWeekday(); // false * Carbon::parse('2019-07-15')->isWeekday(); // true * ``` */ public function isWeekday(): bool { return !$this->isWeekend(); } /** * Determines if the instance is a weekend day. * * @example * ``` * Carbon::parse('2019-07-14')->isWeekend(); // true * Carbon::parse('2019-07-15')->isWeekend(); // false * ``` */ public function isWeekend(): bool { return \in_array( $this->dayOfWeek, $this->transmitFactory(static fn () => static::getWeekendDays()), true, ); } /** * Determines if the instance is yesterday. * * @example * ``` * Carbon::yesterday()->isYesterday(); // true * Carbon::tomorrow()->isYesterday(); // false * ``` */ public function isYesterday(): bool { return $this->toDateString() === $this->transmitFactory( fn () => static::yesterday($this->getTimezone())->toDateString(), ); } /** * Determines if the instance is today. * * @example * ``` * Carbon::today()->isToday(); // true * Carbon::tomorrow()->isToday(); // false * ``` */ public function isToday(): bool { return $this->toDateString() === $this->nowWithSameTz()->toDateString(); } /** * Determines if the instance is tomorrow. * * @example * ``` * Carbon::tomorrow()->isTomorrow(); // true * Carbon::yesterday()->isTomorrow(); // false * ``` */ public function isTomorrow(): bool { return $this->toDateString() === $this->transmitFactory( fn () => static::tomorrow($this->getTimezone())->toDateString(), ); } /** * Determines if the instance is in the future, ie. greater (after) than now. * * @example * ``` * Carbon::now()->addHours(5)->isFuture(); // true * Carbon::now()->subHours(5)->isFuture(); // false * ``` */ public function isFuture(): bool { return $this->greaterThan($this->nowWithSameTz()); } /** * Determines if the instance is in the past, ie. less (before) than now. * * @example * ``` * Carbon::now()->subHours(5)->isPast(); // true * Carbon::now()->addHours(5)->isPast(); // false * ``` */ public function isPast(): bool { return $this->lessThan($this->nowWithSameTz()); } /** * Determines if the instance is now or in the future, ie. greater (after) than or equal to now. * * @example * ``` * Carbon::now()->isNowOrFuture(); // true * Carbon::now()->addHours(5)->isNowOrFuture(); // true * Carbon::now()->subHours(5)->isNowOrFuture(); // false * ``` */ public function isNowOrFuture(): bool { return $this->greaterThanOrEqualTo($this->nowWithSameTz()); } /** * Determines if the instance is now or in the past, ie. less (before) than or equal to now. * * @example * ``` * Carbon::now()->isNowOrPast(); // true * Carbon::now()->subHours(5)->isNowOrPast(); // true * Carbon::now()->addHours(5)->isNowOrPast(); // false * ``` */ public function isNowOrPast(): bool { return $this->lessThanOrEqualTo($this->nowWithSameTz()); } /** * Determines if the instance is a leap year. * * @example * ``` * Carbon::parse('2020-01-01')->isLeapYear(); // true * Carbon::parse('2019-01-01')->isLeapYear(); // false * ``` */ public function isLeapYear(): bool { return $this->rawFormat('L') === '1'; } /** * Determines if the instance is a long year (using calendar year). * * ⚠️ This method completely ignores month and day to use the numeric year number, * it's not correct if the exact date matters. For instance as `2019-12-30` is already * in the first week of the 2020 year, if you want to know from this date if ISO week * year 2020 is a long year, use `isLongIsoYear` instead. * * @example * ``` * Carbon::create(2015)->isLongYear(); // true * Carbon::create(2016)->isLongYear(); // false * ``` * * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates */ public function isLongYear(): bool { return static::create($this->year, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === static::WEEKS_PER_YEAR + 1; } /** * Determines if the instance is a long year (using ISO 8601 year). * * @example * ``` * Carbon::parse('2015-01-01')->isLongIsoYear(); // true * Carbon::parse('2016-01-01')->isLongIsoYear(); // true * Carbon::parse('2016-01-03')->isLongIsoYear(); // false * Carbon::parse('2019-12-29')->isLongIsoYear(); // false * Carbon::parse('2019-12-30')->isLongIsoYear(); // true * ``` * * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates */ public function isLongIsoYear(): bool { return static::create($this->isoWeekYear, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === 53; } /** * Compares the formatted values of the two dates. * * @example * ``` * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-12-13')); // true * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-06-14')); // false * ``` * * @param string $format date formats to compare. * @param DateTimeInterface|string $date instance to compare with or null to use current day. */ public function isSameAs(string $format, DateTimeInterface|string $date): bool { return $this->rawFormat($format) === $this->resolveCarbon($date)->rawFormat($format); } /** * Determines if the instance is in the current unit given. * * @example * ``` * Carbon::parse('2019-01-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // true * Carbon::parse('2018-12-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // false * ``` * * @param string $unit singular unit string * @param DateTimeInterface|string $date instance to compare with or null to use current day. * * @throws BadComparisonUnitException * * @return bool */ public function isSameUnit(string $unit, DateTimeInterface|string $date): bool { if ($unit === /* @call isSameUnit */ 'quarter') { $other = $this->resolveCarbon($date); return $other->year === $this->year && $other->quarter === $this->quarter; } $units = [ // @call isSameUnit 'year' => 'Y', // @call isSameUnit 'month' => 'Y-n', // @call isSameUnit 'week' => 'o-W', // @call isSameUnit 'day' => 'Y-m-d', // @call isSameUnit 'hour' => 'Y-m-d H', // @call isSameUnit 'minute' => 'Y-m-d H:i', // @call isSameUnit 'second' => 'Y-m-d H:i:s', // @call isSameUnit 'milli' => 'Y-m-d H:i:s.v', // @call isSameUnit 'millisecond' => 'Y-m-d H:i:s.v', // @call isSameUnit 'micro' => 'Y-m-d H:i:s.u', // @call isSameUnit 'microsecond' => 'Y-m-d H:i:s.u', ]; if (isset($units[$unit])) { return $this->isSameAs($units[$unit], $date); } if (isset($this->$unit)) { return $this->resolveCarbon($date)->$unit === $this->$unit; } if ($this->isLocalStrictModeEnabled()) { throw new BadComparisonUnitException($unit); } return false; } /** * Determines if the instance is in the current unit given. * * @example * ``` * Carbon::now()->isCurrentUnit('hour'); // true * Carbon::now()->subHours(2)->isCurrentUnit('hour'); // false * ``` * * @param string $unit The unit to test. * * @throws BadMethodCallException */ public function isCurrentUnit(string $unit): bool { return $this->{'isSame'.ucfirst($unit)}('now'); } /** * Checks if the passed in date is in the same quarter as the instance quarter (and year if needed). * * @example * ``` * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-03-01')); // true * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-04-01')); // false * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01')); // false * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01'), false); // true * ``` * * @param DateTimeInterface|string $date The instance to compare with or null to use current day. * @param bool $ofSameYear Check if it is the same month in the same year. * * @return bool */ public function isSameQuarter(DateTimeInterface|string $date, bool $ofSameYear = true): bool { $date = $this->resolveCarbon($date); return $this->quarter === $date->quarter && (!$ofSameYear || $this->isSameYear($date)); } /** * Checks if the passed in date is in the same month as the instance´s month. * * @example * ``` * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-01-01')); // true * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-02-01')); // false * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01')); // false * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01'), false); // true * ``` * * @param DateTimeInterface|string $date The instance to compare with or null to use the current date. * @param bool $ofSameYear Check if it is the same month in the same year. * * @return bool */ public function isSameMonth(DateTimeInterface|string $date, bool $ofSameYear = true): bool { return $this->isSameAs($ofSameYear ? 'Y-m' : 'm', $date); } /** * Checks if this day is a specific day of the week. * * @example * ``` * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::WEDNESDAY); // true * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::FRIDAY); // false * Carbon::parse('2019-07-17')->isDayOfWeek('Wednesday'); // true * Carbon::parse('2019-07-17')->isDayOfWeek('Friday'); // false * ``` * * @param int|string $dayOfWeek * * @return bool */ public function isDayOfWeek($dayOfWeek): bool { if (\is_string($dayOfWeek) && \defined($constant = static::class.'::'.strtoupper($dayOfWeek))) { $dayOfWeek = \constant($constant); } return $this->dayOfWeek === $dayOfWeek; } /** * Check if its the birthday. Compares the date/month values of the two dates. * * @example * ``` * Carbon::now()->subYears(5)->isBirthday(); // true * Carbon::now()->subYears(5)->subDay()->isBirthday(); // false * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-05')); // true * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-06')); // false * ``` * * @param DateTimeInterface|string|null $date The instance to compare with or null to use current day. * * @return bool */ public function isBirthday(DateTimeInterface|string|null $date = null): bool { return $this->isSameAs('md', $date ?? 'now'); } /** * Check if today is the last day of the Month * * @example * ``` * Carbon::parse('2019-02-28')->isLastOfMonth(); // true * Carbon::parse('2019-03-28')->isLastOfMonth(); // false * Carbon::parse('2019-03-30')->isLastOfMonth(); // false * Carbon::parse('2019-03-31')->isLastOfMonth(); // true * Carbon::parse('2019-04-30')->isLastOfMonth(); // true * ``` */ public function isLastOfMonth(): bool { return $this->day === $this->daysInMonth; } /** * Check if the instance is start of a given unit (tolerating a given interval). * * @example * ``` * // Check if a date-time is the first 15 minutes of the hour it's in * Carbon::parse('2019-02-28 20:13:00')->isStartOfUnit(Unit::Hour, '15 minutes'); // true * ``` */ public function isStartOfUnit( Unit $unit, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, mixed ...$params, ): bool { $interval ??= match ($unit) { Unit::Day, Unit::Hour, Unit::Minute, Unit::Second, Unit::Millisecond, Unit::Microsecond => Unit::Microsecond, default => Unit::Day, }; $startOfUnit = $this->avoidMutation()->startOf($unit, ...$params); $startOfUnitDateTime = $startOfUnit->rawFormat('Y-m-d H:i:s.u'); $maximumDateTime = $startOfUnit ->add($interval instanceof Unit ? '1 '.$interval->value : $interval) ->rawFormat('Y-m-d H:i:s.u'); if ($maximumDateTime < $startOfUnitDateTime) { return false; } return $this->rawFormat('Y-m-d H:i:s.u') < $maximumDateTime; } /** * Check if the instance is end of a given unit (tolerating a given interval). * * @example * ``` * // Check if a date-time is the last 15 minutes of the hour it's in * Carbon::parse('2019-02-28 20:13:00')->isEndOfUnit(Unit::Hour, '15 minutes'); // false * ``` */ public function isEndOfUnit( Unit $unit, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, mixed ...$params, ): bool { $interval ??= match ($unit) { Unit::Day, Unit::Hour, Unit::Minute, Unit::Second, Unit::Millisecond, Unit::Microsecond => Unit::Microsecond, default => Unit::Day, }; $endOfUnit = $this->avoidMutation()->endOf($unit, ...$params); $endOfUnitDateTime = $endOfUnit->rawFormat('Y-m-d H:i:s.u'); $minimumDateTime = $endOfUnit ->sub($interval instanceof Unit ? '1 '.$interval->value : $interval) ->rawFormat('Y-m-d H:i:s.u'); if ($minimumDateTime > $endOfUnitDateTime) { return false; } return $this->rawFormat('Y-m-d H:i:s.u') > $minimumDateTime; } /** * Determines if the instance is start of millisecond (first microsecond by default but interval can be customized). */ public function isStartOfMillisecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Millisecond, $interval); } /** * Determines if the instance is end of millisecond (last microsecond by default but interval can be customized). */ public function isEndOfMillisecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Millisecond, $interval); } /** * Determines if the instance is start of second (first microsecond by default but interval can be customized). */ public function isStartOfSecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Second, $interval); } /** * Determines if the instance is end of second (last microsecond by default but interval can be customized). */ public function isEndOfSecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Second, $interval); } /** * Determines if the instance is start of minute (first microsecond by default but interval can be customized). */ public function isStartOfMinute( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Minute, $interval); } /** * Determines if the instance is end of minute (last microsecond by default but interval can be customized). */ public function isEndOfMinute( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Minute, $interval); } /** * Determines if the instance is start of hour (first microsecond by default but interval can be customized). */ public function isStartOfHour( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Hour, $interval); } /** * Determines if the instance is end of hour (last microsecond by default but interval can be customized). */ public function isEndOfHour( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Hour, $interval); } /** * Check if the instance is start of day / midnight. * * @example * ``` * Carbon::parse('2019-02-28 00:00:00')->isStartOfDay(); // true * Carbon::parse('2019-02-28 00:00:00.999999')->isStartOfDay(); // true * Carbon::parse('2019-02-28 00:00:01')->isStartOfDay(); // false * Carbon::parse('2019-02-28 00:00:00.000000')->isStartOfDay(true); // true * Carbon::parse('2019-02-28 00:00:00.000012')->isStartOfDay(true); // false * ``` * * @param bool $checkMicroseconds check time at microseconds precision * @param Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval if an interval is specified it will be used as precision * for instance with "15 minutes", it checks if current date-time * is in the last 15 minutes of the day, with Unit::Hour, it * checks if it's in the last hour of the day. */ public function isStartOfDay( Unit|DateInterval|Closure|CarbonConverterInterface|string|bool $checkMicroseconds = false, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { if ($checkMicroseconds === true) { @trigger_error( "Since 3.8.0, it's deprecated to use \$checkMicroseconds.\n". "It will be removed in 4.0.0.\n". "Instead, you should use either isStartOfDay(interval: Unit::Microsecond) or isStartOfDay(interval: Unit::Second)\n". 'And you can now use any custom interval as precision, such as isStartOfDay(interval: "15 minutes")', \E_USER_DEPRECATED, ); } if ($interval === null && !\is_bool($checkMicroseconds)) { $interval = $checkMicroseconds; } if ($interval !== null) { if ($interval instanceof Unit) { $interval = '1 '.$interval->value; } $date = $this->rawFormat('Y-m-d'); $time = $this->rawFormat('H:i:s.u'); $maximum = $this->avoidMutation()->startOfDay()->add($interval); $maximumDate = $maximum->rawFormat('Y-m-d'); if ($date === $maximumDate) { return $time < $maximum->rawFormat('H:i:s.u'); } return $maximumDate > $date; } /* @var CarbonInterface $this */ return $checkMicroseconds ? $this->rawFormat('H:i:s.u') === '00:00:00.000000' : $this->rawFormat('H:i:s') === '00:00:00'; } /** * Check if the instance is end of day. * * @example * ``` * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:58.999999')->isEndOfDay(); // false * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(true); // true * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(true); // false * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(true); // false * ``` * * @param bool $checkMicroseconds check time at microseconds precision * @param Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval if an interval is specified it will be used as precision * for instance with "15 minutes", it checks if current date-time * is in the last 15 minutes of the day, with Unit::Hour, it * checks if it's in the last hour of the day. */ public function isEndOfDay( Unit|DateInterval|Closure|CarbonConverterInterface|string|bool $checkMicroseconds = false, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { if ($checkMicroseconds === true) { @trigger_error( "Since 3.8.0, it's deprecated to use \$checkMicroseconds.\n". "It will be removed in 4.0.0.\n". "Instead, you should use either isEndOfDay(interval: Unit::Microsecond) or isEndOfDay(interval: Unit::Second)\n". 'And you can now use any custom interval as precision, such as isEndOfDay(interval: "15 minutes")', \E_USER_DEPRECATED, ); } if ($interval === null && !\is_bool($checkMicroseconds)) { $interval = $checkMicroseconds; } if ($interval !== null) { $date = $this->rawFormat('Y-m-d'); $time = $this->rawFormat('H:i:s.u'); $minimum = $this->avoidMutation() ->endOfDay() ->sub($interval instanceof Unit ? '1 '.$interval->value : $interval); $minimumDate = $minimum->rawFormat('Y-m-d'); if ($date === $minimumDate) { return $time > $minimum->rawFormat('H:i:s.u'); } return $minimumDate < $date; } /* @var CarbonInterface $this */ return $checkMicroseconds ? $this->rawFormat('H:i:s.u') === '23:59:59.999999' : $this->rawFormat('H:i:s') === '23:59:59'; } /** * Determines if the instance is start of week (first day by default but interval can be customized). * * @example * ``` * Carbon::parse('2024-08-31')->startOfWeek()->isStartOfWeek(); // true * Carbon::parse('2024-08-31')->isStartOfWeek(); // false * ``` */ public function isStartOfWeek( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, WeekDay|int|null $weekStartsAt = null, ): bool { return $this->isStartOfUnit(Unit::Week, $interval, $weekStartsAt); } /** * Determines if the instance is end of week (last day by default but interval can be customized). * * @example * ``` * Carbon::parse('2024-08-31')->endOfWeek()->isEndOfWeek(); // true * Carbon::parse('2024-08-31')->isEndOfWeek(); // false * ``` */ public function isEndOfWeek( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, WeekDay|int|null $weekEndsAt = null, ): bool { return $this->isEndOfUnit(Unit::Week, $interval, $weekEndsAt); } /** * Determines if the instance is start of month (first day by default but interval can be customized). */ public function isStartOfMonth( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Month, $interval); } /** * Determines if the instance is end of month (last day by default but interval can be customized). */ public function isEndOfMonth( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Month, $interval); } /** * Determines if the instance is start of quarter (first day by default but interval can be customized). */ public function isStartOfQuarter( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Quarter, $interval); } /** * Determines if the instance is end of quarter (last day by default but interval can be customized). */ public function isEndOfQuarter( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Quarter, $interval); } /** * Determines if the instance is start of year (first day by default but interval can be customized). */ public function isStartOfYear( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Year, $interval); } /** * Determines if the instance is end of year (last day by default but interval can be customized). */ public function isEndOfYear( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Year, $interval); } /** * Determines if the instance is start of decade (first day by default but interval can be customized). */ public function isStartOfDecade( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Decade, $interval); } /** * Determines if the instance is end of decade (last day by default but interval can be customized). */ public function isEndOfDecade( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Decade, $interval); } /** * Determines if the instance is start of century (first day by default but interval can be customized). */ public function isStartOfCentury( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Century, $interval); } /** * Determines if the instance is end of century (last day by default but interval can be customized). */ public function isEndOfCentury( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Century, $interval); } /** * Determines if the instance is start of millennium (first day by default but interval can be customized). */ public function isStartOfMillennium( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Millennium, $interval); } /** * Determines if the instance is end of millennium (last day by default but interval can be customized). */ public function isEndOfMillennium( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Millennium, $interval); } /** * Check if the instance is start of day / midnight. * * @example * ``` * Carbon::parse('2019-02-28 00:00:00')->isMidnight(); // true * Carbon::parse('2019-02-28 00:00:00.999999')->isMidnight(); // true * Carbon::parse('2019-02-28 00:00:01')->isMidnight(); // false * ``` */ public function isMidnight(): bool { return $this->isStartOfDay(); } /** * Check if the instance is midday. * * @example * ``` * Carbon::parse('2019-02-28 11:59:59.999999')->isMidday(); // false * Carbon::parse('2019-02-28 12:00:00')->isMidday(); // true * Carbon::parse('2019-02-28 12:00:00.999999')->isMidday(); // true * Carbon::parse('2019-02-28 12:00:01')->isMidday(); // false * ``` */ public function isMidday(): bool { /* @var CarbonInterface $this */ return $this->rawFormat('G:i:s') === static::$midDayAt.':00:00'; } /** * Checks if the (date)time string is in a given format. * * @example * ``` * Carbon::hasFormat('11:12:45', 'h:i:s'); // true * Carbon::hasFormat('13:12:45', 'h:i:s'); // false * ``` */ public static function hasFormat(string $date, string $format): bool { return FactoryImmutable::getInstance()->hasFormat($date, $format); } /** * Checks if the (date)time string is in a given format. * * @example * ``` * Carbon::hasFormatWithModifiers('31/08/2015', 'd#m#Y'); // true * Carbon::hasFormatWithModifiers('31/08/2015', 'm#d#Y'); // false * ``` * * @param string $date * @param string $format * * @return bool */ public static function hasFormatWithModifiers(?string $date, string $format): bool { return FactoryImmutable::getInstance()->hasFormatWithModifiers($date, $format); } /** * Checks if the (date)time string is in a given format and valid to create a * new instance. * * @example * ``` * Carbon::canBeCreatedFromFormat('11:12:45', 'h:i:s'); // true * Carbon::canBeCreatedFromFormat('13:12:45', 'h:i:s'); // false * ``` */ public static function canBeCreatedFromFormat(?string $date, string $format): bool { if ($date === null) { return false; } try { // Try to create a DateTime object. Throws an InvalidArgumentException if the provided time string // doesn't match the format in any way. if (!static::rawCreateFromFormat($format, $date)) { return false; } } catch (InvalidArgumentException) { return false; } return static::hasFormatWithModifiers($date, $format); } /** * Returns true if the current date matches the given string. * * @example * ``` * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2018')); // false * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('06-02')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06-02')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('Sunday')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('June')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:45')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:00')); // false * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12h')); // true * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3pm')); // true * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3am')); // false * ``` * * @param string $tester day name, month name, hour, date, etc. as string */ public function is(WeekDay|Month|string $tester): bool { if ($tester instanceof BackedEnum) { $tester = $tester->name; } $tester = trim($tester); if (preg_match('/^\d+$/', $tester)) { return $this->year === (int) $tester; } if (preg_match('/^(?:Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|September|Oct|October|Nov|November|Dec|December)$/i', $tester)) { return $this->isSameMonth( $this->transmitFactory(static fn () => static::parse("$tester 1st")), false, ); } if (preg_match('/^\d{3,}-\d{1,2}$/', $tester)) { return $this->isSameMonth( $this->transmitFactory(static fn () => static::parse($tester)), ); } if (preg_match('/^(\d{1,2})-(\d{1,2})$/', $tester, $match)) { return $this->month === (int) $match[1] && $this->day === (int) $match[2]; } $modifier = preg_replace('/(\d)h$/i', '$1:00', $tester); /* @var CarbonInterface $max */ $median = $this->transmitFactory(static fn () => static::parse('5555-06-15 12:30:30.555555')) ->modify($modifier); $current = $this->avoidMutation(); /* @var CarbonInterface $other */ $other = $this->avoidMutation()->modify($modifier); if ($current->eq($other)) { return true; } if (preg_match('/\d:\d{1,2}:\d{1,2}$/', $tester)) { return $current->startOfSecond()->eq($other); } if (preg_match('/\d:\d{1,2}$/', $tester)) { return $current->startOfMinute()->eq($other); } if (preg_match('/\d(?:h|am|pm)$/', $tester)) { return $current->startOfHour()->eq($other); } if (preg_match( '/^(?:january|february|march|april|may|june|july|august|september|october|november|december)(?:\s+\d+)?$/i', $tester, )) { return $current->startOfMonth()->eq($other->startOfMonth()); } $units = [ 'month' => [1, 'year'], 'day' => [1, 'month'], 'hour' => [0, 'day'], 'minute' => [0, 'hour'], 'second' => [0, 'minute'], 'microsecond' => [0, 'second'], ]; foreach ($units as $unit => [$minimum, $startUnit]) { if ($minimum === $median->$unit) { $current = $current->startOf($startUnit); break; } } return $current->eq($other); } /** * Returns true if the date was created using CarbonImmutable::startOfTime() * * @return bool */ public function isStartOfTime(): bool { return $this->startOfTime ?? false; } /** * Returns true if the date was created using CarbonImmutable::endOfTime() * * @return bool */ public function isEndOfTime(): bool { return $this->endOfTime ?? false; } }
PHP
{ "end_line": 1237, "name": "canBeCreatedFromFormat", "signature": "public static function canBeCreatedFromFormat(?string $date, string $format): bool", "start_line": 1220 }
{ "class_name": "Comparison", "class_signature": "trait Comparison", "namespace": "Carbon\\Traits" }
is
Carbon/src/Carbon/Traits/Comparison.php
public function is(WeekDay|Month|string $tester): bool { if ($tester instanceof BackedEnum) { $tester = $tester->name; } $tester = trim($tester); if (preg_match('/^\d+$/', $tester)) { return $this->year === (int) $tester; } if (preg_match('/^(?:Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|September|Oct|October|Nov|November|Dec|December)$/i', $tester)) { return $this->isSameMonth( $this->transmitFactory(static fn () => static::parse("$tester 1st")), false, ); } if (preg_match('/^\d{3,}-\d{1,2}$/', $tester)) { return $this->isSameMonth( $this->transmitFactory(static fn () => static::parse($tester)), ); } if (preg_match('/^(\d{1,2})-(\d{1,2})$/', $tester, $match)) { return $this->month === (int) $match[1] && $this->day === (int) $match[2]; } $modifier = preg_replace('/(\d)h$/i', '$1:00', $tester); /* @var CarbonInterface $max */ $median = $this->transmitFactory(static fn () => static::parse('5555-06-15 12:30:30.555555')) ->modify($modifier); $current = $this->avoidMutation(); /* @var CarbonInterface $other */ $other = $this->avoidMutation()->modify($modifier); if ($current->eq($other)) { return true; } if (preg_match('/\d:\d{1,2}:\d{1,2}$/', $tester)) { return $current->startOfSecond()->eq($other); } if (preg_match('/\d:\d{1,2}$/', $tester)) { return $current->startOfMinute()->eq($other); } if (preg_match('/\d(?:h|am|pm)$/', $tester)) { return $current->startOfHour()->eq($other); } if (preg_match( '/^(?:january|february|march|april|may|june|july|august|september|october|november|december)(?:\s+\d+)?$/i', $tester, )) { return $current->startOfMonth()->eq($other->startOfMonth()); } $units = [ 'month' => [1, 'year'], 'day' => [1, 'month'], 'hour' => [0, 'day'], 'minute' => [0, 'hour'], 'second' => [0, 'minute'], 'microsecond' => [0, 'second'], ]; foreach ($units as $unit => [$minimum, $startUnit]) { if ($minimum === $median->$unit) { $current = $current->startOf($startUnit); break; } } return $current->eq($other); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use BackedEnum; use BadMethodCallException; use Carbon\CarbonConverterInterface; use Carbon\CarbonInterface; use Carbon\Exceptions\BadComparisonUnitException; use Carbon\FactoryImmutable; use Carbon\Month; use Carbon\Unit; use Carbon\WeekDay; use Closure; use DateInterval; use DateTimeInterface; use InvalidArgumentException; /** * Trait Comparison. * * Comparison utils and testers. All the following methods return booleans. * nowWithSameTz * * Depends on the following methods: * * @method static resolveCarbon($date) * @method static copy() * @method static nowWithSameTz() * @method static static yesterday($timezone = null) * @method static static tomorrow($timezone = null) */ trait Comparison { protected bool $endOfTime = false; protected bool $startOfTime = false; /** * Determines if the instance is equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->eq(Carbon::parse('2018-07-25 12:45:16')); // true * Carbon::parse('2018-07-25 12:45:16')->eq('2018-07-25 12:45:17'); // false * ``` * * @see equalTo() */ public function eq(DateTimeInterface|string $date): bool { return $this->equalTo($date); } /** * Determines if the instance is equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->equalTo(Carbon::parse('2018-07-25 12:45:16')); // true * Carbon::parse('2018-07-25 12:45:16')->equalTo('2018-07-25 12:45:17'); // false * ``` */ public function equalTo(DateTimeInterface|string $date): bool { return $this == $this->resolveCarbon($date); } /** * Determines if the instance is not equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->ne(Carbon::parse('2018-07-25 12:45:16')); // false * Carbon::parse('2018-07-25 12:45:16')->ne('2018-07-25 12:45:17'); // true * ``` * * @see notEqualTo() */ public function ne(DateTimeInterface|string $date): bool { return $this->notEqualTo($date); } /** * Determines if the instance is not equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->notEqualTo(Carbon::parse('2018-07-25 12:45:16')); // false * Carbon::parse('2018-07-25 12:45:16')->notEqualTo('2018-07-25 12:45:17'); // true * ``` */ public function notEqualTo(DateTimeInterface|string $date): bool { return !$this->equalTo($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->gt('2018-07-25 12:45:17'); // false * ``` * * @see greaterThan() */ public function gt(DateTimeInterface|string $date): bool { return $this->greaterThan($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->greaterThan('2018-07-25 12:45:17'); // false * ``` */ public function greaterThan(DateTimeInterface|string $date): bool { return $this > $this->resolveCarbon($date); } /** * Determines if the instance is greater (after) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->isAfter('2018-07-25 12:45:17'); // false * ``` * * @see greaterThan() */ public function isAfter(DateTimeInterface|string $date): bool { return $this->greaterThan($date); } /** * Determines if the instance is greater (after) than or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->gte('2018-07-25 12:45:17'); // false * ``` * * @see greaterThanOrEqualTo() */ public function gte(DateTimeInterface|string $date): bool { return $this->greaterThanOrEqualTo($date); } /** * Determines if the instance is greater (after) than or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:15'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->greaterThanOrEqualTo('2018-07-25 12:45:17'); // false * ``` */ public function greaterThanOrEqualTo(DateTimeInterface|string $date): bool { return $this >= $this->resolveCarbon($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->lt('2018-07-25 12:45:17'); // true * ``` * * @see lessThan() */ public function lt(DateTimeInterface|string $date): bool { return $this->lessThan($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThan('2018-07-25 12:45:17'); // true * ``` */ public function lessThan(DateTimeInterface|string $date): bool { return $this < $this->resolveCarbon($date); } /** * Determines if the instance is less (before) than another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:16'); // false * Carbon::parse('2018-07-25 12:45:16')->isBefore('2018-07-25 12:45:17'); // true * ``` * * @see lessThan() */ public function isBefore(DateTimeInterface|string $date): bool { return $this->lessThan($date); } /** * Determines if the instance is less (before) or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->lte('2018-07-25 12:45:17'); // true * ``` * * @see lessThanOrEqualTo() */ public function lte(DateTimeInterface|string $date): bool { return $this->lessThanOrEqualTo($date); } /** * Determines if the instance is less (before) or equal to another * * @example * ``` * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:15'); // false * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:16'); // true * Carbon::parse('2018-07-25 12:45:16')->lessThanOrEqualTo('2018-07-25 12:45:17'); // true * ``` */ public function lessThanOrEqualTo(DateTimeInterface|string $date): bool { return $this <= $this->resolveCarbon($date); } /** * Determines if the instance is between two others. * * The third argument allow you to specify if bounds are included or not (true by default) * but for when you including/excluding bounds may produce different results in your application, * we recommend to use the explicit methods ->betweenIncluded() or ->betweenExcluded() instead. * * @example * ``` * Carbon::parse('2018-07-25')->between('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->between('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01'); // true * Carbon::parse('2018-07-25')->between('2018-07-25', '2018-08-01', false); // false * ``` * * @param bool $equal Indicates if an equal to comparison should be done */ public function between(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool { $date1 = $this->resolveCarbon($date1); $date2 = $this->resolveCarbon($date2); if ($date1->greaterThan($date2)) { [$date1, $date2] = [$date2, $date1]; } if ($equal) { return $this >= $date1 && $this <= $date2; } return $this > $date1 && $this < $date2; } /** * Determines if the instance is between two others, bounds included. * * @example * ``` * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->betweenIncluded('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->betweenIncluded('2018-07-25', '2018-08-01'); // true * ``` */ public function betweenIncluded(DateTimeInterface|string $date1, DateTimeInterface|string $date2): bool { return $this->between($date1, $date2, true); } /** * Determines if the instance is between two others, bounds excluded. * * @example * ``` * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->betweenExcluded('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->betweenExcluded('2018-07-25', '2018-08-01'); // false * ``` */ public function betweenExcluded(DateTimeInterface|string $date1, DateTimeInterface|string $date2): bool { return $this->between($date1, $date2, false); } /** * Determines if the instance is between two others * * @example * ``` * Carbon::parse('2018-07-25')->isBetween('2018-07-14', '2018-08-01'); // true * Carbon::parse('2018-07-25')->isBetween('2018-08-01', '2018-08-20'); // false * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01'); // true * Carbon::parse('2018-07-25')->isBetween('2018-07-25', '2018-08-01', false); // false * ``` * * @param bool $equal Indicates if an equal to comparison should be done */ public function isBetween(DateTimeInterface|string $date1, DateTimeInterface|string $date2, bool $equal = true): bool { return $this->between($date1, $date2, $equal); } /** * Determines if the instance is a weekday. * * @example * ``` * Carbon::parse('2019-07-14')->isWeekday(); // false * Carbon::parse('2019-07-15')->isWeekday(); // true * ``` */ public function isWeekday(): bool { return !$this->isWeekend(); } /** * Determines if the instance is a weekend day. * * @example * ``` * Carbon::parse('2019-07-14')->isWeekend(); // true * Carbon::parse('2019-07-15')->isWeekend(); // false * ``` */ public function isWeekend(): bool { return \in_array( $this->dayOfWeek, $this->transmitFactory(static fn () => static::getWeekendDays()), true, ); } /** * Determines if the instance is yesterday. * * @example * ``` * Carbon::yesterday()->isYesterday(); // true * Carbon::tomorrow()->isYesterday(); // false * ``` */ public function isYesterday(): bool { return $this->toDateString() === $this->transmitFactory( fn () => static::yesterday($this->getTimezone())->toDateString(), ); } /** * Determines if the instance is today. * * @example * ``` * Carbon::today()->isToday(); // true * Carbon::tomorrow()->isToday(); // false * ``` */ public function isToday(): bool { return $this->toDateString() === $this->nowWithSameTz()->toDateString(); } /** * Determines if the instance is tomorrow. * * @example * ``` * Carbon::tomorrow()->isTomorrow(); // true * Carbon::yesterday()->isTomorrow(); // false * ``` */ public function isTomorrow(): bool { return $this->toDateString() === $this->transmitFactory( fn () => static::tomorrow($this->getTimezone())->toDateString(), ); } /** * Determines if the instance is in the future, ie. greater (after) than now. * * @example * ``` * Carbon::now()->addHours(5)->isFuture(); // true * Carbon::now()->subHours(5)->isFuture(); // false * ``` */ public function isFuture(): bool { return $this->greaterThan($this->nowWithSameTz()); } /** * Determines if the instance is in the past, ie. less (before) than now. * * @example * ``` * Carbon::now()->subHours(5)->isPast(); // true * Carbon::now()->addHours(5)->isPast(); // false * ``` */ public function isPast(): bool { return $this->lessThan($this->nowWithSameTz()); } /** * Determines if the instance is now or in the future, ie. greater (after) than or equal to now. * * @example * ``` * Carbon::now()->isNowOrFuture(); // true * Carbon::now()->addHours(5)->isNowOrFuture(); // true * Carbon::now()->subHours(5)->isNowOrFuture(); // false * ``` */ public function isNowOrFuture(): bool { return $this->greaterThanOrEqualTo($this->nowWithSameTz()); } /** * Determines if the instance is now or in the past, ie. less (before) than or equal to now. * * @example * ``` * Carbon::now()->isNowOrPast(); // true * Carbon::now()->subHours(5)->isNowOrPast(); // true * Carbon::now()->addHours(5)->isNowOrPast(); // false * ``` */ public function isNowOrPast(): bool { return $this->lessThanOrEqualTo($this->nowWithSameTz()); } /** * Determines if the instance is a leap year. * * @example * ``` * Carbon::parse('2020-01-01')->isLeapYear(); // true * Carbon::parse('2019-01-01')->isLeapYear(); // false * ``` */ public function isLeapYear(): bool { return $this->rawFormat('L') === '1'; } /** * Determines if the instance is a long year (using calendar year). * * ⚠️ This method completely ignores month and day to use the numeric year number, * it's not correct if the exact date matters. For instance as `2019-12-30` is already * in the first week of the 2020 year, if you want to know from this date if ISO week * year 2020 is a long year, use `isLongIsoYear` instead. * * @example * ``` * Carbon::create(2015)->isLongYear(); // true * Carbon::create(2016)->isLongYear(); // false * ``` * * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates */ public function isLongYear(): bool { return static::create($this->year, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === static::WEEKS_PER_YEAR + 1; } /** * Determines if the instance is a long year (using ISO 8601 year). * * @example * ``` * Carbon::parse('2015-01-01')->isLongIsoYear(); // true * Carbon::parse('2016-01-01')->isLongIsoYear(); // true * Carbon::parse('2016-01-03')->isLongIsoYear(); // false * Carbon::parse('2019-12-29')->isLongIsoYear(); // false * Carbon::parse('2019-12-30')->isLongIsoYear(); // true * ``` * * @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates */ public function isLongIsoYear(): bool { return static::create($this->isoWeekYear, 12, 28, 0, 0, 0, $this->tz)->weekOfYear === 53; } /** * Compares the formatted values of the two dates. * * @example * ``` * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-12-13')); // true * Carbon::parse('2019-06-13')->isSameAs('Y-d', Carbon::parse('2019-06-14')); // false * ``` * * @param string $format date formats to compare. * @param DateTimeInterface|string $date instance to compare with or null to use current day. */ public function isSameAs(string $format, DateTimeInterface|string $date): bool { return $this->rawFormat($format) === $this->resolveCarbon($date)->rawFormat($format); } /** * Determines if the instance is in the current unit given. * * @example * ``` * Carbon::parse('2019-01-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // true * Carbon::parse('2018-12-13')->isSameUnit('year', Carbon::parse('2019-12-25')); // false * ``` * * @param string $unit singular unit string * @param DateTimeInterface|string $date instance to compare with or null to use current day. * * @throws BadComparisonUnitException * * @return bool */ public function isSameUnit(string $unit, DateTimeInterface|string $date): bool { if ($unit === /* @call isSameUnit */ 'quarter') { $other = $this->resolveCarbon($date); return $other->year === $this->year && $other->quarter === $this->quarter; } $units = [ // @call isSameUnit 'year' => 'Y', // @call isSameUnit 'month' => 'Y-n', // @call isSameUnit 'week' => 'o-W', // @call isSameUnit 'day' => 'Y-m-d', // @call isSameUnit 'hour' => 'Y-m-d H', // @call isSameUnit 'minute' => 'Y-m-d H:i', // @call isSameUnit 'second' => 'Y-m-d H:i:s', // @call isSameUnit 'milli' => 'Y-m-d H:i:s.v', // @call isSameUnit 'millisecond' => 'Y-m-d H:i:s.v', // @call isSameUnit 'micro' => 'Y-m-d H:i:s.u', // @call isSameUnit 'microsecond' => 'Y-m-d H:i:s.u', ]; if (isset($units[$unit])) { return $this->isSameAs($units[$unit], $date); } if (isset($this->$unit)) { return $this->resolveCarbon($date)->$unit === $this->$unit; } if ($this->isLocalStrictModeEnabled()) { throw new BadComparisonUnitException($unit); } return false; } /** * Determines if the instance is in the current unit given. * * @example * ``` * Carbon::now()->isCurrentUnit('hour'); // true * Carbon::now()->subHours(2)->isCurrentUnit('hour'); // false * ``` * * @param string $unit The unit to test. * * @throws BadMethodCallException */ public function isCurrentUnit(string $unit): bool { return $this->{'isSame'.ucfirst($unit)}('now'); } /** * Checks if the passed in date is in the same quarter as the instance quarter (and year if needed). * * @example * ``` * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-03-01')); // true * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2019-04-01')); // false * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01')); // false * Carbon::parse('2019-01-12')->isSameQuarter(Carbon::parse('2018-03-01'), false); // true * ``` * * @param DateTimeInterface|string $date The instance to compare with or null to use current day. * @param bool $ofSameYear Check if it is the same month in the same year. * * @return bool */ public function isSameQuarter(DateTimeInterface|string $date, bool $ofSameYear = true): bool { $date = $this->resolveCarbon($date); return $this->quarter === $date->quarter && (!$ofSameYear || $this->isSameYear($date)); } /** * Checks if the passed in date is in the same month as the instance´s month. * * @example * ``` * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-01-01')); // true * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2019-02-01')); // false * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01')); // false * Carbon::parse('2019-01-12')->isSameMonth(Carbon::parse('2018-01-01'), false); // true * ``` * * @param DateTimeInterface|string $date The instance to compare with or null to use the current date. * @param bool $ofSameYear Check if it is the same month in the same year. * * @return bool */ public function isSameMonth(DateTimeInterface|string $date, bool $ofSameYear = true): bool { return $this->isSameAs($ofSameYear ? 'Y-m' : 'm', $date); } /** * Checks if this day is a specific day of the week. * * @example * ``` * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::WEDNESDAY); // true * Carbon::parse('2019-07-17')->isDayOfWeek(Carbon::FRIDAY); // false * Carbon::parse('2019-07-17')->isDayOfWeek('Wednesday'); // true * Carbon::parse('2019-07-17')->isDayOfWeek('Friday'); // false * ``` * * @param int|string $dayOfWeek * * @return bool */ public function isDayOfWeek($dayOfWeek): bool { if (\is_string($dayOfWeek) && \defined($constant = static::class.'::'.strtoupper($dayOfWeek))) { $dayOfWeek = \constant($constant); } return $this->dayOfWeek === $dayOfWeek; } /** * Check if its the birthday. Compares the date/month values of the two dates. * * @example * ``` * Carbon::now()->subYears(5)->isBirthday(); // true * Carbon::now()->subYears(5)->subDay()->isBirthday(); // false * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-05')); // true * Carbon::parse('2019-06-05')->isBirthday(Carbon::parse('2001-06-06')); // false * ``` * * @param DateTimeInterface|string|null $date The instance to compare with or null to use current day. * * @return bool */ public function isBirthday(DateTimeInterface|string|null $date = null): bool { return $this->isSameAs('md', $date ?? 'now'); } /** * Check if today is the last day of the Month * * @example * ``` * Carbon::parse('2019-02-28')->isLastOfMonth(); // true * Carbon::parse('2019-03-28')->isLastOfMonth(); // false * Carbon::parse('2019-03-30')->isLastOfMonth(); // false * Carbon::parse('2019-03-31')->isLastOfMonth(); // true * Carbon::parse('2019-04-30')->isLastOfMonth(); // true * ``` */ public function isLastOfMonth(): bool { return $this->day === $this->daysInMonth; } /** * Check if the instance is start of a given unit (tolerating a given interval). * * @example * ``` * // Check if a date-time is the first 15 minutes of the hour it's in * Carbon::parse('2019-02-28 20:13:00')->isStartOfUnit(Unit::Hour, '15 minutes'); // true * ``` */ public function isStartOfUnit( Unit $unit, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, mixed ...$params, ): bool { $interval ??= match ($unit) { Unit::Day, Unit::Hour, Unit::Minute, Unit::Second, Unit::Millisecond, Unit::Microsecond => Unit::Microsecond, default => Unit::Day, }; $startOfUnit = $this->avoidMutation()->startOf($unit, ...$params); $startOfUnitDateTime = $startOfUnit->rawFormat('Y-m-d H:i:s.u'); $maximumDateTime = $startOfUnit ->add($interval instanceof Unit ? '1 '.$interval->value : $interval) ->rawFormat('Y-m-d H:i:s.u'); if ($maximumDateTime < $startOfUnitDateTime) { return false; } return $this->rawFormat('Y-m-d H:i:s.u') < $maximumDateTime; } /** * Check if the instance is end of a given unit (tolerating a given interval). * * @example * ``` * // Check if a date-time is the last 15 minutes of the hour it's in * Carbon::parse('2019-02-28 20:13:00')->isEndOfUnit(Unit::Hour, '15 minutes'); // false * ``` */ public function isEndOfUnit( Unit $unit, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, mixed ...$params, ): bool { $interval ??= match ($unit) { Unit::Day, Unit::Hour, Unit::Minute, Unit::Second, Unit::Millisecond, Unit::Microsecond => Unit::Microsecond, default => Unit::Day, }; $endOfUnit = $this->avoidMutation()->endOf($unit, ...$params); $endOfUnitDateTime = $endOfUnit->rawFormat('Y-m-d H:i:s.u'); $minimumDateTime = $endOfUnit ->sub($interval instanceof Unit ? '1 '.$interval->value : $interval) ->rawFormat('Y-m-d H:i:s.u'); if ($minimumDateTime > $endOfUnitDateTime) { return false; } return $this->rawFormat('Y-m-d H:i:s.u') > $minimumDateTime; } /** * Determines if the instance is start of millisecond (first microsecond by default but interval can be customized). */ public function isStartOfMillisecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Millisecond, $interval); } /** * Determines if the instance is end of millisecond (last microsecond by default but interval can be customized). */ public function isEndOfMillisecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Millisecond, $interval); } /** * Determines if the instance is start of second (first microsecond by default but interval can be customized). */ public function isStartOfSecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Second, $interval); } /** * Determines if the instance is end of second (last microsecond by default but interval can be customized). */ public function isEndOfSecond( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Second, $interval); } /** * Determines if the instance is start of minute (first microsecond by default but interval can be customized). */ public function isStartOfMinute( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Minute, $interval); } /** * Determines if the instance is end of minute (last microsecond by default but interval can be customized). */ public function isEndOfMinute( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Minute, $interval); } /** * Determines if the instance is start of hour (first microsecond by default but interval can be customized). */ public function isStartOfHour( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Hour, $interval); } /** * Determines if the instance is end of hour (last microsecond by default but interval can be customized). */ public function isEndOfHour( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Hour, $interval); } /** * Check if the instance is start of day / midnight. * * @example * ``` * Carbon::parse('2019-02-28 00:00:00')->isStartOfDay(); // true * Carbon::parse('2019-02-28 00:00:00.999999')->isStartOfDay(); // true * Carbon::parse('2019-02-28 00:00:01')->isStartOfDay(); // false * Carbon::parse('2019-02-28 00:00:00.000000')->isStartOfDay(true); // true * Carbon::parse('2019-02-28 00:00:00.000012')->isStartOfDay(true); // false * ``` * * @param bool $checkMicroseconds check time at microseconds precision * @param Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval if an interval is specified it will be used as precision * for instance with "15 minutes", it checks if current date-time * is in the last 15 minutes of the day, with Unit::Hour, it * checks if it's in the last hour of the day. */ public function isStartOfDay( Unit|DateInterval|Closure|CarbonConverterInterface|string|bool $checkMicroseconds = false, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { if ($checkMicroseconds === true) { @trigger_error( "Since 3.8.0, it's deprecated to use \$checkMicroseconds.\n". "It will be removed in 4.0.0.\n". "Instead, you should use either isStartOfDay(interval: Unit::Microsecond) or isStartOfDay(interval: Unit::Second)\n". 'And you can now use any custom interval as precision, such as isStartOfDay(interval: "15 minutes")', \E_USER_DEPRECATED, ); } if ($interval === null && !\is_bool($checkMicroseconds)) { $interval = $checkMicroseconds; } if ($interval !== null) { if ($interval instanceof Unit) { $interval = '1 '.$interval->value; } $date = $this->rawFormat('Y-m-d'); $time = $this->rawFormat('H:i:s.u'); $maximum = $this->avoidMutation()->startOfDay()->add($interval); $maximumDate = $maximum->rawFormat('Y-m-d'); if ($date === $maximumDate) { return $time < $maximum->rawFormat('H:i:s.u'); } return $maximumDate > $date; } /* @var CarbonInterface $this */ return $checkMicroseconds ? $this->rawFormat('H:i:s.u') === '00:00:00.000000' : $this->rawFormat('H:i:s') === '00:00:00'; } /** * Check if the instance is end of day. * * @example * ``` * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(); // true * Carbon::parse('2019-02-28 23:59:58.999999')->isEndOfDay(); // false * Carbon::parse('2019-02-28 23:59:59.999999')->isEndOfDay(true); // true * Carbon::parse('2019-02-28 23:59:59.123456')->isEndOfDay(true); // false * Carbon::parse('2019-02-28 23:59:59')->isEndOfDay(true); // false * ``` * * @param bool $checkMicroseconds check time at microseconds precision * @param Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval if an interval is specified it will be used as precision * for instance with "15 minutes", it checks if current date-time * is in the last 15 minutes of the day, with Unit::Hour, it * checks if it's in the last hour of the day. */ public function isEndOfDay( Unit|DateInterval|Closure|CarbonConverterInterface|string|bool $checkMicroseconds = false, Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { if ($checkMicroseconds === true) { @trigger_error( "Since 3.8.0, it's deprecated to use \$checkMicroseconds.\n". "It will be removed in 4.0.0.\n". "Instead, you should use either isEndOfDay(interval: Unit::Microsecond) or isEndOfDay(interval: Unit::Second)\n". 'And you can now use any custom interval as precision, such as isEndOfDay(interval: "15 minutes")', \E_USER_DEPRECATED, ); } if ($interval === null && !\is_bool($checkMicroseconds)) { $interval = $checkMicroseconds; } if ($interval !== null) { $date = $this->rawFormat('Y-m-d'); $time = $this->rawFormat('H:i:s.u'); $minimum = $this->avoidMutation() ->endOfDay() ->sub($interval instanceof Unit ? '1 '.$interval->value : $interval); $minimumDate = $minimum->rawFormat('Y-m-d'); if ($date === $minimumDate) { return $time > $minimum->rawFormat('H:i:s.u'); } return $minimumDate < $date; } /* @var CarbonInterface $this */ return $checkMicroseconds ? $this->rawFormat('H:i:s.u') === '23:59:59.999999' : $this->rawFormat('H:i:s') === '23:59:59'; } /** * Determines if the instance is start of week (first day by default but interval can be customized). * * @example * ``` * Carbon::parse('2024-08-31')->startOfWeek()->isStartOfWeek(); // true * Carbon::parse('2024-08-31')->isStartOfWeek(); // false * ``` */ public function isStartOfWeek( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, WeekDay|int|null $weekStartsAt = null, ): bool { return $this->isStartOfUnit(Unit::Week, $interval, $weekStartsAt); } /** * Determines if the instance is end of week (last day by default but interval can be customized). * * @example * ``` * Carbon::parse('2024-08-31')->endOfWeek()->isEndOfWeek(); // true * Carbon::parse('2024-08-31')->isEndOfWeek(); // false * ``` */ public function isEndOfWeek( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, WeekDay|int|null $weekEndsAt = null, ): bool { return $this->isEndOfUnit(Unit::Week, $interval, $weekEndsAt); } /** * Determines if the instance is start of month (first day by default but interval can be customized). */ public function isStartOfMonth( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Month, $interval); } /** * Determines if the instance is end of month (last day by default but interval can be customized). */ public function isEndOfMonth( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Month, $interval); } /** * Determines if the instance is start of quarter (first day by default but interval can be customized). */ public function isStartOfQuarter( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Quarter, $interval); } /** * Determines if the instance is end of quarter (last day by default but interval can be customized). */ public function isEndOfQuarter( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Quarter, $interval); } /** * Determines if the instance is start of year (first day by default but interval can be customized). */ public function isStartOfYear( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Year, $interval); } /** * Determines if the instance is end of year (last day by default but interval can be customized). */ public function isEndOfYear( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Year, $interval); } /** * Determines if the instance is start of decade (first day by default but interval can be customized). */ public function isStartOfDecade( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Decade, $interval); } /** * Determines if the instance is end of decade (last day by default but interval can be customized). */ public function isEndOfDecade( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Decade, $interval); } /** * Determines if the instance is start of century (first day by default but interval can be customized). */ public function isStartOfCentury( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Century, $interval); } /** * Determines if the instance is end of century (last day by default but interval can be customized). */ public function isEndOfCentury( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Century, $interval); } /** * Determines if the instance is start of millennium (first day by default but interval can be customized). */ public function isStartOfMillennium( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isStartOfUnit(Unit::Millennium, $interval); } /** * Determines if the instance is end of millennium (last day by default but interval can be customized). */ public function isEndOfMillennium( Unit|DateInterval|Closure|CarbonConverterInterface|string|null $interval = null, ): bool { return $this->isEndOfUnit(Unit::Millennium, $interval); } /** * Check if the instance is start of day / midnight. * * @example * ``` * Carbon::parse('2019-02-28 00:00:00')->isMidnight(); // true * Carbon::parse('2019-02-28 00:00:00.999999')->isMidnight(); // true * Carbon::parse('2019-02-28 00:00:01')->isMidnight(); // false * ``` */ public function isMidnight(): bool { return $this->isStartOfDay(); } /** * Check if the instance is midday. * * @example * ``` * Carbon::parse('2019-02-28 11:59:59.999999')->isMidday(); // false * Carbon::parse('2019-02-28 12:00:00')->isMidday(); // true * Carbon::parse('2019-02-28 12:00:00.999999')->isMidday(); // true * Carbon::parse('2019-02-28 12:00:01')->isMidday(); // false * ``` */ public function isMidday(): bool { /* @var CarbonInterface $this */ return $this->rawFormat('G:i:s') === static::$midDayAt.':00:00'; } /** * Checks if the (date)time string is in a given format. * * @example * ``` * Carbon::hasFormat('11:12:45', 'h:i:s'); // true * Carbon::hasFormat('13:12:45', 'h:i:s'); // false * ``` */ public static function hasFormat(string $date, string $format): bool { return FactoryImmutable::getInstance()->hasFormat($date, $format); } /** * Checks if the (date)time string is in a given format. * * @example * ``` * Carbon::hasFormatWithModifiers('31/08/2015', 'd#m#Y'); // true * Carbon::hasFormatWithModifiers('31/08/2015', 'm#d#Y'); // false * ``` * * @param string $date * @param string $format * * @return bool */ public static function hasFormatWithModifiers(?string $date, string $format): bool { return FactoryImmutable::getInstance()->hasFormatWithModifiers($date, $format); } /** * Checks if the (date)time string is in a given format and valid to create a * new instance. * * @example * ``` * Carbon::canBeCreatedFromFormat('11:12:45', 'h:i:s'); // true * Carbon::canBeCreatedFromFormat('13:12:45', 'h:i:s'); // false * ``` */ public static function canBeCreatedFromFormat(?string $date, string $format): bool { if ($date === null) { return false; } try { // Try to create a DateTime object. Throws an InvalidArgumentException if the provided time string // doesn't match the format in any way. if (!static::rawCreateFromFormat($format, $date)) { return false; } } catch (InvalidArgumentException) { return false; } return static::hasFormatWithModifiers($date, $format); } /** * Returns true if the current date matches the given string. * * @example * ``` * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2018')); // false * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('06-02')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('2019-06-02')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('Sunday')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('June')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:45')); // true * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12:23:00')); // false * var_dump(Carbon::parse('2019-06-02 12:23:45')->is('12h')); // true * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3pm')); // true * var_dump(Carbon::parse('2019-06-02 15:23:45')->is('3am')); // false * ``` * * @param string $tester day name, month name, hour, date, etc. as string */ public function is(WeekDay|Month|string $tester): bool { if ($tester instanceof BackedEnum) { $tester = $tester->name; } $tester = trim($tester); if (preg_match('/^\d+$/', $tester)) { return $this->year === (int) $tester; } if (preg_match('/^(?:Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|September|Oct|October|Nov|November|Dec|December)$/i', $tester)) { return $this->isSameMonth( $this->transmitFactory(static fn () => static::parse("$tester 1st")), false, ); } if (preg_match('/^\d{3,}-\d{1,2}$/', $tester)) { return $this->isSameMonth( $this->transmitFactory(static fn () => static::parse($tester)), ); } if (preg_match('/^(\d{1,2})-(\d{1,2})$/', $tester, $match)) { return $this->month === (int) $match[1] && $this->day === (int) $match[2]; } $modifier = preg_replace('/(\d)h$/i', '$1:00', $tester); /* @var CarbonInterface $max */ $median = $this->transmitFactory(static fn () => static::parse('5555-06-15 12:30:30.555555')) ->modify($modifier); $current = $this->avoidMutation(); /* @var CarbonInterface $other */ $other = $this->avoidMutation()->modify($modifier); if ($current->eq($other)) { return true; } if (preg_match('/\d:\d{1,2}:\d{1,2}$/', $tester)) { return $current->startOfSecond()->eq($other); } if (preg_match('/\d:\d{1,2}$/', $tester)) { return $current->startOfMinute()->eq($other); } if (preg_match('/\d(?:h|am|pm)$/', $tester)) { return $current->startOfHour()->eq($other); } if (preg_match( '/^(?:january|february|march|april|may|june|july|august|september|october|november|december)(?:\s+\d+)?$/i', $tester, )) { return $current->startOfMonth()->eq($other->startOfMonth()); } $units = [ 'month' => [1, 'year'], 'day' => [1, 'month'], 'hour' => [0, 'day'], 'minute' => [0, 'hour'], 'second' => [0, 'minute'], 'microsecond' => [0, 'second'], ]; foreach ($units as $unit => [$minimum, $startUnit]) { if ($minimum === $median->$unit) { $current = $current->startOf($startUnit); break; } } return $current->eq($other); } /** * Returns true if the date was created using CarbonImmutable::startOfTime() * * @return bool */ public function isStartOfTime(): bool { return $this->startOfTime ?? false; } /** * Returns true if the date was created using CarbonImmutable::endOfTime() * * @return bool */ public function isEndOfTime(): bool { return $this->endOfTime ?? false; } }
PHP
{ "end_line": 1340, "name": "is", "signature": "public function is(WeekDay|Month|string $tester): bool", "start_line": 1261 }
{ "class_name": "Comparison", "class_signature": "trait Comparison", "namespace": "Carbon\\Traits" }
format
Carbon/src/Carbon/Traits/Converter.php
public function format(string $format): string { $function = $this->localFormatFunction ?? $this->getFactory()->getSettings()['formatFunction'] ?? static::$formatFunction; if (!$function) { return $this->rawFormat($format); } if (\is_string($function) && method_exists($this, $function)) { $function = [$this, $function]; } return $function(...\func_get_args()); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Carbon\CarbonPeriodImmutable; use Carbon\Exceptions\UnitException; use Closure; use DateTime; use DateTimeImmutable; use DateTimeInterface; /** * Trait Converter. * * Change date into different string formats and types and * handle the string cast. * * Depends on the following methods: * * @method static copy() */ trait Converter { use ToStringFormat; /** * Returns the formatted date string on success or FALSE on failure. * * @see https://php.net/manual/en/datetime.format.php */ public function format(string $format): string { $function = $this->localFormatFunction ?? $this->getFactory()->getSettings()['formatFunction'] ?? static::$formatFunction; if (!$function) { return $this->rawFormat($format); } if (\is_string($function) && method_exists($this, $function)) { $function = [$this, $function]; } return $function(...\func_get_args()); } /** * @see https://php.net/manual/en/datetime.format.php */ public function rawFormat(string $format): string { return parent::format($format); } /** * Format the instance as a string using the set format * * @example * ``` * echo Carbon::now(); // Carbon instances can be cast to string * ``` */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; return $format instanceof Closure ? $format($this) : $this->rawFormat($format ?: ( \defined('static::DEFAULT_TO_STRING_FORMAT') ? static::DEFAULT_TO_STRING_FORMAT : CarbonInterface::DEFAULT_TO_STRING_FORMAT )); } /** * Format the instance as date * * @example * ``` * echo Carbon::now()->toDateString(); * ``` */ public function toDateString(): string { return $this->rawFormat('Y-m-d'); } /** * Format the instance as a readable date * * @example * ``` * echo Carbon::now()->toFormattedDateString(); * ``` */ public function toFormattedDateString(): string { return $this->rawFormat('M j, Y'); } /** * Format the instance with the day, and a readable date * * @example * ``` * echo Carbon::now()->toFormattedDayDateString(); * ``` */ public function toFormattedDayDateString(): string { return $this->rawFormat('D, M j, Y'); } /** * Format the instance as time * * @example * ``` * echo Carbon::now()->toTimeString(); * ``` */ public function toTimeString(string $unitPrecision = 'second'): string { return $this->rawFormat(static::getTimeFormatByPrecision($unitPrecision)); } /** * Format the instance as date and time * * @example * ``` * echo Carbon::now()->toDateTimeString(); * ``` */ public function toDateTimeString(string $unitPrecision = 'second'): string { return $this->rawFormat('Y-m-d '.static::getTimeFormatByPrecision($unitPrecision)); } /** * Return a format from H:i to H:i:s.u according to given unit precision. * * @param string $unitPrecision "minute", "second", "millisecond" or "microsecond" */ public static function getTimeFormatByPrecision(string $unitPrecision): string { return match (static::singularUnit($unitPrecision)) { 'minute' => 'H:i', 'second' => 'H:i:s', 'm', 'millisecond' => 'H:i:s.v', 'µ', 'microsecond' => 'H:i:s.u', default => throw new UnitException('Precision unit expected among: minute, second, millisecond and microsecond.'), }; } /** * Format the instance as date and time T-separated with no timezone * * @example * ``` * echo Carbon::now()->toDateTimeLocalString(); * echo "\n"; * echo Carbon::now()->toDateTimeLocalString('minute'); // You can specify precision among: minute, second, millisecond and microsecond * ``` */ public function toDateTimeLocalString(string $unitPrecision = 'second'): string { return $this->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision)); } /** * Format the instance with day, date and time * * @example * ``` * echo Carbon::now()->toDayDateTimeString(); * ``` */ public function toDayDateTimeString(): string { return $this->rawFormat('D, M j, Y g:i A'); } /** * Format the instance as ATOM * * @example * ``` * echo Carbon::now()->toAtomString(); * ``` */ public function toAtomString(): string { return $this->rawFormat(DateTime::ATOM); } /** * Format the instance as COOKIE * * @example * ``` * echo Carbon::now()->toCookieString(); * ``` */ public function toCookieString(): string { return $this->rawFormat(DateTimeInterface::COOKIE); } /** * Format the instance as ISO8601 * * @example * ``` * echo Carbon::now()->toIso8601String(); * ``` */ public function toIso8601String(): string { return $this->toAtomString(); } /** * Format the instance as RFC822 * * @example * ``` * echo Carbon::now()->toRfc822String(); * ``` */ public function toRfc822String(): string { return $this->rawFormat(DateTimeInterface::RFC822); } /** * Convert the instance to UTC and return as Zulu ISO8601 * * @example * ``` * echo Carbon::now()->toIso8601ZuluString(); * ``` */ public function toIso8601ZuluString(string $unitPrecision = 'second'): string { return $this->avoidMutation() ->utc() ->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision).'\Z'); } /** * Format the instance as RFC850 * * @example * ``` * echo Carbon::now()->toRfc850String(); * ``` */ public function toRfc850String(): string { return $this->rawFormat(DateTimeInterface::RFC850); } /** * Format the instance as RFC1036 * * @example * ``` * echo Carbon::now()->toRfc1036String(); * ``` */ public function toRfc1036String(): string { return $this->rawFormat(DateTimeInterface::RFC1036); } /** * Format the instance as RFC1123 * * @example * ``` * echo Carbon::now()->toRfc1123String(); * ``` */ public function toRfc1123String(): string { return $this->rawFormat(DateTimeInterface::RFC1123); } /** * Format the instance as RFC2822 * * @example * ``` * echo Carbon::now()->toRfc2822String(); * ``` */ public function toRfc2822String(): string { return $this->rawFormat(DateTimeInterface::RFC2822); } /** * Format the instance as RFC3339. * * @example * ``` * echo Carbon::now()->toRfc3339String() . "\n"; * echo Carbon::now()->toRfc3339String(true) . "\n"; * ``` */ public function toRfc3339String(bool $extended = false): string { return $this->rawFormat($extended ? DateTimeInterface::RFC3339_EXTENDED : DateTimeInterface::RFC3339); } /** * Format the instance as RSS * * @example * ``` * echo Carbon::now()->toRssString(); * ``` */ public function toRssString(): string { return $this->rawFormat(DateTimeInterface::RSS); } /** * Format the instance as W3C * * @example * ``` * echo Carbon::now()->toW3cString(); * ``` */ public function toW3cString(): string { return $this->rawFormat(DateTimeInterface::W3C); } /** * Format the instance as RFC7231 * * @example * ``` * echo Carbon::now()->toRfc7231String(); * ``` */ public function toRfc7231String(): string { return $this->avoidMutation() ->setTimezone('GMT') ->rawFormat(\defined('static::RFC7231_FORMAT') ? static::RFC7231_FORMAT : CarbonInterface::RFC7231_FORMAT); } /** * Get default array representation. * * @example * ``` * var_dump(Carbon::now()->toArray()); * ``` */ public function toArray(): array { return [ 'year' => $this->year, 'month' => $this->month, 'day' => $this->day, 'dayOfWeek' => $this->dayOfWeek, 'dayOfYear' => $this->dayOfYear, 'hour' => $this->hour, 'minute' => $this->minute, 'second' => $this->second, 'micro' => $this->micro, 'timestamp' => $this->timestamp, 'formatted' => $this->rawFormat(\defined('static::DEFAULT_TO_STRING_FORMAT') ? static::DEFAULT_TO_STRING_FORMAT : CarbonInterface::DEFAULT_TO_STRING_FORMAT), 'timezone' => $this->timezone, ]; } /** * Get default object representation. * * @example * ``` * var_dump(Carbon::now()->toObject()); * ``` */ public function toObject(): object { return (object) $this->toArray(); } /** * Returns english human-readable complete date string. * * @example * ``` * echo Carbon::now()->toString(); * ``` */ public function toString(): string { return $this->avoidMutation()->locale('en')->isoFormat('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); } /** * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z, if $keepOffset truthy, offset will be kept: * 1977-04-22T01:00:00-05:00). * * @example * ``` * echo Carbon::now('America/Toronto')->toISOString() . "\n"; * echo Carbon::now('America/Toronto')->toISOString(true) . "\n"; * ``` * * @param bool $keepOffset Pass true to keep the date offset. Else forced to UTC. */ public function toISOString(bool $keepOffset = false): ?string { if (!$this->isValid()) { return null; } $yearFormat = $this->year < 0 || $this->year > 9999 ? 'YYYYYY' : 'YYYY'; $timezoneFormat = $keepOffset ? 'Z' : '[Z]'; $date = $keepOffset ? $this : $this->avoidMutation()->utc(); return $date->isoFormat("$yearFormat-MM-DD[T]HH:mm:ss.SSSSSS$timezoneFormat"); } /** * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z) with UTC timezone. * * @example * ``` * echo Carbon::now('America/Toronto')->toJSON(); * ``` */ public function toJSON(): ?string { return $this->toISOString(); } /** * Return native DateTime PHP object matching the current instance. * * @example * ``` * var_dump(Carbon::now()->toDateTime()); * ``` */ public function toDateTime(): DateTime { return DateTime::createFromFormat('U.u', $this->rawFormat('U.u')) ->setTimezone($this->getTimezone()); } /** * Return native toDateTimeImmutable PHP object matching the current instance. * * @example * ``` * var_dump(Carbon::now()->toDateTimeImmutable()); * ``` */ public function toDateTimeImmutable(): DateTimeImmutable { return DateTimeImmutable::createFromFormat('U.u', $this->rawFormat('U.u')) ->setTimezone($this->getTimezone()); } /** * @alias toDateTime * * Return native DateTime PHP object matching the current instance. * * @example * ``` * var_dump(Carbon::now()->toDate()); * ``` */ public function toDate(): DateTime { return $this->toDateTime(); } /** * Create a iterable CarbonPeriod object from current date to a given end date (and optional interval). * * @param \DateTimeInterface|Carbon|CarbonImmutable|int|null $end period end date or recurrences count if int * @param int|\DateInterval|string|null $interval period default interval or number of the given $unit * @param string|null $unit if specified, $interval must be an integer */ public function toPeriod($end = null, $interval = null, $unit = null): CarbonPeriod { if ($unit) { $interval = CarbonInterval::make("$interval ".static::pluralUnit($unit)); } $isDefaultInterval = !$interval; $interval ??= CarbonInterval::day(); $class = $this->isMutable() ? CarbonPeriod::class : CarbonPeriodImmutable::class; if (\is_int($end) || (\is_string($end) && ctype_digit($end))) { $end = (int) $end; } $end ??= 1; if (!\is_int($end)) { $end = $this->resolveCarbon($end); } return new $class( raw: [$this, CarbonInterval::make($interval), $end], dateClass: static::class, isDefaultInterval: $isDefaultInterval, ); } /** * Create a iterable CarbonPeriod object from current date to a given end date (and optional interval). * * @param \DateTimeInterface|Carbon|CarbonImmutable|null $end period end date * @param int|\DateInterval|string|null $interval period default interval or number of the given $unit * @param string|null $unit if specified, $interval must be an integer */ public function range($end = null, $interval = null, $unit = null): CarbonPeriod { return $this->toPeriod($end, $interval, $unit); } }
PHP
{ "end_line": 62, "name": "format", "signature": "public function format(string $format): string", "start_line": 47 }
{ "class_name": "Converter", "class_signature": "trait Converter", "namespace": "Carbon\\Traits" }
toArray
Carbon/src/Carbon/Traits/Converter.php
public function toArray(): array { return [ 'year' => $this->year, 'month' => $this->month, 'day' => $this->day, 'dayOfWeek' => $this->dayOfWeek, 'dayOfYear' => $this->dayOfYear, 'hour' => $this->hour, 'minute' => $this->minute, 'second' => $this->second, 'micro' => $this->micro, 'timestamp' => $this->timestamp, 'formatted' => $this->rawFormat(\defined('static::DEFAULT_TO_STRING_FORMAT') ? static::DEFAULT_TO_STRING_FORMAT : CarbonInterface::DEFAULT_TO_STRING_FORMAT), 'timezone' => $this->timezone, ]; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Carbon\CarbonPeriodImmutable; use Carbon\Exceptions\UnitException; use Closure; use DateTime; use DateTimeImmutable; use DateTimeInterface; /** * Trait Converter. * * Change date into different string formats and types and * handle the string cast. * * Depends on the following methods: * * @method static copy() */ trait Converter { use ToStringFormat; /** * Returns the formatted date string on success or FALSE on failure. * * @see https://php.net/manual/en/datetime.format.php */ public function format(string $format): string { $function = $this->localFormatFunction ?? $this->getFactory()->getSettings()['formatFunction'] ?? static::$formatFunction; if (!$function) { return $this->rawFormat($format); } if (\is_string($function) && method_exists($this, $function)) { $function = [$this, $function]; } return $function(...\func_get_args()); } /** * @see https://php.net/manual/en/datetime.format.php */ public function rawFormat(string $format): string { return parent::format($format); } /** * Format the instance as a string using the set format * * @example * ``` * echo Carbon::now(); // Carbon instances can be cast to string * ``` */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; return $format instanceof Closure ? $format($this) : $this->rawFormat($format ?: ( \defined('static::DEFAULT_TO_STRING_FORMAT') ? static::DEFAULT_TO_STRING_FORMAT : CarbonInterface::DEFAULT_TO_STRING_FORMAT )); } /** * Format the instance as date * * @example * ``` * echo Carbon::now()->toDateString(); * ``` */ public function toDateString(): string { return $this->rawFormat('Y-m-d'); } /** * Format the instance as a readable date * * @example * ``` * echo Carbon::now()->toFormattedDateString(); * ``` */ public function toFormattedDateString(): string { return $this->rawFormat('M j, Y'); } /** * Format the instance with the day, and a readable date * * @example * ``` * echo Carbon::now()->toFormattedDayDateString(); * ``` */ public function toFormattedDayDateString(): string { return $this->rawFormat('D, M j, Y'); } /** * Format the instance as time * * @example * ``` * echo Carbon::now()->toTimeString(); * ``` */ public function toTimeString(string $unitPrecision = 'second'): string { return $this->rawFormat(static::getTimeFormatByPrecision($unitPrecision)); } /** * Format the instance as date and time * * @example * ``` * echo Carbon::now()->toDateTimeString(); * ``` */ public function toDateTimeString(string $unitPrecision = 'second'): string { return $this->rawFormat('Y-m-d '.static::getTimeFormatByPrecision($unitPrecision)); } /** * Return a format from H:i to H:i:s.u according to given unit precision. * * @param string $unitPrecision "minute", "second", "millisecond" or "microsecond" */ public static function getTimeFormatByPrecision(string $unitPrecision): string { return match (static::singularUnit($unitPrecision)) { 'minute' => 'H:i', 'second' => 'H:i:s', 'm', 'millisecond' => 'H:i:s.v', 'µ', 'microsecond' => 'H:i:s.u', default => throw new UnitException('Precision unit expected among: minute, second, millisecond and microsecond.'), }; } /** * Format the instance as date and time T-separated with no timezone * * @example * ``` * echo Carbon::now()->toDateTimeLocalString(); * echo "\n"; * echo Carbon::now()->toDateTimeLocalString('minute'); // You can specify precision among: minute, second, millisecond and microsecond * ``` */ public function toDateTimeLocalString(string $unitPrecision = 'second'): string { return $this->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision)); } /** * Format the instance with day, date and time * * @example * ``` * echo Carbon::now()->toDayDateTimeString(); * ``` */ public function toDayDateTimeString(): string { return $this->rawFormat('D, M j, Y g:i A'); } /** * Format the instance as ATOM * * @example * ``` * echo Carbon::now()->toAtomString(); * ``` */ public function toAtomString(): string { return $this->rawFormat(DateTime::ATOM); } /** * Format the instance as COOKIE * * @example * ``` * echo Carbon::now()->toCookieString(); * ``` */ public function toCookieString(): string { return $this->rawFormat(DateTimeInterface::COOKIE); } /** * Format the instance as ISO8601 * * @example * ``` * echo Carbon::now()->toIso8601String(); * ``` */ public function toIso8601String(): string { return $this->toAtomString(); } /** * Format the instance as RFC822 * * @example * ``` * echo Carbon::now()->toRfc822String(); * ``` */ public function toRfc822String(): string { return $this->rawFormat(DateTimeInterface::RFC822); } /** * Convert the instance to UTC and return as Zulu ISO8601 * * @example * ``` * echo Carbon::now()->toIso8601ZuluString(); * ``` */ public function toIso8601ZuluString(string $unitPrecision = 'second'): string { return $this->avoidMutation() ->utc() ->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision).'\Z'); } /** * Format the instance as RFC850 * * @example * ``` * echo Carbon::now()->toRfc850String(); * ``` */ public function toRfc850String(): string { return $this->rawFormat(DateTimeInterface::RFC850); } /** * Format the instance as RFC1036 * * @example * ``` * echo Carbon::now()->toRfc1036String(); * ``` */ public function toRfc1036String(): string { return $this->rawFormat(DateTimeInterface::RFC1036); } /** * Format the instance as RFC1123 * * @example * ``` * echo Carbon::now()->toRfc1123String(); * ``` */ public function toRfc1123String(): string { return $this->rawFormat(DateTimeInterface::RFC1123); } /** * Format the instance as RFC2822 * * @example * ``` * echo Carbon::now()->toRfc2822String(); * ``` */ public function toRfc2822String(): string { return $this->rawFormat(DateTimeInterface::RFC2822); } /** * Format the instance as RFC3339. * * @example * ``` * echo Carbon::now()->toRfc3339String() . "\n"; * echo Carbon::now()->toRfc3339String(true) . "\n"; * ``` */ public function toRfc3339String(bool $extended = false): string { return $this->rawFormat($extended ? DateTimeInterface::RFC3339_EXTENDED : DateTimeInterface::RFC3339); } /** * Format the instance as RSS * * @example * ``` * echo Carbon::now()->toRssString(); * ``` */ public function toRssString(): string { return $this->rawFormat(DateTimeInterface::RSS); } /** * Format the instance as W3C * * @example * ``` * echo Carbon::now()->toW3cString(); * ``` */ public function toW3cString(): string { return $this->rawFormat(DateTimeInterface::W3C); } /** * Format the instance as RFC7231 * * @example * ``` * echo Carbon::now()->toRfc7231String(); * ``` */ public function toRfc7231String(): string { return $this->avoidMutation() ->setTimezone('GMT') ->rawFormat(\defined('static::RFC7231_FORMAT') ? static::RFC7231_FORMAT : CarbonInterface::RFC7231_FORMAT); } /** * Get default array representation. * * @example * ``` * var_dump(Carbon::now()->toArray()); * ``` */ public function toArray(): array { return [ 'year' => $this->year, 'month' => $this->month, 'day' => $this->day, 'dayOfWeek' => $this->dayOfWeek, 'dayOfYear' => $this->dayOfYear, 'hour' => $this->hour, 'minute' => $this->minute, 'second' => $this->second, 'micro' => $this->micro, 'timestamp' => $this->timestamp, 'formatted' => $this->rawFormat(\defined('static::DEFAULT_TO_STRING_FORMAT') ? static::DEFAULT_TO_STRING_FORMAT : CarbonInterface::DEFAULT_TO_STRING_FORMAT), 'timezone' => $this->timezone, ]; } /** * Get default object representation. * * @example * ``` * var_dump(Carbon::now()->toObject()); * ``` */ public function toObject(): object { return (object) $this->toArray(); } /** * Returns english human-readable complete date string. * * @example * ``` * echo Carbon::now()->toString(); * ``` */ public function toString(): string { return $this->avoidMutation()->locale('en')->isoFormat('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); } /** * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z, if $keepOffset truthy, offset will be kept: * 1977-04-22T01:00:00-05:00). * * @example * ``` * echo Carbon::now('America/Toronto')->toISOString() . "\n"; * echo Carbon::now('America/Toronto')->toISOString(true) . "\n"; * ``` * * @param bool $keepOffset Pass true to keep the date offset. Else forced to UTC. */ public function toISOString(bool $keepOffset = false): ?string { if (!$this->isValid()) { return null; } $yearFormat = $this->year < 0 || $this->year > 9999 ? 'YYYYYY' : 'YYYY'; $timezoneFormat = $keepOffset ? 'Z' : '[Z]'; $date = $keepOffset ? $this : $this->avoidMutation()->utc(); return $date->isoFormat("$yearFormat-MM-DD[T]HH:mm:ss.SSSSSS$timezoneFormat"); } /** * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z) with UTC timezone. * * @example * ``` * echo Carbon::now('America/Toronto')->toJSON(); * ``` */ public function toJSON(): ?string { return $this->toISOString(); } /** * Return native DateTime PHP object matching the current instance. * * @example * ``` * var_dump(Carbon::now()->toDateTime()); * ``` */ public function toDateTime(): DateTime { return DateTime::createFromFormat('U.u', $this->rawFormat('U.u')) ->setTimezone($this->getTimezone()); } /** * Return native toDateTimeImmutable PHP object matching the current instance. * * @example * ``` * var_dump(Carbon::now()->toDateTimeImmutable()); * ``` */ public function toDateTimeImmutable(): DateTimeImmutable { return DateTimeImmutable::createFromFormat('U.u', $this->rawFormat('U.u')) ->setTimezone($this->getTimezone()); } /** * @alias toDateTime * * Return native DateTime PHP object matching the current instance. * * @example * ``` * var_dump(Carbon::now()->toDate()); * ``` */ public function toDate(): DateTime { return $this->toDateTime(); } /** * Create a iterable CarbonPeriod object from current date to a given end date (and optional interval). * * @param \DateTimeInterface|Carbon|CarbonImmutable|int|null $end period end date or recurrences count if int * @param int|\DateInterval|string|null $interval period default interval or number of the given $unit * @param string|null $unit if specified, $interval must be an integer */ public function toPeriod($end = null, $interval = null, $unit = null): CarbonPeriod { if ($unit) { $interval = CarbonInterval::make("$interval ".static::pluralUnit($unit)); } $isDefaultInterval = !$interval; $interval ??= CarbonInterval::day(); $class = $this->isMutable() ? CarbonPeriod::class : CarbonPeriodImmutable::class; if (\is_int($end) || (\is_string($end) && ctype_digit($end))) { $end = (int) $end; } $end ??= 1; if (!\is_int($end)) { $end = $this->resolveCarbon($end); } return new $class( raw: [$this, CarbonInterval::make($interval), $end], dateClass: static::class, isDefaultInterval: $isDefaultInterval, ); } /** * Create a iterable CarbonPeriod object from current date to a given end date (and optional interval). * * @param \DateTimeInterface|Carbon|CarbonImmutable|null $end period end date * @param int|\DateInterval|string|null $interval period default interval or number of the given $unit * @param string|null $unit if specified, $interval must be an integer */ public function range($end = null, $interval = null, $unit = null): CarbonPeriod { return $this->toPeriod($end, $interval, $unit); } }
PHP
{ "end_line": 402, "name": "toArray", "signature": "public function toArray(): array", "start_line": 386 }
{ "class_name": "Converter", "class_signature": "trait Converter", "namespace": "Carbon\\Traits" }
toISOString
Carbon/src/Carbon/Traits/Converter.php
public function toISOString(bool $keepOffset = false): ?string { if (!$this->isValid()) { return null; } $yearFormat = $this->year < 0 || $this->year > 9999 ? 'YYYYYY' : 'YYYY'; $timezoneFormat = $keepOffset ? 'Z' : '[Z]'; $date = $keepOffset ? $this : $this->avoidMutation()->utc(); return $date->isoFormat("$yearFormat-MM-DD[T]HH:mm:ss.SSSSSS$timezoneFormat"); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Carbon\CarbonPeriodImmutable; use Carbon\Exceptions\UnitException; use Closure; use DateTime; use DateTimeImmutable; use DateTimeInterface; /** * Trait Converter. * * Change date into different string formats and types and * handle the string cast. * * Depends on the following methods: * * @method static copy() */ trait Converter { use ToStringFormat; /** * Returns the formatted date string on success or FALSE on failure. * * @see https://php.net/manual/en/datetime.format.php */ public function format(string $format): string { $function = $this->localFormatFunction ?? $this->getFactory()->getSettings()['formatFunction'] ?? static::$formatFunction; if (!$function) { return $this->rawFormat($format); } if (\is_string($function) && method_exists($this, $function)) { $function = [$this, $function]; } return $function(...\func_get_args()); } /** * @see https://php.net/manual/en/datetime.format.php */ public function rawFormat(string $format): string { return parent::format($format); } /** * Format the instance as a string using the set format * * @example * ``` * echo Carbon::now(); // Carbon instances can be cast to string * ``` */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; return $format instanceof Closure ? $format($this) : $this->rawFormat($format ?: ( \defined('static::DEFAULT_TO_STRING_FORMAT') ? static::DEFAULT_TO_STRING_FORMAT : CarbonInterface::DEFAULT_TO_STRING_FORMAT )); } /** * Format the instance as date * * @example * ``` * echo Carbon::now()->toDateString(); * ``` */ public function toDateString(): string { return $this->rawFormat('Y-m-d'); } /** * Format the instance as a readable date * * @example * ``` * echo Carbon::now()->toFormattedDateString(); * ``` */ public function toFormattedDateString(): string { return $this->rawFormat('M j, Y'); } /** * Format the instance with the day, and a readable date * * @example * ``` * echo Carbon::now()->toFormattedDayDateString(); * ``` */ public function toFormattedDayDateString(): string { return $this->rawFormat('D, M j, Y'); } /** * Format the instance as time * * @example * ``` * echo Carbon::now()->toTimeString(); * ``` */ public function toTimeString(string $unitPrecision = 'second'): string { return $this->rawFormat(static::getTimeFormatByPrecision($unitPrecision)); } /** * Format the instance as date and time * * @example * ``` * echo Carbon::now()->toDateTimeString(); * ``` */ public function toDateTimeString(string $unitPrecision = 'second'): string { return $this->rawFormat('Y-m-d '.static::getTimeFormatByPrecision($unitPrecision)); } /** * Return a format from H:i to H:i:s.u according to given unit precision. * * @param string $unitPrecision "minute", "second", "millisecond" or "microsecond" */ public static function getTimeFormatByPrecision(string $unitPrecision): string { return match (static::singularUnit($unitPrecision)) { 'minute' => 'H:i', 'second' => 'H:i:s', 'm', 'millisecond' => 'H:i:s.v', 'µ', 'microsecond' => 'H:i:s.u', default => throw new UnitException('Precision unit expected among: minute, second, millisecond and microsecond.'), }; } /** * Format the instance as date and time T-separated with no timezone * * @example * ``` * echo Carbon::now()->toDateTimeLocalString(); * echo "\n"; * echo Carbon::now()->toDateTimeLocalString('minute'); // You can specify precision among: minute, second, millisecond and microsecond * ``` */ public function toDateTimeLocalString(string $unitPrecision = 'second'): string { return $this->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision)); } /** * Format the instance with day, date and time * * @example * ``` * echo Carbon::now()->toDayDateTimeString(); * ``` */ public function toDayDateTimeString(): string { return $this->rawFormat('D, M j, Y g:i A'); } /** * Format the instance as ATOM * * @example * ``` * echo Carbon::now()->toAtomString(); * ``` */ public function toAtomString(): string { return $this->rawFormat(DateTime::ATOM); } /** * Format the instance as COOKIE * * @example * ``` * echo Carbon::now()->toCookieString(); * ``` */ public function toCookieString(): string { return $this->rawFormat(DateTimeInterface::COOKIE); } /** * Format the instance as ISO8601 * * @example * ``` * echo Carbon::now()->toIso8601String(); * ``` */ public function toIso8601String(): string { return $this->toAtomString(); } /** * Format the instance as RFC822 * * @example * ``` * echo Carbon::now()->toRfc822String(); * ``` */ public function toRfc822String(): string { return $this->rawFormat(DateTimeInterface::RFC822); } /** * Convert the instance to UTC and return as Zulu ISO8601 * * @example * ``` * echo Carbon::now()->toIso8601ZuluString(); * ``` */ public function toIso8601ZuluString(string $unitPrecision = 'second'): string { return $this->avoidMutation() ->utc() ->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision).'\Z'); } /** * Format the instance as RFC850 * * @example * ``` * echo Carbon::now()->toRfc850String(); * ``` */ public function toRfc850String(): string { return $this->rawFormat(DateTimeInterface::RFC850); } /** * Format the instance as RFC1036 * * @example * ``` * echo Carbon::now()->toRfc1036String(); * ``` */ public function toRfc1036String(): string { return $this->rawFormat(DateTimeInterface::RFC1036); } /** * Format the instance as RFC1123 * * @example * ``` * echo Carbon::now()->toRfc1123String(); * ``` */ public function toRfc1123String(): string { return $this->rawFormat(DateTimeInterface::RFC1123); } /** * Format the instance as RFC2822 * * @example * ``` * echo Carbon::now()->toRfc2822String(); * ``` */ public function toRfc2822String(): string { return $this->rawFormat(DateTimeInterface::RFC2822); } /** * Format the instance as RFC3339. * * @example * ``` * echo Carbon::now()->toRfc3339String() . "\n"; * echo Carbon::now()->toRfc3339String(true) . "\n"; * ``` */ public function toRfc3339String(bool $extended = false): string { return $this->rawFormat($extended ? DateTimeInterface::RFC3339_EXTENDED : DateTimeInterface::RFC3339); } /** * Format the instance as RSS * * @example * ``` * echo Carbon::now()->toRssString(); * ``` */ public function toRssString(): string { return $this->rawFormat(DateTimeInterface::RSS); } /** * Format the instance as W3C * * @example * ``` * echo Carbon::now()->toW3cString(); * ``` */ public function toW3cString(): string { return $this->rawFormat(DateTimeInterface::W3C); } /** * Format the instance as RFC7231 * * @example * ``` * echo Carbon::now()->toRfc7231String(); * ``` */ public function toRfc7231String(): string { return $this->avoidMutation() ->setTimezone('GMT') ->rawFormat(\defined('static::RFC7231_FORMAT') ? static::RFC7231_FORMAT : CarbonInterface::RFC7231_FORMAT); } /** * Get default array representation. * * @example * ``` * var_dump(Carbon::now()->toArray()); * ``` */ public function toArray(): array { return [ 'year' => $this->year, 'month' => $this->month, 'day' => $this->day, 'dayOfWeek' => $this->dayOfWeek, 'dayOfYear' => $this->dayOfYear, 'hour' => $this->hour, 'minute' => $this->minute, 'second' => $this->second, 'micro' => $this->micro, 'timestamp' => $this->timestamp, 'formatted' => $this->rawFormat(\defined('static::DEFAULT_TO_STRING_FORMAT') ? static::DEFAULT_TO_STRING_FORMAT : CarbonInterface::DEFAULT_TO_STRING_FORMAT), 'timezone' => $this->timezone, ]; } /** * Get default object representation. * * @example * ``` * var_dump(Carbon::now()->toObject()); * ``` */ public function toObject(): object { return (object) $this->toArray(); } /** * Returns english human-readable complete date string. * * @example * ``` * echo Carbon::now()->toString(); * ``` */ public function toString(): string { return $this->avoidMutation()->locale('en')->isoFormat('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); } /** * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z, if $keepOffset truthy, offset will be kept: * 1977-04-22T01:00:00-05:00). * * @example * ``` * echo Carbon::now('America/Toronto')->toISOString() . "\n"; * echo Carbon::now('America/Toronto')->toISOString(true) . "\n"; * ``` * * @param bool $keepOffset Pass true to keep the date offset. Else forced to UTC. */ public function toISOString(bool $keepOffset = false): ?string { if (!$this->isValid()) { return null; } $yearFormat = $this->year < 0 || $this->year > 9999 ? 'YYYYYY' : 'YYYY'; $timezoneFormat = $keepOffset ? 'Z' : '[Z]'; $date = $keepOffset ? $this : $this->avoidMutation()->utc(); return $date->isoFormat("$yearFormat-MM-DD[T]HH:mm:ss.SSSSSS$timezoneFormat"); } /** * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z) with UTC timezone. * * @example * ``` * echo Carbon::now('America/Toronto')->toJSON(); * ``` */ public function toJSON(): ?string { return $this->toISOString(); } /** * Return native DateTime PHP object matching the current instance. * * @example * ``` * var_dump(Carbon::now()->toDateTime()); * ``` */ public function toDateTime(): DateTime { return DateTime::createFromFormat('U.u', $this->rawFormat('U.u')) ->setTimezone($this->getTimezone()); } /** * Return native toDateTimeImmutable PHP object matching the current instance. * * @example * ``` * var_dump(Carbon::now()->toDateTimeImmutable()); * ``` */ public function toDateTimeImmutable(): DateTimeImmutable { return DateTimeImmutable::createFromFormat('U.u', $this->rawFormat('U.u')) ->setTimezone($this->getTimezone()); } /** * @alias toDateTime * * Return native DateTime PHP object matching the current instance. * * @example * ``` * var_dump(Carbon::now()->toDate()); * ``` */ public function toDate(): DateTime { return $this->toDateTime(); } /** * Create a iterable CarbonPeriod object from current date to a given end date (and optional interval). * * @param \DateTimeInterface|Carbon|CarbonImmutable|int|null $end period end date or recurrences count if int * @param int|\DateInterval|string|null $interval period default interval or number of the given $unit * @param string|null $unit if specified, $interval must be an integer */ public function toPeriod($end = null, $interval = null, $unit = null): CarbonPeriod { if ($unit) { $interval = CarbonInterval::make("$interval ".static::pluralUnit($unit)); } $isDefaultInterval = !$interval; $interval ??= CarbonInterval::day(); $class = $this->isMutable() ? CarbonPeriod::class : CarbonPeriodImmutable::class; if (\is_int($end) || (\is_string($end) && ctype_digit($end))) { $end = (int) $end; } $end ??= 1; if (!\is_int($end)) { $end = $this->resolveCarbon($end); } return new $class( raw: [$this, CarbonInterval::make($interval), $end], dateClass: static::class, isDefaultInterval: $isDefaultInterval, ); } /** * Create a iterable CarbonPeriod object from current date to a given end date (and optional interval). * * @param \DateTimeInterface|Carbon|CarbonImmutable|null $end period end date * @param int|\DateInterval|string|null $interval period default interval or number of the given $unit * @param string|null $unit if specified, $interval must be an integer */ public function range($end = null, $interval = null, $unit = null): CarbonPeriod { return $this->toPeriod($end, $interval, $unit); } }
PHP
{ "end_line": 453, "name": "toISOString", "signature": "public function toISOString(bool $keepOffset = false): ?string", "start_line": 442 }
{ "class_name": "Converter", "class_signature": "trait Converter", "namespace": "Carbon\\Traits" }
toPeriod
Carbon/src/Carbon/Traits/Converter.php
public function toPeriod($end = null, $interval = null, $unit = null): CarbonPeriod { if ($unit) { $interval = CarbonInterval::make("$interval ".static::pluralUnit($unit)); } $isDefaultInterval = !$interval; $interval ??= CarbonInterval::day(); $class = $this->isMutable() ? CarbonPeriod::class : CarbonPeriodImmutable::class; if (\is_int($end) || (\is_string($end) && ctype_digit($end))) { $end = (int) $end; } $end ??= 1; if (!\is_int($end)) { $end = $this->resolveCarbon($end); } return new $class( raw: [$this, CarbonInterval::make($interval), $end], dateClass: static::class, isDefaultInterval: $isDefaultInterval, ); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Carbon\CarbonPeriodImmutable; use Carbon\Exceptions\UnitException; use Closure; use DateTime; use DateTimeImmutable; use DateTimeInterface; /** * Trait Converter. * * Change date into different string formats and types and * handle the string cast. * * Depends on the following methods: * * @method static copy() */ trait Converter { use ToStringFormat; /** * Returns the formatted date string on success or FALSE on failure. * * @see https://php.net/manual/en/datetime.format.php */ public function format(string $format): string { $function = $this->localFormatFunction ?? $this->getFactory()->getSettings()['formatFunction'] ?? static::$formatFunction; if (!$function) { return $this->rawFormat($format); } if (\is_string($function) && method_exists($this, $function)) { $function = [$this, $function]; } return $function(...\func_get_args()); } /** * @see https://php.net/manual/en/datetime.format.php */ public function rawFormat(string $format): string { return parent::format($format); } /** * Format the instance as a string using the set format * * @example * ``` * echo Carbon::now(); // Carbon instances can be cast to string * ``` */ public function __toString(): string { $format = $this->localToStringFormat ?? $this->getFactory()->getSettings()['toStringFormat'] ?? null; return $format instanceof Closure ? $format($this) : $this->rawFormat($format ?: ( \defined('static::DEFAULT_TO_STRING_FORMAT') ? static::DEFAULT_TO_STRING_FORMAT : CarbonInterface::DEFAULT_TO_STRING_FORMAT )); } /** * Format the instance as date * * @example * ``` * echo Carbon::now()->toDateString(); * ``` */ public function toDateString(): string { return $this->rawFormat('Y-m-d'); } /** * Format the instance as a readable date * * @example * ``` * echo Carbon::now()->toFormattedDateString(); * ``` */ public function toFormattedDateString(): string { return $this->rawFormat('M j, Y'); } /** * Format the instance with the day, and a readable date * * @example * ``` * echo Carbon::now()->toFormattedDayDateString(); * ``` */ public function toFormattedDayDateString(): string { return $this->rawFormat('D, M j, Y'); } /** * Format the instance as time * * @example * ``` * echo Carbon::now()->toTimeString(); * ``` */ public function toTimeString(string $unitPrecision = 'second'): string { return $this->rawFormat(static::getTimeFormatByPrecision($unitPrecision)); } /** * Format the instance as date and time * * @example * ``` * echo Carbon::now()->toDateTimeString(); * ``` */ public function toDateTimeString(string $unitPrecision = 'second'): string { return $this->rawFormat('Y-m-d '.static::getTimeFormatByPrecision($unitPrecision)); } /** * Return a format from H:i to H:i:s.u according to given unit precision. * * @param string $unitPrecision "minute", "second", "millisecond" or "microsecond" */ public static function getTimeFormatByPrecision(string $unitPrecision): string { return match (static::singularUnit($unitPrecision)) { 'minute' => 'H:i', 'second' => 'H:i:s', 'm', 'millisecond' => 'H:i:s.v', 'µ', 'microsecond' => 'H:i:s.u', default => throw new UnitException('Precision unit expected among: minute, second, millisecond and microsecond.'), }; } /** * Format the instance as date and time T-separated with no timezone * * @example * ``` * echo Carbon::now()->toDateTimeLocalString(); * echo "\n"; * echo Carbon::now()->toDateTimeLocalString('minute'); // You can specify precision among: minute, second, millisecond and microsecond * ``` */ public function toDateTimeLocalString(string $unitPrecision = 'second'): string { return $this->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision)); } /** * Format the instance with day, date and time * * @example * ``` * echo Carbon::now()->toDayDateTimeString(); * ``` */ public function toDayDateTimeString(): string { return $this->rawFormat('D, M j, Y g:i A'); } /** * Format the instance as ATOM * * @example * ``` * echo Carbon::now()->toAtomString(); * ``` */ public function toAtomString(): string { return $this->rawFormat(DateTime::ATOM); } /** * Format the instance as COOKIE * * @example * ``` * echo Carbon::now()->toCookieString(); * ``` */ public function toCookieString(): string { return $this->rawFormat(DateTimeInterface::COOKIE); } /** * Format the instance as ISO8601 * * @example * ``` * echo Carbon::now()->toIso8601String(); * ``` */ public function toIso8601String(): string { return $this->toAtomString(); } /** * Format the instance as RFC822 * * @example * ``` * echo Carbon::now()->toRfc822String(); * ``` */ public function toRfc822String(): string { return $this->rawFormat(DateTimeInterface::RFC822); } /** * Convert the instance to UTC and return as Zulu ISO8601 * * @example * ``` * echo Carbon::now()->toIso8601ZuluString(); * ``` */ public function toIso8601ZuluString(string $unitPrecision = 'second'): string { return $this->avoidMutation() ->utc() ->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision).'\Z'); } /** * Format the instance as RFC850 * * @example * ``` * echo Carbon::now()->toRfc850String(); * ``` */ public function toRfc850String(): string { return $this->rawFormat(DateTimeInterface::RFC850); } /** * Format the instance as RFC1036 * * @example * ``` * echo Carbon::now()->toRfc1036String(); * ``` */ public function toRfc1036String(): string { return $this->rawFormat(DateTimeInterface::RFC1036); } /** * Format the instance as RFC1123 * * @example * ``` * echo Carbon::now()->toRfc1123String(); * ``` */ public function toRfc1123String(): string { return $this->rawFormat(DateTimeInterface::RFC1123); } /** * Format the instance as RFC2822 * * @example * ``` * echo Carbon::now()->toRfc2822String(); * ``` */ public function toRfc2822String(): string { return $this->rawFormat(DateTimeInterface::RFC2822); } /** * Format the instance as RFC3339. * * @example * ``` * echo Carbon::now()->toRfc3339String() . "\n"; * echo Carbon::now()->toRfc3339String(true) . "\n"; * ``` */ public function toRfc3339String(bool $extended = false): string { return $this->rawFormat($extended ? DateTimeInterface::RFC3339_EXTENDED : DateTimeInterface::RFC3339); } /** * Format the instance as RSS * * @example * ``` * echo Carbon::now()->toRssString(); * ``` */ public function toRssString(): string { return $this->rawFormat(DateTimeInterface::RSS); } /** * Format the instance as W3C * * @example * ``` * echo Carbon::now()->toW3cString(); * ``` */ public function toW3cString(): string { return $this->rawFormat(DateTimeInterface::W3C); } /** * Format the instance as RFC7231 * * @example * ``` * echo Carbon::now()->toRfc7231String(); * ``` */ public function toRfc7231String(): string { return $this->avoidMutation() ->setTimezone('GMT') ->rawFormat(\defined('static::RFC7231_FORMAT') ? static::RFC7231_FORMAT : CarbonInterface::RFC7231_FORMAT); } /** * Get default array representation. * * @example * ``` * var_dump(Carbon::now()->toArray()); * ``` */ public function toArray(): array { return [ 'year' => $this->year, 'month' => $this->month, 'day' => $this->day, 'dayOfWeek' => $this->dayOfWeek, 'dayOfYear' => $this->dayOfYear, 'hour' => $this->hour, 'minute' => $this->minute, 'second' => $this->second, 'micro' => $this->micro, 'timestamp' => $this->timestamp, 'formatted' => $this->rawFormat(\defined('static::DEFAULT_TO_STRING_FORMAT') ? static::DEFAULT_TO_STRING_FORMAT : CarbonInterface::DEFAULT_TO_STRING_FORMAT), 'timezone' => $this->timezone, ]; } /** * Get default object representation. * * @example * ``` * var_dump(Carbon::now()->toObject()); * ``` */ public function toObject(): object { return (object) $this->toArray(); } /** * Returns english human-readable complete date string. * * @example * ``` * echo Carbon::now()->toString(); * ``` */ public function toString(): string { return $this->avoidMutation()->locale('en')->isoFormat('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); } /** * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z, if $keepOffset truthy, offset will be kept: * 1977-04-22T01:00:00-05:00). * * @example * ``` * echo Carbon::now('America/Toronto')->toISOString() . "\n"; * echo Carbon::now('America/Toronto')->toISOString(true) . "\n"; * ``` * * @param bool $keepOffset Pass true to keep the date offset. Else forced to UTC. */ public function toISOString(bool $keepOffset = false): ?string { if (!$this->isValid()) { return null; } $yearFormat = $this->year < 0 || $this->year > 9999 ? 'YYYYYY' : 'YYYY'; $timezoneFormat = $keepOffset ? 'Z' : '[Z]'; $date = $keepOffset ? $this : $this->avoidMutation()->utc(); return $date->isoFormat("$yearFormat-MM-DD[T]HH:mm:ss.SSSSSS$timezoneFormat"); } /** * Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z) with UTC timezone. * * @example * ``` * echo Carbon::now('America/Toronto')->toJSON(); * ``` */ public function toJSON(): ?string { return $this->toISOString(); } /** * Return native DateTime PHP object matching the current instance. * * @example * ``` * var_dump(Carbon::now()->toDateTime()); * ``` */ public function toDateTime(): DateTime { return DateTime::createFromFormat('U.u', $this->rawFormat('U.u')) ->setTimezone($this->getTimezone()); } /** * Return native toDateTimeImmutable PHP object matching the current instance. * * @example * ``` * var_dump(Carbon::now()->toDateTimeImmutable()); * ``` */ public function toDateTimeImmutable(): DateTimeImmutable { return DateTimeImmutable::createFromFormat('U.u', $this->rawFormat('U.u')) ->setTimezone($this->getTimezone()); } /** * @alias toDateTime * * Return native DateTime PHP object matching the current instance. * * @example * ``` * var_dump(Carbon::now()->toDate()); * ``` */ public function toDate(): DateTime { return $this->toDateTime(); } /** * Create a iterable CarbonPeriod object from current date to a given end date (and optional interval). * * @param \DateTimeInterface|Carbon|CarbonImmutable|int|null $end period end date or recurrences count if int * @param int|\DateInterval|string|null $interval period default interval or number of the given $unit * @param string|null $unit if specified, $interval must be an integer */ public function toPeriod($end = null, $interval = null, $unit = null): CarbonPeriod { if ($unit) { $interval = CarbonInterval::make("$interval ".static::pluralUnit($unit)); } $isDefaultInterval = !$interval; $interval ??= CarbonInterval::day(); $class = $this->isMutable() ? CarbonPeriod::class : CarbonPeriodImmutable::class; if (\is_int($end) || (\is_string($end) && ctype_digit($end))) { $end = (int) $end; } $end ??= 1; if (!\is_int($end)) { $end = $this->resolveCarbon($end); } return new $class( raw: [$this, CarbonInterval::make($interval), $end], dateClass: static::class, isDefaultInterval: $isDefaultInterval, ); } /** * Create a iterable CarbonPeriod object from current date to a given end date (and optional interval). * * @param \DateTimeInterface|Carbon|CarbonImmutable|null $end period end date * @param int|\DateInterval|string|null $interval period default interval or number of the given $unit * @param string|null $unit if specified, $interval must be an integer */ public function range($end = null, $interval = null, $unit = null): CarbonPeriod { return $this->toPeriod($end, $interval, $unit); } }
PHP
{ "end_line": 543, "name": "toPeriod", "signature": "public function toPeriod($end = null, $interval = null, $unit = null): CarbonPeriod", "start_line": 518 }
{ "class_name": "Converter", "class_signature": "trait Converter", "namespace": "Carbon\\Traits" }
instance
Carbon/src/Carbon/Traits/Creator.php
public static function instance(DateTimeInterface $date): static { if ($date instanceof static) { return clone $date; } $instance = parent::createFromFormat('U.u', $date->format('U.u')) ->setTimezone($date->getTimezone()); if ($date instanceof CarbonInterface) { $settings = $date->getSettings(); if (!$date->hasLocalTranslator()) { unset($settings['locale']); } $instance->settings($settings); } return $instance; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\UnitException; use Carbon\Month; use Carbon\Translator; use Carbon\WeekDay; use Closure; use DateMalformedStringException; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Exception; use ReturnTypeWillChange; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Creator. * * Static creators. * * Depends on the following methods: * * @method static Carbon|CarbonImmutable getTestNow() */ trait Creator { use ObjectInitialisation; use LocalFactory; /** * The errors that can occur. */ protected static array|bool $lastErrors = false; /** * Create a new Carbon instance. * * Please see the testing aids section (specifically static::setTestNow()) * for more on the possibility of this constructor returning a test instance. * * @throws InvalidFormatException */ public function __construct( DateTimeInterface|WeekDay|Month|string|int|float|null $time = null, DateTimeZone|string|int|null $timezone = null, ) { $this->initLocalFactory(); if ($time instanceof Month) { $time = $time->name.' 1'; } elseif ($time instanceof WeekDay) { $time = $time->name; } elseif ($time instanceof DateTimeInterface) { $time = $this->constructTimezoneFromDateTime($time, $timezone)->format('Y-m-d H:i:s.u'); } if (\is_string($time) && str_starts_with($time, '@')) { $time = static::createFromTimestampUTC(substr($time, 1))->format('Y-m-d\TH:i:s.uP'); } elseif (is_numeric($time) && (!\is_string($time) || !preg_match('/^\d{1,14}$/', $time))) { $time = static::createFromTimestampUTC($time)->format('Y-m-d\TH:i:s.uP'); } // If the class has a test now set, and we are trying to create a now() // instance then override as required $isNow = \in_array($time, [null, '', 'now'], true); $timezone = static::safeCreateDateTimeZone($timezone) ?? null; if ( ($this->clock || ( method_exists(static::class, 'hasTestNow') && method_exists(static::class, 'getTestNow') && static::hasTestNow() )) && ($isNow || static::hasRelativeKeywords($time)) ) { $this->mockConstructorParameters($time, $timezone); } try { parent::__construct($time ?? 'now', $timezone); } catch (Exception $exception) { throw new InvalidFormatException($exception->getMessage(), 0, $exception); } $this->constructedObjectId = spl_object_hash($this); self::setLastErrors(parent::getLastErrors()); } /** * Get timezone from a datetime instance. */ private function constructTimezoneFromDateTime( DateTimeInterface $date, DateTimeZone|string|int|null &$timezone, ): DateTimeInterface { if ($timezone !== null) { $safeTz = static::safeCreateDateTimeZone($timezone); if ($safeTz) { $date = ($date instanceof DateTimeImmutable ? $date : clone $date)->setTimezone($safeTz); } return $date; } $timezone = $date->getTimezone(); return $date; } /** * Update constructedObjectId on cloned. */ public function __clone(): void { $this->constructedObjectId = spl_object_hash($this); } /** * Create a Carbon instance from a DateTime one. */ public static function instance(DateTimeInterface $date): static { if ($date instanceof static) { return clone $date; } $instance = parent::createFromFormat('U.u', $date->format('U.u')) ->setTimezone($date->getTimezone()); if ($date instanceof CarbonInterface) { $settings = $date->getSettings(); if (!$date->hasLocalTranslator()) { unset($settings['locale']); } $instance->settings($settings); } return $instance; } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function rawParse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { if ($time instanceof DateTimeInterface) { return static::instance($time); } try { return new static($time, $timezone); } catch (Exception $exception) { // @codeCoverageIgnoreStart try { $date = @static::now($timezone)->change($time); } catch (DateMalformedStringException|InvalidFormatException) { $date = null; } // @codeCoverageIgnoreEnd return $date ?? throw new InvalidFormatException("Could not parse '$time': ".$exception->getMessage(), 0, $exception); } } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function parse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { $function = static::$parseFunction; if (!$function) { return static::rawParse($time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.). * * @param string $time date/time string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be * used instead. * @param DateTimeZone|string|int|null $timezone optional timezone for the new instance. * * @throws InvalidFormatException */ public static function parseFromLocale( string $time, ?string $locale = null, DateTimeZone|string|int|null $timezone = null, ): static { return static::rawParse(static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Get a Carbon instance for the current date and time. */ public static function now(DateTimeZone|string|int|null $timezone = null): static { return new static(null, $timezone); } /** * Create a Carbon instance for today. */ public static function today(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('today', $timezone); } /** * Create a Carbon instance for tomorrow. */ public static function tomorrow(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('tomorrow', $timezone); } /** * Create a Carbon instance for yesterday. */ public static function yesterday(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('yesterday', $timezone); } private static function assertBetween($unit, $value, $min, $max): void { if (static::isStrictModeEnabled() && ($value < $min || $value > $max)) { throw new OutOfRangeException($unit, $min, $max, $value); } } private static function createNowInstance($timezone) { if (!static::hasTestNow()) { return static::now($timezone); } $now = static::getTestNow(); if ($now instanceof Closure) { return $now(static::now($timezone)); } $now = $now->avoidMutation(); return $timezone === null ? $now : $now->setTimezone($timezone); } /** * Create a new Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * @param DateTimeInterface|string|int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null): ?static { $month = self::monthToInt($month); if ((\is_string($year) && !is_numeric($year)) || $year instanceof DateTimeInterface) { return static::parse($year, $timezone ?? (\is_string($month) || $month instanceof DateTimeZone ? $month : null)); } $defaults = null; $getDefault = function ($unit) use ($timezone, &$defaults) { if ($defaults === null) { $now = self::createNowInstance($timezone); $defaults = array_combine([ 'year', 'month', 'day', 'hour', 'minute', 'second', ], explode('-', $now->rawFormat('Y-n-j-G-i-s.u'))); } return $defaults[$unit]; }; $year = $year ?? $getDefault('year'); $month = $month ?? $getDefault('month'); $day = $day ?? $getDefault('day'); $hour = $hour ?? $getDefault('hour'); $minute = $minute ?? $getDefault('minute'); $second = (float) ($second ?? $getDefault('second')); self::assertBetween('month', $month, 0, 99); self::assertBetween('day', $day, 0, 99); self::assertBetween('hour', $hour, 0, 99); self::assertBetween('minute', $minute, 0, 99); self::assertBetween('second', $second, 0, 99); $fixYear = null; if ($year < 0) { $fixYear = $year; $year = 0; } elseif ($year > 9999) { $fixYear = $year - 9999; $year = 9999; } $second = ($second < 10 ? '0' : '').number_format($second, 6); $instance = static::rawCreateFromFormat('!Y-n-j G:i:s.u', \sprintf('%s-%s-%s %s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $timezone); if ($instance && $fixYear !== null) { $instance = $instance->addYears($fixYear); } return $instance ?? null; } /** * Create a new safe Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * If one of the set values is not valid, an InvalidDateException * will be thrown. * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidDateException * * @return static|null */ public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null): ?static { $month = self::monthToInt($month); $fields = static::getRangesByUnit(); foreach ($fields as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field < $range[0] || $$field > $range[1])) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } $instance = static::create($year, $month, $day, $hour, $minute, $second, $timezone); foreach (array_reverse($fields) as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field !== $instance->$field)) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } return $instance; } /** * Create a new Carbon instance from a specific date and time using strict validation. * * @see create() * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $timezone = null): static { $initialStrictMode = static::isStrictModeEnabled(); static::useStrictMode(true); try { $date = static::create($year, $month, $day, $hour, $minute, $second, $timezone); } finally { static::useStrictMode($initialStrictMode); } return $date; } /** * Create a Carbon instance from just a date. The time portion is set to now. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, null, null, null, $timezone); } /** * Create a Carbon instance from just a date. The time portion is set to midnight. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createMidnightDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, 0, 0, 0, $timezone); } /** * Create a Carbon instance from just a time. The date portion is set to today. * * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromTime($hour = 0, $minute = 0, $second = 0, $timezone = null): static { return static::create(null, null, null, $hour, $minute, $second, $timezone); } /** * Create a Carbon instance from a time string. The date portion is set to today. * * @throws InvalidFormatException */ public static function createFromTimeString(string $time, DateTimeZone|string|int|null $timezone = null): static { return static::today($timezone)->setTimeFromTimeString($time); } private static function createFromFormatAndTimezone( string $format, string $time, DateTimeZone|string|int|null $originalTimezone, ): ?DateTimeInterface { if ($originalTimezone === null) { return parent::createFromFormat($format, $time) ?: null; } $timezone = \is_int($originalTimezone) ? self::getOffsetTimezone($originalTimezone) : $originalTimezone; $timezone = static::safeCreateDateTimeZone($timezone, $originalTimezone); return parent::createFromFormat($format, $time, $timezone) ?: null; } private static function getOffsetTimezone(int $offset): string { $minutes = (int) ($offset * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE); return @timezone_name_from_abbr('', $minutes, 1) ?: throw new InvalidTimeZoneException( "Invalid offset timezone $offset", ); } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function rawCreateFromFormat(string $format, string $time, $timezone = null): ?static { // Work-around for https://bugs.php.net/bug.php?id=80141 $format = preg_replace('/(?<!\\\\)((?:\\\\{2})*)c/', '$1Y-m-d\TH:i:sP', $format); if (preg_match('/(?<!\\\\)(?:\\\\{2})*(a|A)/', $format, $aMatches, PREG_OFFSET_CAPTURE) && preg_match('/(?<!\\\\)(?:\\\\{2})*(h|g|H|G)/', $format, $hMatches, PREG_OFFSET_CAPTURE) && $aMatches[1][1] < $hMatches[1][1] && preg_match('/(am|pm|AM|PM)/', $time) ) { $format = preg_replace('/^(.*)(?<!\\\\)((?:\\\\{2})*)(a|A)(.*)$/U', '$1$2$4 $3', $format); $time = preg_replace('/^(.*)(am|pm|AM|PM)(.*)$/U', '$1$3 $2', $time); } if ($timezone === false) { $timezone = null; } // First attempt to create an instance, so that error messages are based on the unmodified format. $date = self::createFromFormatAndTimezone($format, $time, $timezone); $lastErrors = parent::getLastErrors(); /** @var \Carbon\CarbonImmutable|\Carbon\Carbon|null $mock */ $mock = static::getMockedTestNow($timezone); if ($mock && $date instanceof DateTimeInterface) { // Set timezone from mock if custom timezone was neither given directly nor as a part of format. // First let's skip the part that will be ignored by the parser. $nonEscaped = '(?<!\\\\)(\\\\{2})*'; $nonIgnored = preg_replace("/^.*{$nonEscaped}!/s", '', $format); if ($timezone === null && !preg_match("/{$nonEscaped}[eOPT]/", $nonIgnored)) { $timezone = clone $mock->getTimezone(); } $mock = $mock->copy(); // Prepend mock datetime only if the format does not contain non escaped unix epoch reset flag. if (!preg_match("/{$nonEscaped}[!|]/", $format)) { if (preg_match('/[HhGgisvuB]/', $format)) { $mock = $mock->setTime(0, 0); } $format = static::MOCK_DATETIME_FORMAT.' '.$format; $time = ($mock instanceof self ? $mock->rawFormat(static::MOCK_DATETIME_FORMAT) : $mock->format(static::MOCK_DATETIME_FORMAT)).' '.$time; } // Regenerate date from the modified format to base result on the mocked instance instead of now. $date = self::createFromFormatAndTimezone($format, $time, $timezone); } if ($date instanceof DateTimeInterface) { $instance = static::instance($date); $instance::setLastErrors($lastErrors); return $instance; } if (static::isStrictModeEnabled()) { throw new InvalidFormatException(implode(PHP_EOL, (array) $lastErrors['errors'])); } return null; } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ #[ReturnTypeWillChange] public static function createFromFormat($format, $time, $timezone = null): ?static { $function = static::$createFromFormatFunction; // format is a single numeric unit if (\is_int($time) && \in_array(ltrim($format, '!'), ['U', 'Y', 'y', 'X', 'x', 'm', 'n', 'd', 'j', 'w', 'W', 'H', 'h', 'G', 'g', 'i', 's', 'u', 'z', 'v'], true)) { $time = (string) $time; } if (!\is_string($time)) { @trigger_error( 'createFromFormat() $time parameter will only accept string or integer for 1-letter format representing a numeric unit in the next version', \E_USER_DEPRECATED, ); $time = (string) $time; } if (!$function) { return static::rawCreateFromFormat($format, $time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()). * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone optional timezone * @param string|null $locale locale to be used for LTS, LT, LL, LLL, etc. macro-formats (en by fault, unneeded if no such macro-format in use) * @param TranslatorInterface|null $translator optional custom translator to use for macro-formats * * @throws InvalidFormatException * * @return static|null */ public static function createFromIsoFormat( string $format, string $time, $timezone = null, ?string $locale = CarbonInterface::DEFAULT_LOCALE, ?TranslatorInterface $translator = null ): ?static { $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*(LTS|LT|[Ll]{1,4})/', function ($match) use ($locale, $translator) { [$code] = $match; static $formats = null; if ($formats === null) { $translator ??= Translator::get($locale); $formats = [ 'LT' => static::getTranslationMessageWith($translator, 'formats.LT', $locale), 'LTS' => static::getTranslationMessageWith($translator, 'formats.LTS', $locale), 'L' => static::getTranslationMessageWith($translator, 'formats.L', $locale), 'LL' => static::getTranslationMessageWith($translator, 'formats.LL', $locale), 'LLL' => static::getTranslationMessageWith($translator, 'formats.LLL', $locale), 'LLLL' => static::getTranslationMessageWith($translator, 'formats.LLLL', $locale), ]; } return $formats[$code] ?? preg_replace_callback( '/MMMM|MM|DD|dddd/', static fn (array $code) => mb_substr($code[0], 1), $formats[strtoupper($code)] ?? '', ); }, $format); $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*('.CarbonInterface::ISO_FORMAT_REGEXP.'|[A-Za-z])/', function ($match) { [$code] = $match; static $replacements = null; if ($replacements === null) { $replacements = [ 'OD' => 'd', 'OM' => 'M', 'OY' => 'Y', 'OH' => 'G', 'Oh' => 'g', 'Om' => 'i', 'Os' => 's', 'D' => 'd', 'DD' => 'd', 'Do' => 'd', 'd' => '!', 'dd' => '!', 'ddd' => 'D', 'dddd' => 'D', 'DDD' => 'z', 'DDDD' => 'z', 'DDDo' => 'z', 'e' => '!', 'E' => '!', 'H' => 'G', 'HH' => 'H', 'h' => 'g', 'hh' => 'h', 'k' => 'G', 'kk' => 'G', 'hmm' => 'gi', 'hmmss' => 'gis', 'Hmm' => 'Gi', 'Hmmss' => 'Gis', 'm' => 'i', 'mm' => 'i', 'a' => 'a', 'A' => 'a', 's' => 's', 'ss' => 's', 'S' => '*', 'SS' => '*', 'SSS' => '*', 'SSSS' => '*', 'SSSSS' => '*', 'SSSSSS' => 'u', 'SSSSSSS' => 'u*', 'SSSSSSSS' => 'u*', 'SSSSSSSSS' => 'u*', 'M' => 'm', 'MM' => 'm', 'MMM' => 'M', 'MMMM' => 'M', 'Mo' => 'm', 'Q' => '!', 'Qo' => '!', 'G' => '!', 'GG' => '!', 'GGG' => '!', 'GGGG' => '!', 'GGGGG' => '!', 'g' => '!', 'gg' => '!', 'ggg' => '!', 'gggg' => '!', 'ggggg' => '!', 'W' => '!', 'WW' => '!', 'Wo' => '!', 'w' => '!', 'ww' => '!', 'wo' => '!', 'x' => 'U???', 'X' => 'U', 'Y' => 'Y', 'YY' => 'y', 'YYYY' => 'Y', 'YYYYY' => 'Y', 'YYYYYY' => 'Y', 'z' => 'e', 'zz' => 'e', 'Z' => 'e', 'ZZ' => 'e', ]; } $format = $replacements[$code] ?? '?'; if ($format === '!') { throw new InvalidFormatException("Format $code not supported for creation."); } return $format; }, $format); return static::rawCreateFromFormat($format, $time, $timezone); } /** * Create a Carbon instance from a specific format and a string in a given language. * * @param string $format Datetime format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null): ?static { $format = preg_replace_callback( '/(?:\\\\[a-zA-Z]|[bfkqCEJKQRV]){2,}/', static function (array $match) use ($locale): string { $word = str_replace('\\', '', $match[0]); $translatedWord = static::translateTimeString($word, $locale, static::DEFAULT_LOCALE); return $word === $translatedWord ? $match[0] : preg_replace('/[a-zA-Z]/', '\\\\$0', $translatedWord); }, $format ); return static::rawCreateFromFormat($format, static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Create a Carbon instance from a specific ISO format and a string in a given language. * * @param string $format Datetime ISO format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleIsoFormat(string $format, string $locale, string $time, $timezone = null): ?static { $time = static::translateTimeString($time, $locale, static::DEFAULT_LOCALE, CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS | CarbonInterface::TRANSLATE_MERIDIEM); return static::createFromIsoFormat($format, $time, $timezone, $locale); } /** * Make a Carbon instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed $var * * @throws InvalidFormatException * * @return static|null */ public static function make($var, DateTimeZone|string|null $timezone = null): ?static { if ($var instanceof DateTimeInterface) { return static::instance($var); } $date = null; if (\is_string($var)) { $var = trim($var); if (!preg_match('/^P[\dT]/', $var) && !preg_match('/^R\d/', $var) && preg_match('/[a-z\d]/i', $var) ) { $date = static::parse($var, $timezone); } } return $date; } /** * Set last errors. * * @param array|bool $lastErrors * * @return void */ private static function setLastErrors($lastErrors): void { static::$lastErrors = $lastErrors; } /** * {@inheritdoc} */ public static function getLastErrors(): array|false { return static::$lastErrors; } private static function monthToInt(mixed $value, string $unit = 'month'): mixed { if ($value instanceof Month) { if ($unit !== 'month') { throw new UnitException("Month enum cannot be used to set $unit"); } return Month::int($value); } return $value; } }
PHP
{ "end_line": 163, "name": "instance", "signature": "public static function instance(DateTimeInterface $date): static", "start_line": 143 }
{ "class_name": "Creator", "class_signature": "trait Creator", "namespace": "Carbon\\Traits" }
rawParse
Carbon/src/Carbon/Traits/Creator.php
public static function rawParse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { if ($time instanceof DateTimeInterface) { return static::instance($time); } try { return new static($time, $timezone); } catch (Exception $exception) { // @codeCoverageIgnoreStart try { $date = @static::now($timezone)->change($time); } catch (DateMalformedStringException|InvalidFormatException) { $date = null; } // @codeCoverageIgnoreEnd return $date ?? throw new InvalidFormatException("Could not parse '$time': ".$exception->getMessage(), 0, $exception); } }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\UnitException; use Carbon\Month; use Carbon\Translator; use Carbon\WeekDay; use Closure; use DateMalformedStringException; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Exception; use ReturnTypeWillChange; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Creator. * * Static creators. * * Depends on the following methods: * * @method static Carbon|CarbonImmutable getTestNow() */ trait Creator { use ObjectInitialisation; use LocalFactory; /** * The errors that can occur. */ protected static array|bool $lastErrors = false; /** * Create a new Carbon instance. * * Please see the testing aids section (specifically static::setTestNow()) * for more on the possibility of this constructor returning a test instance. * * @throws InvalidFormatException */ public function __construct( DateTimeInterface|WeekDay|Month|string|int|float|null $time = null, DateTimeZone|string|int|null $timezone = null, ) { $this->initLocalFactory(); if ($time instanceof Month) { $time = $time->name.' 1'; } elseif ($time instanceof WeekDay) { $time = $time->name; } elseif ($time instanceof DateTimeInterface) { $time = $this->constructTimezoneFromDateTime($time, $timezone)->format('Y-m-d H:i:s.u'); } if (\is_string($time) && str_starts_with($time, '@')) { $time = static::createFromTimestampUTC(substr($time, 1))->format('Y-m-d\TH:i:s.uP'); } elseif (is_numeric($time) && (!\is_string($time) || !preg_match('/^\d{1,14}$/', $time))) { $time = static::createFromTimestampUTC($time)->format('Y-m-d\TH:i:s.uP'); } // If the class has a test now set, and we are trying to create a now() // instance then override as required $isNow = \in_array($time, [null, '', 'now'], true); $timezone = static::safeCreateDateTimeZone($timezone) ?? null; if ( ($this->clock || ( method_exists(static::class, 'hasTestNow') && method_exists(static::class, 'getTestNow') && static::hasTestNow() )) && ($isNow || static::hasRelativeKeywords($time)) ) { $this->mockConstructorParameters($time, $timezone); } try { parent::__construct($time ?? 'now', $timezone); } catch (Exception $exception) { throw new InvalidFormatException($exception->getMessage(), 0, $exception); } $this->constructedObjectId = spl_object_hash($this); self::setLastErrors(parent::getLastErrors()); } /** * Get timezone from a datetime instance. */ private function constructTimezoneFromDateTime( DateTimeInterface $date, DateTimeZone|string|int|null &$timezone, ): DateTimeInterface { if ($timezone !== null) { $safeTz = static::safeCreateDateTimeZone($timezone); if ($safeTz) { $date = ($date instanceof DateTimeImmutable ? $date : clone $date)->setTimezone($safeTz); } return $date; } $timezone = $date->getTimezone(); return $date; } /** * Update constructedObjectId on cloned. */ public function __clone(): void { $this->constructedObjectId = spl_object_hash($this); } /** * Create a Carbon instance from a DateTime one. */ public static function instance(DateTimeInterface $date): static { if ($date instanceof static) { return clone $date; } $instance = parent::createFromFormat('U.u', $date->format('U.u')) ->setTimezone($date->getTimezone()); if ($date instanceof CarbonInterface) { $settings = $date->getSettings(); if (!$date->hasLocalTranslator()) { unset($settings['locale']); } $instance->settings($settings); } return $instance; } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function rawParse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { if ($time instanceof DateTimeInterface) { return static::instance($time); } try { return new static($time, $timezone); } catch (Exception $exception) { // @codeCoverageIgnoreStart try { $date = @static::now($timezone)->change($time); } catch (DateMalformedStringException|InvalidFormatException) { $date = null; } // @codeCoverageIgnoreEnd return $date ?? throw new InvalidFormatException("Could not parse '$time': ".$exception->getMessage(), 0, $exception); } } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function parse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { $function = static::$parseFunction; if (!$function) { return static::rawParse($time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.). * * @param string $time date/time string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be * used instead. * @param DateTimeZone|string|int|null $timezone optional timezone for the new instance. * * @throws InvalidFormatException */ public static function parseFromLocale( string $time, ?string $locale = null, DateTimeZone|string|int|null $timezone = null, ): static { return static::rawParse(static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Get a Carbon instance for the current date and time. */ public static function now(DateTimeZone|string|int|null $timezone = null): static { return new static(null, $timezone); } /** * Create a Carbon instance for today. */ public static function today(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('today', $timezone); } /** * Create a Carbon instance for tomorrow. */ public static function tomorrow(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('tomorrow', $timezone); } /** * Create a Carbon instance for yesterday. */ public static function yesterday(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('yesterday', $timezone); } private static function assertBetween($unit, $value, $min, $max): void { if (static::isStrictModeEnabled() && ($value < $min || $value > $max)) { throw new OutOfRangeException($unit, $min, $max, $value); } } private static function createNowInstance($timezone) { if (!static::hasTestNow()) { return static::now($timezone); } $now = static::getTestNow(); if ($now instanceof Closure) { return $now(static::now($timezone)); } $now = $now->avoidMutation(); return $timezone === null ? $now : $now->setTimezone($timezone); } /** * Create a new Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * @param DateTimeInterface|string|int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null): ?static { $month = self::monthToInt($month); if ((\is_string($year) && !is_numeric($year)) || $year instanceof DateTimeInterface) { return static::parse($year, $timezone ?? (\is_string($month) || $month instanceof DateTimeZone ? $month : null)); } $defaults = null; $getDefault = function ($unit) use ($timezone, &$defaults) { if ($defaults === null) { $now = self::createNowInstance($timezone); $defaults = array_combine([ 'year', 'month', 'day', 'hour', 'minute', 'second', ], explode('-', $now->rawFormat('Y-n-j-G-i-s.u'))); } return $defaults[$unit]; }; $year = $year ?? $getDefault('year'); $month = $month ?? $getDefault('month'); $day = $day ?? $getDefault('day'); $hour = $hour ?? $getDefault('hour'); $minute = $minute ?? $getDefault('minute'); $second = (float) ($second ?? $getDefault('second')); self::assertBetween('month', $month, 0, 99); self::assertBetween('day', $day, 0, 99); self::assertBetween('hour', $hour, 0, 99); self::assertBetween('minute', $minute, 0, 99); self::assertBetween('second', $second, 0, 99); $fixYear = null; if ($year < 0) { $fixYear = $year; $year = 0; } elseif ($year > 9999) { $fixYear = $year - 9999; $year = 9999; } $second = ($second < 10 ? '0' : '').number_format($second, 6); $instance = static::rawCreateFromFormat('!Y-n-j G:i:s.u', \sprintf('%s-%s-%s %s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $timezone); if ($instance && $fixYear !== null) { $instance = $instance->addYears($fixYear); } return $instance ?? null; } /** * Create a new safe Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * If one of the set values is not valid, an InvalidDateException * will be thrown. * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidDateException * * @return static|null */ public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null): ?static { $month = self::monthToInt($month); $fields = static::getRangesByUnit(); foreach ($fields as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field < $range[0] || $$field > $range[1])) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } $instance = static::create($year, $month, $day, $hour, $minute, $second, $timezone); foreach (array_reverse($fields) as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field !== $instance->$field)) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } return $instance; } /** * Create a new Carbon instance from a specific date and time using strict validation. * * @see create() * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $timezone = null): static { $initialStrictMode = static::isStrictModeEnabled(); static::useStrictMode(true); try { $date = static::create($year, $month, $day, $hour, $minute, $second, $timezone); } finally { static::useStrictMode($initialStrictMode); } return $date; } /** * Create a Carbon instance from just a date. The time portion is set to now. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, null, null, null, $timezone); } /** * Create a Carbon instance from just a date. The time portion is set to midnight. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createMidnightDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, 0, 0, 0, $timezone); } /** * Create a Carbon instance from just a time. The date portion is set to today. * * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromTime($hour = 0, $minute = 0, $second = 0, $timezone = null): static { return static::create(null, null, null, $hour, $minute, $second, $timezone); } /** * Create a Carbon instance from a time string. The date portion is set to today. * * @throws InvalidFormatException */ public static function createFromTimeString(string $time, DateTimeZone|string|int|null $timezone = null): static { return static::today($timezone)->setTimeFromTimeString($time); } private static function createFromFormatAndTimezone( string $format, string $time, DateTimeZone|string|int|null $originalTimezone, ): ?DateTimeInterface { if ($originalTimezone === null) { return parent::createFromFormat($format, $time) ?: null; } $timezone = \is_int($originalTimezone) ? self::getOffsetTimezone($originalTimezone) : $originalTimezone; $timezone = static::safeCreateDateTimeZone($timezone, $originalTimezone); return parent::createFromFormat($format, $time, $timezone) ?: null; } private static function getOffsetTimezone(int $offset): string { $minutes = (int) ($offset * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE); return @timezone_name_from_abbr('', $minutes, 1) ?: throw new InvalidTimeZoneException( "Invalid offset timezone $offset", ); } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function rawCreateFromFormat(string $format, string $time, $timezone = null): ?static { // Work-around for https://bugs.php.net/bug.php?id=80141 $format = preg_replace('/(?<!\\\\)((?:\\\\{2})*)c/', '$1Y-m-d\TH:i:sP', $format); if (preg_match('/(?<!\\\\)(?:\\\\{2})*(a|A)/', $format, $aMatches, PREG_OFFSET_CAPTURE) && preg_match('/(?<!\\\\)(?:\\\\{2})*(h|g|H|G)/', $format, $hMatches, PREG_OFFSET_CAPTURE) && $aMatches[1][1] < $hMatches[1][1] && preg_match('/(am|pm|AM|PM)/', $time) ) { $format = preg_replace('/^(.*)(?<!\\\\)((?:\\\\{2})*)(a|A)(.*)$/U', '$1$2$4 $3', $format); $time = preg_replace('/^(.*)(am|pm|AM|PM)(.*)$/U', '$1$3 $2', $time); } if ($timezone === false) { $timezone = null; } // First attempt to create an instance, so that error messages are based on the unmodified format. $date = self::createFromFormatAndTimezone($format, $time, $timezone); $lastErrors = parent::getLastErrors(); /** @var \Carbon\CarbonImmutable|\Carbon\Carbon|null $mock */ $mock = static::getMockedTestNow($timezone); if ($mock && $date instanceof DateTimeInterface) { // Set timezone from mock if custom timezone was neither given directly nor as a part of format. // First let's skip the part that will be ignored by the parser. $nonEscaped = '(?<!\\\\)(\\\\{2})*'; $nonIgnored = preg_replace("/^.*{$nonEscaped}!/s", '', $format); if ($timezone === null && !preg_match("/{$nonEscaped}[eOPT]/", $nonIgnored)) { $timezone = clone $mock->getTimezone(); } $mock = $mock->copy(); // Prepend mock datetime only if the format does not contain non escaped unix epoch reset flag. if (!preg_match("/{$nonEscaped}[!|]/", $format)) { if (preg_match('/[HhGgisvuB]/', $format)) { $mock = $mock->setTime(0, 0); } $format = static::MOCK_DATETIME_FORMAT.' '.$format; $time = ($mock instanceof self ? $mock->rawFormat(static::MOCK_DATETIME_FORMAT) : $mock->format(static::MOCK_DATETIME_FORMAT)).' '.$time; } // Regenerate date from the modified format to base result on the mocked instance instead of now. $date = self::createFromFormatAndTimezone($format, $time, $timezone); } if ($date instanceof DateTimeInterface) { $instance = static::instance($date); $instance::setLastErrors($lastErrors); return $instance; } if (static::isStrictModeEnabled()) { throw new InvalidFormatException(implode(PHP_EOL, (array) $lastErrors['errors'])); } return null; } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ #[ReturnTypeWillChange] public static function createFromFormat($format, $time, $timezone = null): ?static { $function = static::$createFromFormatFunction; // format is a single numeric unit if (\is_int($time) && \in_array(ltrim($format, '!'), ['U', 'Y', 'y', 'X', 'x', 'm', 'n', 'd', 'j', 'w', 'W', 'H', 'h', 'G', 'g', 'i', 's', 'u', 'z', 'v'], true)) { $time = (string) $time; } if (!\is_string($time)) { @trigger_error( 'createFromFormat() $time parameter will only accept string or integer for 1-letter format representing a numeric unit in the next version', \E_USER_DEPRECATED, ); $time = (string) $time; } if (!$function) { return static::rawCreateFromFormat($format, $time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()). * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone optional timezone * @param string|null $locale locale to be used for LTS, LT, LL, LLL, etc. macro-formats (en by fault, unneeded if no such macro-format in use) * @param TranslatorInterface|null $translator optional custom translator to use for macro-formats * * @throws InvalidFormatException * * @return static|null */ public static function createFromIsoFormat( string $format, string $time, $timezone = null, ?string $locale = CarbonInterface::DEFAULT_LOCALE, ?TranslatorInterface $translator = null ): ?static { $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*(LTS|LT|[Ll]{1,4})/', function ($match) use ($locale, $translator) { [$code] = $match; static $formats = null; if ($formats === null) { $translator ??= Translator::get($locale); $formats = [ 'LT' => static::getTranslationMessageWith($translator, 'formats.LT', $locale), 'LTS' => static::getTranslationMessageWith($translator, 'formats.LTS', $locale), 'L' => static::getTranslationMessageWith($translator, 'formats.L', $locale), 'LL' => static::getTranslationMessageWith($translator, 'formats.LL', $locale), 'LLL' => static::getTranslationMessageWith($translator, 'formats.LLL', $locale), 'LLLL' => static::getTranslationMessageWith($translator, 'formats.LLLL', $locale), ]; } return $formats[$code] ?? preg_replace_callback( '/MMMM|MM|DD|dddd/', static fn (array $code) => mb_substr($code[0], 1), $formats[strtoupper($code)] ?? '', ); }, $format); $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*('.CarbonInterface::ISO_FORMAT_REGEXP.'|[A-Za-z])/', function ($match) { [$code] = $match; static $replacements = null; if ($replacements === null) { $replacements = [ 'OD' => 'd', 'OM' => 'M', 'OY' => 'Y', 'OH' => 'G', 'Oh' => 'g', 'Om' => 'i', 'Os' => 's', 'D' => 'd', 'DD' => 'd', 'Do' => 'd', 'd' => '!', 'dd' => '!', 'ddd' => 'D', 'dddd' => 'D', 'DDD' => 'z', 'DDDD' => 'z', 'DDDo' => 'z', 'e' => '!', 'E' => '!', 'H' => 'G', 'HH' => 'H', 'h' => 'g', 'hh' => 'h', 'k' => 'G', 'kk' => 'G', 'hmm' => 'gi', 'hmmss' => 'gis', 'Hmm' => 'Gi', 'Hmmss' => 'Gis', 'm' => 'i', 'mm' => 'i', 'a' => 'a', 'A' => 'a', 's' => 's', 'ss' => 's', 'S' => '*', 'SS' => '*', 'SSS' => '*', 'SSSS' => '*', 'SSSSS' => '*', 'SSSSSS' => 'u', 'SSSSSSS' => 'u*', 'SSSSSSSS' => 'u*', 'SSSSSSSSS' => 'u*', 'M' => 'm', 'MM' => 'm', 'MMM' => 'M', 'MMMM' => 'M', 'Mo' => 'm', 'Q' => '!', 'Qo' => '!', 'G' => '!', 'GG' => '!', 'GGG' => '!', 'GGGG' => '!', 'GGGGG' => '!', 'g' => '!', 'gg' => '!', 'ggg' => '!', 'gggg' => '!', 'ggggg' => '!', 'W' => '!', 'WW' => '!', 'Wo' => '!', 'w' => '!', 'ww' => '!', 'wo' => '!', 'x' => 'U???', 'X' => 'U', 'Y' => 'Y', 'YY' => 'y', 'YYYY' => 'Y', 'YYYYY' => 'Y', 'YYYYYY' => 'Y', 'z' => 'e', 'zz' => 'e', 'Z' => 'e', 'ZZ' => 'e', ]; } $format = $replacements[$code] ?? '?'; if ($format === '!') { throw new InvalidFormatException("Format $code not supported for creation."); } return $format; }, $format); return static::rawCreateFromFormat($format, $time, $timezone); } /** * Create a Carbon instance from a specific format and a string in a given language. * * @param string $format Datetime format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null): ?static { $format = preg_replace_callback( '/(?:\\\\[a-zA-Z]|[bfkqCEJKQRV]){2,}/', static function (array $match) use ($locale): string { $word = str_replace('\\', '', $match[0]); $translatedWord = static::translateTimeString($word, $locale, static::DEFAULT_LOCALE); return $word === $translatedWord ? $match[0] : preg_replace('/[a-zA-Z]/', '\\\\$0', $translatedWord); }, $format ); return static::rawCreateFromFormat($format, static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Create a Carbon instance from a specific ISO format and a string in a given language. * * @param string $format Datetime ISO format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleIsoFormat(string $format, string $locale, string $time, $timezone = null): ?static { $time = static::translateTimeString($time, $locale, static::DEFAULT_LOCALE, CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS | CarbonInterface::TRANSLATE_MERIDIEM); return static::createFromIsoFormat($format, $time, $timezone, $locale); } /** * Make a Carbon instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed $var * * @throws InvalidFormatException * * @return static|null */ public static function make($var, DateTimeZone|string|null $timezone = null): ?static { if ($var instanceof DateTimeInterface) { return static::instance($var); } $date = null; if (\is_string($var)) { $var = trim($var); if (!preg_match('/^P[\dT]/', $var) && !preg_match('/^R\d/', $var) && preg_match('/[a-z\d]/i', $var) ) { $date = static::parse($var, $timezone); } } return $date; } /** * Set last errors. * * @param array|bool $lastErrors * * @return void */ private static function setLastErrors($lastErrors): void { static::$lastErrors = $lastErrors; } /** * {@inheritdoc} */ public static function getLastErrors(): array|false { return static::$lastErrors; } private static function monthToInt(mixed $value, string $unit = 'month'): mixed { if ($value instanceof Month) { if ($unit !== 'month') { throw new UnitException("Month enum cannot be used to set $unit"); } return Month::int($value); } return $value; } }
PHP
{ "end_line": 196, "name": "rawParse", "signature": "public static function rawParse(", "start_line": 174 }
{ "class_name": "Creator", "class_signature": "trait Creator", "namespace": "Carbon\\Traits" }
parse
Carbon/src/Carbon/Traits/Creator.php
public static function parse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { $function = static::$parseFunction; if (!$function) { return static::rawParse($time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\UnitException; use Carbon\Month; use Carbon\Translator; use Carbon\WeekDay; use Closure; use DateMalformedStringException; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Exception; use ReturnTypeWillChange; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Creator. * * Static creators. * * Depends on the following methods: * * @method static Carbon|CarbonImmutable getTestNow() */ trait Creator { use ObjectInitialisation; use LocalFactory; /** * The errors that can occur. */ protected static array|bool $lastErrors = false; /** * Create a new Carbon instance. * * Please see the testing aids section (specifically static::setTestNow()) * for more on the possibility of this constructor returning a test instance. * * @throws InvalidFormatException */ public function __construct( DateTimeInterface|WeekDay|Month|string|int|float|null $time = null, DateTimeZone|string|int|null $timezone = null, ) { $this->initLocalFactory(); if ($time instanceof Month) { $time = $time->name.' 1'; } elseif ($time instanceof WeekDay) { $time = $time->name; } elseif ($time instanceof DateTimeInterface) { $time = $this->constructTimezoneFromDateTime($time, $timezone)->format('Y-m-d H:i:s.u'); } if (\is_string($time) && str_starts_with($time, '@')) { $time = static::createFromTimestampUTC(substr($time, 1))->format('Y-m-d\TH:i:s.uP'); } elseif (is_numeric($time) && (!\is_string($time) || !preg_match('/^\d{1,14}$/', $time))) { $time = static::createFromTimestampUTC($time)->format('Y-m-d\TH:i:s.uP'); } // If the class has a test now set, and we are trying to create a now() // instance then override as required $isNow = \in_array($time, [null, '', 'now'], true); $timezone = static::safeCreateDateTimeZone($timezone) ?? null; if ( ($this->clock || ( method_exists(static::class, 'hasTestNow') && method_exists(static::class, 'getTestNow') && static::hasTestNow() )) && ($isNow || static::hasRelativeKeywords($time)) ) { $this->mockConstructorParameters($time, $timezone); } try { parent::__construct($time ?? 'now', $timezone); } catch (Exception $exception) { throw new InvalidFormatException($exception->getMessage(), 0, $exception); } $this->constructedObjectId = spl_object_hash($this); self::setLastErrors(parent::getLastErrors()); } /** * Get timezone from a datetime instance. */ private function constructTimezoneFromDateTime( DateTimeInterface $date, DateTimeZone|string|int|null &$timezone, ): DateTimeInterface { if ($timezone !== null) { $safeTz = static::safeCreateDateTimeZone($timezone); if ($safeTz) { $date = ($date instanceof DateTimeImmutable ? $date : clone $date)->setTimezone($safeTz); } return $date; } $timezone = $date->getTimezone(); return $date; } /** * Update constructedObjectId on cloned. */ public function __clone(): void { $this->constructedObjectId = spl_object_hash($this); } /** * Create a Carbon instance from a DateTime one. */ public static function instance(DateTimeInterface $date): static { if ($date instanceof static) { return clone $date; } $instance = parent::createFromFormat('U.u', $date->format('U.u')) ->setTimezone($date->getTimezone()); if ($date instanceof CarbonInterface) { $settings = $date->getSettings(); if (!$date->hasLocalTranslator()) { unset($settings['locale']); } $instance->settings($settings); } return $instance; } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function rawParse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { if ($time instanceof DateTimeInterface) { return static::instance($time); } try { return new static($time, $timezone); } catch (Exception $exception) { // @codeCoverageIgnoreStart try { $date = @static::now($timezone)->change($time); } catch (DateMalformedStringException|InvalidFormatException) { $date = null; } // @codeCoverageIgnoreEnd return $date ?? throw new InvalidFormatException("Could not parse '$time': ".$exception->getMessage(), 0, $exception); } } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function parse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { $function = static::$parseFunction; if (!$function) { return static::rawParse($time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.). * * @param string $time date/time string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be * used instead. * @param DateTimeZone|string|int|null $timezone optional timezone for the new instance. * * @throws InvalidFormatException */ public static function parseFromLocale( string $time, ?string $locale = null, DateTimeZone|string|int|null $timezone = null, ): static { return static::rawParse(static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Get a Carbon instance for the current date and time. */ public static function now(DateTimeZone|string|int|null $timezone = null): static { return new static(null, $timezone); } /** * Create a Carbon instance for today. */ public static function today(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('today', $timezone); } /** * Create a Carbon instance for tomorrow. */ public static function tomorrow(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('tomorrow', $timezone); } /** * Create a Carbon instance for yesterday. */ public static function yesterday(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('yesterday', $timezone); } private static function assertBetween($unit, $value, $min, $max): void { if (static::isStrictModeEnabled() && ($value < $min || $value > $max)) { throw new OutOfRangeException($unit, $min, $max, $value); } } private static function createNowInstance($timezone) { if (!static::hasTestNow()) { return static::now($timezone); } $now = static::getTestNow(); if ($now instanceof Closure) { return $now(static::now($timezone)); } $now = $now->avoidMutation(); return $timezone === null ? $now : $now->setTimezone($timezone); } /** * Create a new Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * @param DateTimeInterface|string|int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null): ?static { $month = self::monthToInt($month); if ((\is_string($year) && !is_numeric($year)) || $year instanceof DateTimeInterface) { return static::parse($year, $timezone ?? (\is_string($month) || $month instanceof DateTimeZone ? $month : null)); } $defaults = null; $getDefault = function ($unit) use ($timezone, &$defaults) { if ($defaults === null) { $now = self::createNowInstance($timezone); $defaults = array_combine([ 'year', 'month', 'day', 'hour', 'minute', 'second', ], explode('-', $now->rawFormat('Y-n-j-G-i-s.u'))); } return $defaults[$unit]; }; $year = $year ?? $getDefault('year'); $month = $month ?? $getDefault('month'); $day = $day ?? $getDefault('day'); $hour = $hour ?? $getDefault('hour'); $minute = $minute ?? $getDefault('minute'); $second = (float) ($second ?? $getDefault('second')); self::assertBetween('month', $month, 0, 99); self::assertBetween('day', $day, 0, 99); self::assertBetween('hour', $hour, 0, 99); self::assertBetween('minute', $minute, 0, 99); self::assertBetween('second', $second, 0, 99); $fixYear = null; if ($year < 0) { $fixYear = $year; $year = 0; } elseif ($year > 9999) { $fixYear = $year - 9999; $year = 9999; } $second = ($second < 10 ? '0' : '').number_format($second, 6); $instance = static::rawCreateFromFormat('!Y-n-j G:i:s.u', \sprintf('%s-%s-%s %s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $timezone); if ($instance && $fixYear !== null) { $instance = $instance->addYears($fixYear); } return $instance ?? null; } /** * Create a new safe Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * If one of the set values is not valid, an InvalidDateException * will be thrown. * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidDateException * * @return static|null */ public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null): ?static { $month = self::monthToInt($month); $fields = static::getRangesByUnit(); foreach ($fields as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field < $range[0] || $$field > $range[1])) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } $instance = static::create($year, $month, $day, $hour, $minute, $second, $timezone); foreach (array_reverse($fields) as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field !== $instance->$field)) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } return $instance; } /** * Create a new Carbon instance from a specific date and time using strict validation. * * @see create() * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $timezone = null): static { $initialStrictMode = static::isStrictModeEnabled(); static::useStrictMode(true); try { $date = static::create($year, $month, $day, $hour, $minute, $second, $timezone); } finally { static::useStrictMode($initialStrictMode); } return $date; } /** * Create a Carbon instance from just a date. The time portion is set to now. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, null, null, null, $timezone); } /** * Create a Carbon instance from just a date. The time portion is set to midnight. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createMidnightDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, 0, 0, 0, $timezone); } /** * Create a Carbon instance from just a time. The date portion is set to today. * * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromTime($hour = 0, $minute = 0, $second = 0, $timezone = null): static { return static::create(null, null, null, $hour, $minute, $second, $timezone); } /** * Create a Carbon instance from a time string. The date portion is set to today. * * @throws InvalidFormatException */ public static function createFromTimeString(string $time, DateTimeZone|string|int|null $timezone = null): static { return static::today($timezone)->setTimeFromTimeString($time); } private static function createFromFormatAndTimezone( string $format, string $time, DateTimeZone|string|int|null $originalTimezone, ): ?DateTimeInterface { if ($originalTimezone === null) { return parent::createFromFormat($format, $time) ?: null; } $timezone = \is_int($originalTimezone) ? self::getOffsetTimezone($originalTimezone) : $originalTimezone; $timezone = static::safeCreateDateTimeZone($timezone, $originalTimezone); return parent::createFromFormat($format, $time, $timezone) ?: null; } private static function getOffsetTimezone(int $offset): string { $minutes = (int) ($offset * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE); return @timezone_name_from_abbr('', $minutes, 1) ?: throw new InvalidTimeZoneException( "Invalid offset timezone $offset", ); } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function rawCreateFromFormat(string $format, string $time, $timezone = null): ?static { // Work-around for https://bugs.php.net/bug.php?id=80141 $format = preg_replace('/(?<!\\\\)((?:\\\\{2})*)c/', '$1Y-m-d\TH:i:sP', $format); if (preg_match('/(?<!\\\\)(?:\\\\{2})*(a|A)/', $format, $aMatches, PREG_OFFSET_CAPTURE) && preg_match('/(?<!\\\\)(?:\\\\{2})*(h|g|H|G)/', $format, $hMatches, PREG_OFFSET_CAPTURE) && $aMatches[1][1] < $hMatches[1][1] && preg_match('/(am|pm|AM|PM)/', $time) ) { $format = preg_replace('/^(.*)(?<!\\\\)((?:\\\\{2})*)(a|A)(.*)$/U', '$1$2$4 $3', $format); $time = preg_replace('/^(.*)(am|pm|AM|PM)(.*)$/U', '$1$3 $2', $time); } if ($timezone === false) { $timezone = null; } // First attempt to create an instance, so that error messages are based on the unmodified format. $date = self::createFromFormatAndTimezone($format, $time, $timezone); $lastErrors = parent::getLastErrors(); /** @var \Carbon\CarbonImmutable|\Carbon\Carbon|null $mock */ $mock = static::getMockedTestNow($timezone); if ($mock && $date instanceof DateTimeInterface) { // Set timezone from mock if custom timezone was neither given directly nor as a part of format. // First let's skip the part that will be ignored by the parser. $nonEscaped = '(?<!\\\\)(\\\\{2})*'; $nonIgnored = preg_replace("/^.*{$nonEscaped}!/s", '', $format); if ($timezone === null && !preg_match("/{$nonEscaped}[eOPT]/", $nonIgnored)) { $timezone = clone $mock->getTimezone(); } $mock = $mock->copy(); // Prepend mock datetime only if the format does not contain non escaped unix epoch reset flag. if (!preg_match("/{$nonEscaped}[!|]/", $format)) { if (preg_match('/[HhGgisvuB]/', $format)) { $mock = $mock->setTime(0, 0); } $format = static::MOCK_DATETIME_FORMAT.' '.$format; $time = ($mock instanceof self ? $mock->rawFormat(static::MOCK_DATETIME_FORMAT) : $mock->format(static::MOCK_DATETIME_FORMAT)).' '.$time; } // Regenerate date from the modified format to base result on the mocked instance instead of now. $date = self::createFromFormatAndTimezone($format, $time, $timezone); } if ($date instanceof DateTimeInterface) { $instance = static::instance($date); $instance::setLastErrors($lastErrors); return $instance; } if (static::isStrictModeEnabled()) { throw new InvalidFormatException(implode(PHP_EOL, (array) $lastErrors['errors'])); } return null; } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ #[ReturnTypeWillChange] public static function createFromFormat($format, $time, $timezone = null): ?static { $function = static::$createFromFormatFunction; // format is a single numeric unit if (\is_int($time) && \in_array(ltrim($format, '!'), ['U', 'Y', 'y', 'X', 'x', 'm', 'n', 'd', 'j', 'w', 'W', 'H', 'h', 'G', 'g', 'i', 's', 'u', 'z', 'v'], true)) { $time = (string) $time; } if (!\is_string($time)) { @trigger_error( 'createFromFormat() $time parameter will only accept string or integer for 1-letter format representing a numeric unit in the next version', \E_USER_DEPRECATED, ); $time = (string) $time; } if (!$function) { return static::rawCreateFromFormat($format, $time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()). * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone optional timezone * @param string|null $locale locale to be used for LTS, LT, LL, LLL, etc. macro-formats (en by fault, unneeded if no such macro-format in use) * @param TranslatorInterface|null $translator optional custom translator to use for macro-formats * * @throws InvalidFormatException * * @return static|null */ public static function createFromIsoFormat( string $format, string $time, $timezone = null, ?string $locale = CarbonInterface::DEFAULT_LOCALE, ?TranslatorInterface $translator = null ): ?static { $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*(LTS|LT|[Ll]{1,4})/', function ($match) use ($locale, $translator) { [$code] = $match; static $formats = null; if ($formats === null) { $translator ??= Translator::get($locale); $formats = [ 'LT' => static::getTranslationMessageWith($translator, 'formats.LT', $locale), 'LTS' => static::getTranslationMessageWith($translator, 'formats.LTS', $locale), 'L' => static::getTranslationMessageWith($translator, 'formats.L', $locale), 'LL' => static::getTranslationMessageWith($translator, 'formats.LL', $locale), 'LLL' => static::getTranslationMessageWith($translator, 'formats.LLL', $locale), 'LLLL' => static::getTranslationMessageWith($translator, 'formats.LLLL', $locale), ]; } return $formats[$code] ?? preg_replace_callback( '/MMMM|MM|DD|dddd/', static fn (array $code) => mb_substr($code[0], 1), $formats[strtoupper($code)] ?? '', ); }, $format); $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*('.CarbonInterface::ISO_FORMAT_REGEXP.'|[A-Za-z])/', function ($match) { [$code] = $match; static $replacements = null; if ($replacements === null) { $replacements = [ 'OD' => 'd', 'OM' => 'M', 'OY' => 'Y', 'OH' => 'G', 'Oh' => 'g', 'Om' => 'i', 'Os' => 's', 'D' => 'd', 'DD' => 'd', 'Do' => 'd', 'd' => '!', 'dd' => '!', 'ddd' => 'D', 'dddd' => 'D', 'DDD' => 'z', 'DDDD' => 'z', 'DDDo' => 'z', 'e' => '!', 'E' => '!', 'H' => 'G', 'HH' => 'H', 'h' => 'g', 'hh' => 'h', 'k' => 'G', 'kk' => 'G', 'hmm' => 'gi', 'hmmss' => 'gis', 'Hmm' => 'Gi', 'Hmmss' => 'Gis', 'm' => 'i', 'mm' => 'i', 'a' => 'a', 'A' => 'a', 's' => 's', 'ss' => 's', 'S' => '*', 'SS' => '*', 'SSS' => '*', 'SSSS' => '*', 'SSSSS' => '*', 'SSSSSS' => 'u', 'SSSSSSS' => 'u*', 'SSSSSSSS' => 'u*', 'SSSSSSSSS' => 'u*', 'M' => 'm', 'MM' => 'm', 'MMM' => 'M', 'MMMM' => 'M', 'Mo' => 'm', 'Q' => '!', 'Qo' => '!', 'G' => '!', 'GG' => '!', 'GGG' => '!', 'GGGG' => '!', 'GGGGG' => '!', 'g' => '!', 'gg' => '!', 'ggg' => '!', 'gggg' => '!', 'ggggg' => '!', 'W' => '!', 'WW' => '!', 'Wo' => '!', 'w' => '!', 'ww' => '!', 'wo' => '!', 'x' => 'U???', 'X' => 'U', 'Y' => 'Y', 'YY' => 'y', 'YYYY' => 'Y', 'YYYYY' => 'Y', 'YYYYYY' => 'Y', 'z' => 'e', 'zz' => 'e', 'Z' => 'e', 'ZZ' => 'e', ]; } $format = $replacements[$code] ?? '?'; if ($format === '!') { throw new InvalidFormatException("Format $code not supported for creation."); } return $format; }, $format); return static::rawCreateFromFormat($format, $time, $timezone); } /** * Create a Carbon instance from a specific format and a string in a given language. * * @param string $format Datetime format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null): ?static { $format = preg_replace_callback( '/(?:\\\\[a-zA-Z]|[bfkqCEJKQRV]){2,}/', static function (array $match) use ($locale): string { $word = str_replace('\\', '', $match[0]); $translatedWord = static::translateTimeString($word, $locale, static::DEFAULT_LOCALE); return $word === $translatedWord ? $match[0] : preg_replace('/[a-zA-Z]/', '\\\\$0', $translatedWord); }, $format ); return static::rawCreateFromFormat($format, static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Create a Carbon instance from a specific ISO format and a string in a given language. * * @param string $format Datetime ISO format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleIsoFormat(string $format, string $locale, string $time, $timezone = null): ?static { $time = static::translateTimeString($time, $locale, static::DEFAULT_LOCALE, CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS | CarbonInterface::TRANSLATE_MERIDIEM); return static::createFromIsoFormat($format, $time, $timezone, $locale); } /** * Make a Carbon instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed $var * * @throws InvalidFormatException * * @return static|null */ public static function make($var, DateTimeZone|string|null $timezone = null): ?static { if ($var instanceof DateTimeInterface) { return static::instance($var); } $date = null; if (\is_string($var)) { $var = trim($var); if (!preg_match('/^P[\dT]/', $var) && !preg_match('/^R\d/', $var) && preg_match('/[a-z\d]/i', $var) ) { $date = static::parse($var, $timezone); } } return $date; } /** * Set last errors. * * @param array|bool $lastErrors * * @return void */ private static function setLastErrors($lastErrors): void { static::$lastErrors = $lastErrors; } /** * {@inheritdoc} */ public static function getLastErrors(): array|false { return static::$lastErrors; } private static function monthToInt(mixed $value, string $unit = 'month'): mixed { if ($value instanceof Month) { if ($unit !== 'month') { throw new UnitException("Month enum cannot be used to set $unit"); } return Month::int($value); } return $value; } }
PHP
{ "end_line": 222, "name": "parse", "signature": "public static function parse(", "start_line": 207 }
{ "class_name": "Creator", "class_signature": "trait Creator", "namespace": "Carbon\\Traits" }
create
Carbon/src/Carbon/Traits/Creator.php
public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null): ?static { $month = self::monthToInt($month); if ((\is_string($year) && !is_numeric($year)) || $year instanceof DateTimeInterface) { return static::parse($year, $timezone ?? (\is_string($month) || $month instanceof DateTimeZone ? $month : null)); } $defaults = null; $getDefault = function ($unit) use ($timezone, &$defaults) { if ($defaults === null) { $now = self::createNowInstance($timezone); $defaults = array_combine([ 'year', 'month', 'day', 'hour', 'minute', 'second', ], explode('-', $now->rawFormat('Y-n-j-G-i-s.u'))); } return $defaults[$unit]; }; $year = $year ?? $getDefault('year'); $month = $month ?? $getDefault('month'); $day = $day ?? $getDefault('day'); $hour = $hour ?? $getDefault('hour'); $minute = $minute ?? $getDefault('minute'); $second = (float) ($second ?? $getDefault('second')); self::assertBetween('month', $month, 0, 99); self::assertBetween('day', $day, 0, 99); self::assertBetween('hour', $hour, 0, 99); self::assertBetween('minute', $minute, 0, 99); self::assertBetween('second', $second, 0, 99); $fixYear = null; if ($year < 0) { $fixYear = $year; $year = 0; } elseif ($year > 9999) { $fixYear = $year - 9999; $year = 9999; } $second = ($second < 10 ? '0' : '').number_format($second, 6); $instance = static::rawCreateFromFormat('!Y-n-j G:i:s.u', \sprintf('%s-%s-%s %s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $timezone); if ($instance && $fixYear !== null) { $instance = $instance->addYears($fixYear); } return $instance ?? null; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\UnitException; use Carbon\Month; use Carbon\Translator; use Carbon\WeekDay; use Closure; use DateMalformedStringException; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Exception; use ReturnTypeWillChange; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Creator. * * Static creators. * * Depends on the following methods: * * @method static Carbon|CarbonImmutable getTestNow() */ trait Creator { use ObjectInitialisation; use LocalFactory; /** * The errors that can occur. */ protected static array|bool $lastErrors = false; /** * Create a new Carbon instance. * * Please see the testing aids section (specifically static::setTestNow()) * for more on the possibility of this constructor returning a test instance. * * @throws InvalidFormatException */ public function __construct( DateTimeInterface|WeekDay|Month|string|int|float|null $time = null, DateTimeZone|string|int|null $timezone = null, ) { $this->initLocalFactory(); if ($time instanceof Month) { $time = $time->name.' 1'; } elseif ($time instanceof WeekDay) { $time = $time->name; } elseif ($time instanceof DateTimeInterface) { $time = $this->constructTimezoneFromDateTime($time, $timezone)->format('Y-m-d H:i:s.u'); } if (\is_string($time) && str_starts_with($time, '@')) { $time = static::createFromTimestampUTC(substr($time, 1))->format('Y-m-d\TH:i:s.uP'); } elseif (is_numeric($time) && (!\is_string($time) || !preg_match('/^\d{1,14}$/', $time))) { $time = static::createFromTimestampUTC($time)->format('Y-m-d\TH:i:s.uP'); } // If the class has a test now set, and we are trying to create a now() // instance then override as required $isNow = \in_array($time, [null, '', 'now'], true); $timezone = static::safeCreateDateTimeZone($timezone) ?? null; if ( ($this->clock || ( method_exists(static::class, 'hasTestNow') && method_exists(static::class, 'getTestNow') && static::hasTestNow() )) && ($isNow || static::hasRelativeKeywords($time)) ) { $this->mockConstructorParameters($time, $timezone); } try { parent::__construct($time ?? 'now', $timezone); } catch (Exception $exception) { throw new InvalidFormatException($exception->getMessage(), 0, $exception); } $this->constructedObjectId = spl_object_hash($this); self::setLastErrors(parent::getLastErrors()); } /** * Get timezone from a datetime instance. */ private function constructTimezoneFromDateTime( DateTimeInterface $date, DateTimeZone|string|int|null &$timezone, ): DateTimeInterface { if ($timezone !== null) { $safeTz = static::safeCreateDateTimeZone($timezone); if ($safeTz) { $date = ($date instanceof DateTimeImmutable ? $date : clone $date)->setTimezone($safeTz); } return $date; } $timezone = $date->getTimezone(); return $date; } /** * Update constructedObjectId on cloned. */ public function __clone(): void { $this->constructedObjectId = spl_object_hash($this); } /** * Create a Carbon instance from a DateTime one. */ public static function instance(DateTimeInterface $date): static { if ($date instanceof static) { return clone $date; } $instance = parent::createFromFormat('U.u', $date->format('U.u')) ->setTimezone($date->getTimezone()); if ($date instanceof CarbonInterface) { $settings = $date->getSettings(); if (!$date->hasLocalTranslator()) { unset($settings['locale']); } $instance->settings($settings); } return $instance; } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function rawParse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { if ($time instanceof DateTimeInterface) { return static::instance($time); } try { return new static($time, $timezone); } catch (Exception $exception) { // @codeCoverageIgnoreStart try { $date = @static::now($timezone)->change($time); } catch (DateMalformedStringException|InvalidFormatException) { $date = null; } // @codeCoverageIgnoreEnd return $date ?? throw new InvalidFormatException("Could not parse '$time': ".$exception->getMessage(), 0, $exception); } } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function parse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { $function = static::$parseFunction; if (!$function) { return static::rawParse($time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.). * * @param string $time date/time string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be * used instead. * @param DateTimeZone|string|int|null $timezone optional timezone for the new instance. * * @throws InvalidFormatException */ public static function parseFromLocale( string $time, ?string $locale = null, DateTimeZone|string|int|null $timezone = null, ): static { return static::rawParse(static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Get a Carbon instance for the current date and time. */ public static function now(DateTimeZone|string|int|null $timezone = null): static { return new static(null, $timezone); } /** * Create a Carbon instance for today. */ public static function today(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('today', $timezone); } /** * Create a Carbon instance for tomorrow. */ public static function tomorrow(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('tomorrow', $timezone); } /** * Create a Carbon instance for yesterday. */ public static function yesterday(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('yesterday', $timezone); } private static function assertBetween($unit, $value, $min, $max): void { if (static::isStrictModeEnabled() && ($value < $min || $value > $max)) { throw new OutOfRangeException($unit, $min, $max, $value); } } private static function createNowInstance($timezone) { if (!static::hasTestNow()) { return static::now($timezone); } $now = static::getTestNow(); if ($now instanceof Closure) { return $now(static::now($timezone)); } $now = $now->avoidMutation(); return $timezone === null ? $now : $now->setTimezone($timezone); } /** * Create a new Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * @param DateTimeInterface|string|int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null): ?static { $month = self::monthToInt($month); if ((\is_string($year) && !is_numeric($year)) || $year instanceof DateTimeInterface) { return static::parse($year, $timezone ?? (\is_string($month) || $month instanceof DateTimeZone ? $month : null)); } $defaults = null; $getDefault = function ($unit) use ($timezone, &$defaults) { if ($defaults === null) { $now = self::createNowInstance($timezone); $defaults = array_combine([ 'year', 'month', 'day', 'hour', 'minute', 'second', ], explode('-', $now->rawFormat('Y-n-j-G-i-s.u'))); } return $defaults[$unit]; }; $year = $year ?? $getDefault('year'); $month = $month ?? $getDefault('month'); $day = $day ?? $getDefault('day'); $hour = $hour ?? $getDefault('hour'); $minute = $minute ?? $getDefault('minute'); $second = (float) ($second ?? $getDefault('second')); self::assertBetween('month', $month, 0, 99); self::assertBetween('day', $day, 0, 99); self::assertBetween('hour', $hour, 0, 99); self::assertBetween('minute', $minute, 0, 99); self::assertBetween('second', $second, 0, 99); $fixYear = null; if ($year < 0) { $fixYear = $year; $year = 0; } elseif ($year > 9999) { $fixYear = $year - 9999; $year = 9999; } $second = ($second < 10 ? '0' : '').number_format($second, 6); $instance = static::rawCreateFromFormat('!Y-n-j G:i:s.u', \sprintf('%s-%s-%s %s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $timezone); if ($instance && $fixYear !== null) { $instance = $instance->addYears($fixYear); } return $instance ?? null; } /** * Create a new safe Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * If one of the set values is not valid, an InvalidDateException * will be thrown. * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidDateException * * @return static|null */ public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null): ?static { $month = self::monthToInt($month); $fields = static::getRangesByUnit(); foreach ($fields as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field < $range[0] || $$field > $range[1])) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } $instance = static::create($year, $month, $day, $hour, $minute, $second, $timezone); foreach (array_reverse($fields) as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field !== $instance->$field)) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } return $instance; } /** * Create a new Carbon instance from a specific date and time using strict validation. * * @see create() * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $timezone = null): static { $initialStrictMode = static::isStrictModeEnabled(); static::useStrictMode(true); try { $date = static::create($year, $month, $day, $hour, $minute, $second, $timezone); } finally { static::useStrictMode($initialStrictMode); } return $date; } /** * Create a Carbon instance from just a date. The time portion is set to now. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, null, null, null, $timezone); } /** * Create a Carbon instance from just a date. The time portion is set to midnight. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createMidnightDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, 0, 0, 0, $timezone); } /** * Create a Carbon instance from just a time. The date portion is set to today. * * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromTime($hour = 0, $minute = 0, $second = 0, $timezone = null): static { return static::create(null, null, null, $hour, $minute, $second, $timezone); } /** * Create a Carbon instance from a time string. The date portion is set to today. * * @throws InvalidFormatException */ public static function createFromTimeString(string $time, DateTimeZone|string|int|null $timezone = null): static { return static::today($timezone)->setTimeFromTimeString($time); } private static function createFromFormatAndTimezone( string $format, string $time, DateTimeZone|string|int|null $originalTimezone, ): ?DateTimeInterface { if ($originalTimezone === null) { return parent::createFromFormat($format, $time) ?: null; } $timezone = \is_int($originalTimezone) ? self::getOffsetTimezone($originalTimezone) : $originalTimezone; $timezone = static::safeCreateDateTimeZone($timezone, $originalTimezone); return parent::createFromFormat($format, $time, $timezone) ?: null; } private static function getOffsetTimezone(int $offset): string { $minutes = (int) ($offset * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE); return @timezone_name_from_abbr('', $minutes, 1) ?: throw new InvalidTimeZoneException( "Invalid offset timezone $offset", ); } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function rawCreateFromFormat(string $format, string $time, $timezone = null): ?static { // Work-around for https://bugs.php.net/bug.php?id=80141 $format = preg_replace('/(?<!\\\\)((?:\\\\{2})*)c/', '$1Y-m-d\TH:i:sP', $format); if (preg_match('/(?<!\\\\)(?:\\\\{2})*(a|A)/', $format, $aMatches, PREG_OFFSET_CAPTURE) && preg_match('/(?<!\\\\)(?:\\\\{2})*(h|g|H|G)/', $format, $hMatches, PREG_OFFSET_CAPTURE) && $aMatches[1][1] < $hMatches[1][1] && preg_match('/(am|pm|AM|PM)/', $time) ) { $format = preg_replace('/^(.*)(?<!\\\\)((?:\\\\{2})*)(a|A)(.*)$/U', '$1$2$4 $3', $format); $time = preg_replace('/^(.*)(am|pm|AM|PM)(.*)$/U', '$1$3 $2', $time); } if ($timezone === false) { $timezone = null; } // First attempt to create an instance, so that error messages are based on the unmodified format. $date = self::createFromFormatAndTimezone($format, $time, $timezone); $lastErrors = parent::getLastErrors(); /** @var \Carbon\CarbonImmutable|\Carbon\Carbon|null $mock */ $mock = static::getMockedTestNow($timezone); if ($mock && $date instanceof DateTimeInterface) { // Set timezone from mock if custom timezone was neither given directly nor as a part of format. // First let's skip the part that will be ignored by the parser. $nonEscaped = '(?<!\\\\)(\\\\{2})*'; $nonIgnored = preg_replace("/^.*{$nonEscaped}!/s", '', $format); if ($timezone === null && !preg_match("/{$nonEscaped}[eOPT]/", $nonIgnored)) { $timezone = clone $mock->getTimezone(); } $mock = $mock->copy(); // Prepend mock datetime only if the format does not contain non escaped unix epoch reset flag. if (!preg_match("/{$nonEscaped}[!|]/", $format)) { if (preg_match('/[HhGgisvuB]/', $format)) { $mock = $mock->setTime(0, 0); } $format = static::MOCK_DATETIME_FORMAT.' '.$format; $time = ($mock instanceof self ? $mock->rawFormat(static::MOCK_DATETIME_FORMAT) : $mock->format(static::MOCK_DATETIME_FORMAT)).' '.$time; } // Regenerate date from the modified format to base result on the mocked instance instead of now. $date = self::createFromFormatAndTimezone($format, $time, $timezone); } if ($date instanceof DateTimeInterface) { $instance = static::instance($date); $instance::setLastErrors($lastErrors); return $instance; } if (static::isStrictModeEnabled()) { throw new InvalidFormatException(implode(PHP_EOL, (array) $lastErrors['errors'])); } return null; } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ #[ReturnTypeWillChange] public static function createFromFormat($format, $time, $timezone = null): ?static { $function = static::$createFromFormatFunction; // format is a single numeric unit if (\is_int($time) && \in_array(ltrim($format, '!'), ['U', 'Y', 'y', 'X', 'x', 'm', 'n', 'd', 'j', 'w', 'W', 'H', 'h', 'G', 'g', 'i', 's', 'u', 'z', 'v'], true)) { $time = (string) $time; } if (!\is_string($time)) { @trigger_error( 'createFromFormat() $time parameter will only accept string or integer for 1-letter format representing a numeric unit in the next version', \E_USER_DEPRECATED, ); $time = (string) $time; } if (!$function) { return static::rawCreateFromFormat($format, $time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()). * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone optional timezone * @param string|null $locale locale to be used for LTS, LT, LL, LLL, etc. macro-formats (en by fault, unneeded if no such macro-format in use) * @param TranslatorInterface|null $translator optional custom translator to use for macro-formats * * @throws InvalidFormatException * * @return static|null */ public static function createFromIsoFormat( string $format, string $time, $timezone = null, ?string $locale = CarbonInterface::DEFAULT_LOCALE, ?TranslatorInterface $translator = null ): ?static { $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*(LTS|LT|[Ll]{1,4})/', function ($match) use ($locale, $translator) { [$code] = $match; static $formats = null; if ($formats === null) { $translator ??= Translator::get($locale); $formats = [ 'LT' => static::getTranslationMessageWith($translator, 'formats.LT', $locale), 'LTS' => static::getTranslationMessageWith($translator, 'formats.LTS', $locale), 'L' => static::getTranslationMessageWith($translator, 'formats.L', $locale), 'LL' => static::getTranslationMessageWith($translator, 'formats.LL', $locale), 'LLL' => static::getTranslationMessageWith($translator, 'formats.LLL', $locale), 'LLLL' => static::getTranslationMessageWith($translator, 'formats.LLLL', $locale), ]; } return $formats[$code] ?? preg_replace_callback( '/MMMM|MM|DD|dddd/', static fn (array $code) => mb_substr($code[0], 1), $formats[strtoupper($code)] ?? '', ); }, $format); $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*('.CarbonInterface::ISO_FORMAT_REGEXP.'|[A-Za-z])/', function ($match) { [$code] = $match; static $replacements = null; if ($replacements === null) { $replacements = [ 'OD' => 'd', 'OM' => 'M', 'OY' => 'Y', 'OH' => 'G', 'Oh' => 'g', 'Om' => 'i', 'Os' => 's', 'D' => 'd', 'DD' => 'd', 'Do' => 'd', 'd' => '!', 'dd' => '!', 'ddd' => 'D', 'dddd' => 'D', 'DDD' => 'z', 'DDDD' => 'z', 'DDDo' => 'z', 'e' => '!', 'E' => '!', 'H' => 'G', 'HH' => 'H', 'h' => 'g', 'hh' => 'h', 'k' => 'G', 'kk' => 'G', 'hmm' => 'gi', 'hmmss' => 'gis', 'Hmm' => 'Gi', 'Hmmss' => 'Gis', 'm' => 'i', 'mm' => 'i', 'a' => 'a', 'A' => 'a', 's' => 's', 'ss' => 's', 'S' => '*', 'SS' => '*', 'SSS' => '*', 'SSSS' => '*', 'SSSSS' => '*', 'SSSSSS' => 'u', 'SSSSSSS' => 'u*', 'SSSSSSSS' => 'u*', 'SSSSSSSSS' => 'u*', 'M' => 'm', 'MM' => 'm', 'MMM' => 'M', 'MMMM' => 'M', 'Mo' => 'm', 'Q' => '!', 'Qo' => '!', 'G' => '!', 'GG' => '!', 'GGG' => '!', 'GGGG' => '!', 'GGGGG' => '!', 'g' => '!', 'gg' => '!', 'ggg' => '!', 'gggg' => '!', 'ggggg' => '!', 'W' => '!', 'WW' => '!', 'Wo' => '!', 'w' => '!', 'ww' => '!', 'wo' => '!', 'x' => 'U???', 'X' => 'U', 'Y' => 'Y', 'YY' => 'y', 'YYYY' => 'Y', 'YYYYY' => 'Y', 'YYYYYY' => 'Y', 'z' => 'e', 'zz' => 'e', 'Z' => 'e', 'ZZ' => 'e', ]; } $format = $replacements[$code] ?? '?'; if ($format === '!') { throw new InvalidFormatException("Format $code not supported for creation."); } return $format; }, $format); return static::rawCreateFromFormat($format, $time, $timezone); } /** * Create a Carbon instance from a specific format and a string in a given language. * * @param string $format Datetime format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null): ?static { $format = preg_replace_callback( '/(?:\\\\[a-zA-Z]|[bfkqCEJKQRV]){2,}/', static function (array $match) use ($locale): string { $word = str_replace('\\', '', $match[0]); $translatedWord = static::translateTimeString($word, $locale, static::DEFAULT_LOCALE); return $word === $translatedWord ? $match[0] : preg_replace('/[a-zA-Z]/', '\\\\$0', $translatedWord); }, $format ); return static::rawCreateFromFormat($format, static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Create a Carbon instance from a specific ISO format and a string in a given language. * * @param string $format Datetime ISO format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleIsoFormat(string $format, string $locale, string $time, $timezone = null): ?static { $time = static::translateTimeString($time, $locale, static::DEFAULT_LOCALE, CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS | CarbonInterface::TRANSLATE_MERIDIEM); return static::createFromIsoFormat($format, $time, $timezone, $locale); } /** * Make a Carbon instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed $var * * @throws InvalidFormatException * * @return static|null */ public static function make($var, DateTimeZone|string|null $timezone = null): ?static { if ($var instanceof DateTimeInterface) { return static::instance($var); } $date = null; if (\is_string($var)) { $var = trim($var); if (!preg_match('/^P[\dT]/', $var) && !preg_match('/^R\d/', $var) && preg_match('/[a-z\d]/i', $var) ) { $date = static::parse($var, $timezone); } } return $date; } /** * Set last errors. * * @param array|bool $lastErrors * * @return void */ private static function setLastErrors($lastErrors): void { static::$lastErrors = $lastErrors; } /** * {@inheritdoc} */ public static function getLastErrors(): array|false { return static::$lastErrors; } private static function monthToInt(mixed $value, string $unit = 'month'): mixed { if ($value instanceof Month) { if ($unit !== 'month') { throw new UnitException("Month enum cannot be used to set $unit"); } return Month::int($value); } return $value; } }
PHP
{ "end_line": 379, "name": "create", "signature": "public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null): ?static", "start_line": 322 }
{ "class_name": "Creator", "class_signature": "trait Creator", "namespace": "Carbon\\Traits" }
createSafe
Carbon/src/Carbon/Traits/Creator.php
public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null): ?static { $month = self::monthToInt($month); $fields = static::getRangesByUnit(); foreach ($fields as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field < $range[0] || $$field > $range[1])) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } $instance = static::create($year, $month, $day, $hour, $minute, $second, $timezone); foreach (array_reverse($fields) as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field !== $instance->$field)) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } return $instance; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\UnitException; use Carbon\Month; use Carbon\Translator; use Carbon\WeekDay; use Closure; use DateMalformedStringException; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Exception; use ReturnTypeWillChange; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Creator. * * Static creators. * * Depends on the following methods: * * @method static Carbon|CarbonImmutable getTestNow() */ trait Creator { use ObjectInitialisation; use LocalFactory; /** * The errors that can occur. */ protected static array|bool $lastErrors = false; /** * Create a new Carbon instance. * * Please see the testing aids section (specifically static::setTestNow()) * for more on the possibility of this constructor returning a test instance. * * @throws InvalidFormatException */ public function __construct( DateTimeInterface|WeekDay|Month|string|int|float|null $time = null, DateTimeZone|string|int|null $timezone = null, ) { $this->initLocalFactory(); if ($time instanceof Month) { $time = $time->name.' 1'; } elseif ($time instanceof WeekDay) { $time = $time->name; } elseif ($time instanceof DateTimeInterface) { $time = $this->constructTimezoneFromDateTime($time, $timezone)->format('Y-m-d H:i:s.u'); } if (\is_string($time) && str_starts_with($time, '@')) { $time = static::createFromTimestampUTC(substr($time, 1))->format('Y-m-d\TH:i:s.uP'); } elseif (is_numeric($time) && (!\is_string($time) || !preg_match('/^\d{1,14}$/', $time))) { $time = static::createFromTimestampUTC($time)->format('Y-m-d\TH:i:s.uP'); } // If the class has a test now set, and we are trying to create a now() // instance then override as required $isNow = \in_array($time, [null, '', 'now'], true); $timezone = static::safeCreateDateTimeZone($timezone) ?? null; if ( ($this->clock || ( method_exists(static::class, 'hasTestNow') && method_exists(static::class, 'getTestNow') && static::hasTestNow() )) && ($isNow || static::hasRelativeKeywords($time)) ) { $this->mockConstructorParameters($time, $timezone); } try { parent::__construct($time ?? 'now', $timezone); } catch (Exception $exception) { throw new InvalidFormatException($exception->getMessage(), 0, $exception); } $this->constructedObjectId = spl_object_hash($this); self::setLastErrors(parent::getLastErrors()); } /** * Get timezone from a datetime instance. */ private function constructTimezoneFromDateTime( DateTimeInterface $date, DateTimeZone|string|int|null &$timezone, ): DateTimeInterface { if ($timezone !== null) { $safeTz = static::safeCreateDateTimeZone($timezone); if ($safeTz) { $date = ($date instanceof DateTimeImmutable ? $date : clone $date)->setTimezone($safeTz); } return $date; } $timezone = $date->getTimezone(); return $date; } /** * Update constructedObjectId on cloned. */ public function __clone(): void { $this->constructedObjectId = spl_object_hash($this); } /** * Create a Carbon instance from a DateTime one. */ public static function instance(DateTimeInterface $date): static { if ($date instanceof static) { return clone $date; } $instance = parent::createFromFormat('U.u', $date->format('U.u')) ->setTimezone($date->getTimezone()); if ($date instanceof CarbonInterface) { $settings = $date->getSettings(); if (!$date->hasLocalTranslator()) { unset($settings['locale']); } $instance->settings($settings); } return $instance; } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function rawParse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { if ($time instanceof DateTimeInterface) { return static::instance($time); } try { return new static($time, $timezone); } catch (Exception $exception) { // @codeCoverageIgnoreStart try { $date = @static::now($timezone)->change($time); } catch (DateMalformedStringException|InvalidFormatException) { $date = null; } // @codeCoverageIgnoreEnd return $date ?? throw new InvalidFormatException("Could not parse '$time': ".$exception->getMessage(), 0, $exception); } } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function parse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { $function = static::$parseFunction; if (!$function) { return static::rawParse($time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.). * * @param string $time date/time string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be * used instead. * @param DateTimeZone|string|int|null $timezone optional timezone for the new instance. * * @throws InvalidFormatException */ public static function parseFromLocale( string $time, ?string $locale = null, DateTimeZone|string|int|null $timezone = null, ): static { return static::rawParse(static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Get a Carbon instance for the current date and time. */ public static function now(DateTimeZone|string|int|null $timezone = null): static { return new static(null, $timezone); } /** * Create a Carbon instance for today. */ public static function today(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('today', $timezone); } /** * Create a Carbon instance for tomorrow. */ public static function tomorrow(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('tomorrow', $timezone); } /** * Create a Carbon instance for yesterday. */ public static function yesterday(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('yesterday', $timezone); } private static function assertBetween($unit, $value, $min, $max): void { if (static::isStrictModeEnabled() && ($value < $min || $value > $max)) { throw new OutOfRangeException($unit, $min, $max, $value); } } private static function createNowInstance($timezone) { if (!static::hasTestNow()) { return static::now($timezone); } $now = static::getTestNow(); if ($now instanceof Closure) { return $now(static::now($timezone)); } $now = $now->avoidMutation(); return $timezone === null ? $now : $now->setTimezone($timezone); } /** * Create a new Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * @param DateTimeInterface|string|int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null): ?static { $month = self::monthToInt($month); if ((\is_string($year) && !is_numeric($year)) || $year instanceof DateTimeInterface) { return static::parse($year, $timezone ?? (\is_string($month) || $month instanceof DateTimeZone ? $month : null)); } $defaults = null; $getDefault = function ($unit) use ($timezone, &$defaults) { if ($defaults === null) { $now = self::createNowInstance($timezone); $defaults = array_combine([ 'year', 'month', 'day', 'hour', 'minute', 'second', ], explode('-', $now->rawFormat('Y-n-j-G-i-s.u'))); } return $defaults[$unit]; }; $year = $year ?? $getDefault('year'); $month = $month ?? $getDefault('month'); $day = $day ?? $getDefault('day'); $hour = $hour ?? $getDefault('hour'); $minute = $minute ?? $getDefault('minute'); $second = (float) ($second ?? $getDefault('second')); self::assertBetween('month', $month, 0, 99); self::assertBetween('day', $day, 0, 99); self::assertBetween('hour', $hour, 0, 99); self::assertBetween('minute', $minute, 0, 99); self::assertBetween('second', $second, 0, 99); $fixYear = null; if ($year < 0) { $fixYear = $year; $year = 0; } elseif ($year > 9999) { $fixYear = $year - 9999; $year = 9999; } $second = ($second < 10 ? '0' : '').number_format($second, 6); $instance = static::rawCreateFromFormat('!Y-n-j G:i:s.u', \sprintf('%s-%s-%s %s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $timezone); if ($instance && $fixYear !== null) { $instance = $instance->addYears($fixYear); } return $instance ?? null; } /** * Create a new safe Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * If one of the set values is not valid, an InvalidDateException * will be thrown. * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidDateException * * @return static|null */ public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null): ?static { $month = self::monthToInt($month); $fields = static::getRangesByUnit(); foreach ($fields as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field < $range[0] || $$field > $range[1])) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } $instance = static::create($year, $month, $day, $hour, $minute, $second, $timezone); foreach (array_reverse($fields) as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field !== $instance->$field)) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } return $instance; } /** * Create a new Carbon instance from a specific date and time using strict validation. * * @see create() * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $timezone = null): static { $initialStrictMode = static::isStrictModeEnabled(); static::useStrictMode(true); try { $date = static::create($year, $month, $day, $hour, $minute, $second, $timezone); } finally { static::useStrictMode($initialStrictMode); } return $date; } /** * Create a Carbon instance from just a date. The time portion is set to now. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, null, null, null, $timezone); } /** * Create a Carbon instance from just a date. The time portion is set to midnight. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createMidnightDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, 0, 0, 0, $timezone); } /** * Create a Carbon instance from just a time. The date portion is set to today. * * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromTime($hour = 0, $minute = 0, $second = 0, $timezone = null): static { return static::create(null, null, null, $hour, $minute, $second, $timezone); } /** * Create a Carbon instance from a time string. The date portion is set to today. * * @throws InvalidFormatException */ public static function createFromTimeString(string $time, DateTimeZone|string|int|null $timezone = null): static { return static::today($timezone)->setTimeFromTimeString($time); } private static function createFromFormatAndTimezone( string $format, string $time, DateTimeZone|string|int|null $originalTimezone, ): ?DateTimeInterface { if ($originalTimezone === null) { return parent::createFromFormat($format, $time) ?: null; } $timezone = \is_int($originalTimezone) ? self::getOffsetTimezone($originalTimezone) : $originalTimezone; $timezone = static::safeCreateDateTimeZone($timezone, $originalTimezone); return parent::createFromFormat($format, $time, $timezone) ?: null; } private static function getOffsetTimezone(int $offset): string { $minutes = (int) ($offset * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE); return @timezone_name_from_abbr('', $minutes, 1) ?: throw new InvalidTimeZoneException( "Invalid offset timezone $offset", ); } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function rawCreateFromFormat(string $format, string $time, $timezone = null): ?static { // Work-around for https://bugs.php.net/bug.php?id=80141 $format = preg_replace('/(?<!\\\\)((?:\\\\{2})*)c/', '$1Y-m-d\TH:i:sP', $format); if (preg_match('/(?<!\\\\)(?:\\\\{2})*(a|A)/', $format, $aMatches, PREG_OFFSET_CAPTURE) && preg_match('/(?<!\\\\)(?:\\\\{2})*(h|g|H|G)/', $format, $hMatches, PREG_OFFSET_CAPTURE) && $aMatches[1][1] < $hMatches[1][1] && preg_match('/(am|pm|AM|PM)/', $time) ) { $format = preg_replace('/^(.*)(?<!\\\\)((?:\\\\{2})*)(a|A)(.*)$/U', '$1$2$4 $3', $format); $time = preg_replace('/^(.*)(am|pm|AM|PM)(.*)$/U', '$1$3 $2', $time); } if ($timezone === false) { $timezone = null; } // First attempt to create an instance, so that error messages are based on the unmodified format. $date = self::createFromFormatAndTimezone($format, $time, $timezone); $lastErrors = parent::getLastErrors(); /** @var \Carbon\CarbonImmutable|\Carbon\Carbon|null $mock */ $mock = static::getMockedTestNow($timezone); if ($mock && $date instanceof DateTimeInterface) { // Set timezone from mock if custom timezone was neither given directly nor as a part of format. // First let's skip the part that will be ignored by the parser. $nonEscaped = '(?<!\\\\)(\\\\{2})*'; $nonIgnored = preg_replace("/^.*{$nonEscaped}!/s", '', $format); if ($timezone === null && !preg_match("/{$nonEscaped}[eOPT]/", $nonIgnored)) { $timezone = clone $mock->getTimezone(); } $mock = $mock->copy(); // Prepend mock datetime only if the format does not contain non escaped unix epoch reset flag. if (!preg_match("/{$nonEscaped}[!|]/", $format)) { if (preg_match('/[HhGgisvuB]/', $format)) { $mock = $mock->setTime(0, 0); } $format = static::MOCK_DATETIME_FORMAT.' '.$format; $time = ($mock instanceof self ? $mock->rawFormat(static::MOCK_DATETIME_FORMAT) : $mock->format(static::MOCK_DATETIME_FORMAT)).' '.$time; } // Regenerate date from the modified format to base result on the mocked instance instead of now. $date = self::createFromFormatAndTimezone($format, $time, $timezone); } if ($date instanceof DateTimeInterface) { $instance = static::instance($date); $instance::setLastErrors($lastErrors); return $instance; } if (static::isStrictModeEnabled()) { throw new InvalidFormatException(implode(PHP_EOL, (array) $lastErrors['errors'])); } return null; } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ #[ReturnTypeWillChange] public static function createFromFormat($format, $time, $timezone = null): ?static { $function = static::$createFromFormatFunction; // format is a single numeric unit if (\is_int($time) && \in_array(ltrim($format, '!'), ['U', 'Y', 'y', 'X', 'x', 'm', 'n', 'd', 'j', 'w', 'W', 'H', 'h', 'G', 'g', 'i', 's', 'u', 'z', 'v'], true)) { $time = (string) $time; } if (!\is_string($time)) { @trigger_error( 'createFromFormat() $time parameter will only accept string or integer for 1-letter format representing a numeric unit in the next version', \E_USER_DEPRECATED, ); $time = (string) $time; } if (!$function) { return static::rawCreateFromFormat($format, $time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()). * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone optional timezone * @param string|null $locale locale to be used for LTS, LT, LL, LLL, etc. macro-formats (en by fault, unneeded if no such macro-format in use) * @param TranslatorInterface|null $translator optional custom translator to use for macro-formats * * @throws InvalidFormatException * * @return static|null */ public static function createFromIsoFormat( string $format, string $time, $timezone = null, ?string $locale = CarbonInterface::DEFAULT_LOCALE, ?TranslatorInterface $translator = null ): ?static { $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*(LTS|LT|[Ll]{1,4})/', function ($match) use ($locale, $translator) { [$code] = $match; static $formats = null; if ($formats === null) { $translator ??= Translator::get($locale); $formats = [ 'LT' => static::getTranslationMessageWith($translator, 'formats.LT', $locale), 'LTS' => static::getTranslationMessageWith($translator, 'formats.LTS', $locale), 'L' => static::getTranslationMessageWith($translator, 'formats.L', $locale), 'LL' => static::getTranslationMessageWith($translator, 'formats.LL', $locale), 'LLL' => static::getTranslationMessageWith($translator, 'formats.LLL', $locale), 'LLLL' => static::getTranslationMessageWith($translator, 'formats.LLLL', $locale), ]; } return $formats[$code] ?? preg_replace_callback( '/MMMM|MM|DD|dddd/', static fn (array $code) => mb_substr($code[0], 1), $formats[strtoupper($code)] ?? '', ); }, $format); $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*('.CarbonInterface::ISO_FORMAT_REGEXP.'|[A-Za-z])/', function ($match) { [$code] = $match; static $replacements = null; if ($replacements === null) { $replacements = [ 'OD' => 'd', 'OM' => 'M', 'OY' => 'Y', 'OH' => 'G', 'Oh' => 'g', 'Om' => 'i', 'Os' => 's', 'D' => 'd', 'DD' => 'd', 'Do' => 'd', 'd' => '!', 'dd' => '!', 'ddd' => 'D', 'dddd' => 'D', 'DDD' => 'z', 'DDDD' => 'z', 'DDDo' => 'z', 'e' => '!', 'E' => '!', 'H' => 'G', 'HH' => 'H', 'h' => 'g', 'hh' => 'h', 'k' => 'G', 'kk' => 'G', 'hmm' => 'gi', 'hmmss' => 'gis', 'Hmm' => 'Gi', 'Hmmss' => 'Gis', 'm' => 'i', 'mm' => 'i', 'a' => 'a', 'A' => 'a', 's' => 's', 'ss' => 's', 'S' => '*', 'SS' => '*', 'SSS' => '*', 'SSSS' => '*', 'SSSSS' => '*', 'SSSSSS' => 'u', 'SSSSSSS' => 'u*', 'SSSSSSSS' => 'u*', 'SSSSSSSSS' => 'u*', 'M' => 'm', 'MM' => 'm', 'MMM' => 'M', 'MMMM' => 'M', 'Mo' => 'm', 'Q' => '!', 'Qo' => '!', 'G' => '!', 'GG' => '!', 'GGG' => '!', 'GGGG' => '!', 'GGGGG' => '!', 'g' => '!', 'gg' => '!', 'ggg' => '!', 'gggg' => '!', 'ggggg' => '!', 'W' => '!', 'WW' => '!', 'Wo' => '!', 'w' => '!', 'ww' => '!', 'wo' => '!', 'x' => 'U???', 'X' => 'U', 'Y' => 'Y', 'YY' => 'y', 'YYYY' => 'Y', 'YYYYY' => 'Y', 'YYYYYY' => 'Y', 'z' => 'e', 'zz' => 'e', 'Z' => 'e', 'ZZ' => 'e', ]; } $format = $replacements[$code] ?? '?'; if ($format === '!') { throw new InvalidFormatException("Format $code not supported for creation."); } return $format; }, $format); return static::rawCreateFromFormat($format, $time, $timezone); } /** * Create a Carbon instance from a specific format and a string in a given language. * * @param string $format Datetime format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null): ?static { $format = preg_replace_callback( '/(?:\\\\[a-zA-Z]|[bfkqCEJKQRV]){2,}/', static function (array $match) use ($locale): string { $word = str_replace('\\', '', $match[0]); $translatedWord = static::translateTimeString($word, $locale, static::DEFAULT_LOCALE); return $word === $translatedWord ? $match[0] : preg_replace('/[a-zA-Z]/', '\\\\$0', $translatedWord); }, $format ); return static::rawCreateFromFormat($format, static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Create a Carbon instance from a specific ISO format and a string in a given language. * * @param string $format Datetime ISO format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleIsoFormat(string $format, string $locale, string $time, $timezone = null): ?static { $time = static::translateTimeString($time, $locale, static::DEFAULT_LOCALE, CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS | CarbonInterface::TRANSLATE_MERIDIEM); return static::createFromIsoFormat($format, $time, $timezone, $locale); } /** * Make a Carbon instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed $var * * @throws InvalidFormatException * * @return static|null */ public static function make($var, DateTimeZone|string|null $timezone = null): ?static { if ($var instanceof DateTimeInterface) { return static::instance($var); } $date = null; if (\is_string($var)) { $var = trim($var); if (!preg_match('/^P[\dT]/', $var) && !preg_match('/^R\d/', $var) && preg_match('/[a-z\d]/i', $var) ) { $date = static::parse($var, $timezone); } } return $date; } /** * Set last errors. * * @param array|bool $lastErrors * * @return void */ private static function setLastErrors($lastErrors): void { static::$lastErrors = $lastErrors; } /** * {@inheritdoc} */ public static function getLastErrors(): array|false { return static::$lastErrors; } private static function monthToInt(mixed $value, string $unit = 'month'): mixed { if ($value instanceof Month) { if ($unit !== 'month') { throw new UnitException("Month enum cannot be used to set $unit"); } return Month::int($value); } return $value; } }
PHP
{ "end_line": 436, "name": "createSafe", "signature": "public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null): ?static", "start_line": 408 }
{ "class_name": "Creator", "class_signature": "trait Creator", "namespace": "Carbon\\Traits" }
rawCreateFromFormat
Carbon/src/Carbon/Traits/Creator.php
public static function rawCreateFromFormat(string $format, string $time, $timezone = null): ?static { // Work-around for https://bugs.php.net/bug.php?id=80141 $format = preg_replace('/(?<!\\\\)((?:\\\\{2})*)c/', '$1Y-m-d\TH:i:sP', $format); if (preg_match('/(?<!\\\\)(?:\\\\{2})*(a|A)/', $format, $aMatches, PREG_OFFSET_CAPTURE) && preg_match('/(?<!\\\\)(?:\\\\{2})*(h|g|H|G)/', $format, $hMatches, PREG_OFFSET_CAPTURE) && $aMatches[1][1] < $hMatches[1][1] && preg_match('/(am|pm|AM|PM)/', $time) ) { $format = preg_replace('/^(.*)(?<!\\\\)((?:\\\\{2})*)(a|A)(.*)$/U', '$1$2$4 $3', $format); $time = preg_replace('/^(.*)(am|pm|AM|PM)(.*)$/U', '$1$3 $2', $time); } if ($timezone === false) { $timezone = null; } // First attempt to create an instance, so that error messages are based on the unmodified format. $date = self::createFromFormatAndTimezone($format, $time, $timezone); $lastErrors = parent::getLastErrors(); /** @var \Carbon\CarbonImmutable|\Carbon\Carbon|null $mock */ $mock = static::getMockedTestNow($timezone); if ($mock && $date instanceof DateTimeInterface) { // Set timezone from mock if custom timezone was neither given directly nor as a part of format. // First let's skip the part that will be ignored by the parser. $nonEscaped = '(?<!\\\\)(\\\\{2})*'; $nonIgnored = preg_replace("/^.*{$nonEscaped}!/s", '', $format); if ($timezone === null && !preg_match("/{$nonEscaped}[eOPT]/", $nonIgnored)) { $timezone = clone $mock->getTimezone(); } $mock = $mock->copy(); // Prepend mock datetime only if the format does not contain non escaped unix epoch reset flag. if (!preg_match("/{$nonEscaped}[!|]/", $format)) { if (preg_match('/[HhGgisvuB]/', $format)) { $mock = $mock->setTime(0, 0); } $format = static::MOCK_DATETIME_FORMAT.' '.$format; $time = ($mock instanceof self ? $mock->rawFormat(static::MOCK_DATETIME_FORMAT) : $mock->format(static::MOCK_DATETIME_FORMAT)).' '.$time; } // Regenerate date from the modified format to base result on the mocked instance instead of now. $date = self::createFromFormatAndTimezone($format, $time, $timezone); } if ($date instanceof DateTimeInterface) { $instance = static::instance($date); $instance::setLastErrors($lastErrors); return $instance; } if (static::isStrictModeEnabled()) { throw new InvalidFormatException(implode(PHP_EOL, (array) $lastErrors['errors'])); } return null; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\UnitException; use Carbon\Month; use Carbon\Translator; use Carbon\WeekDay; use Closure; use DateMalformedStringException; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Exception; use ReturnTypeWillChange; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Creator. * * Static creators. * * Depends on the following methods: * * @method static Carbon|CarbonImmutable getTestNow() */ trait Creator { use ObjectInitialisation; use LocalFactory; /** * The errors that can occur. */ protected static array|bool $lastErrors = false; /** * Create a new Carbon instance. * * Please see the testing aids section (specifically static::setTestNow()) * for more on the possibility of this constructor returning a test instance. * * @throws InvalidFormatException */ public function __construct( DateTimeInterface|WeekDay|Month|string|int|float|null $time = null, DateTimeZone|string|int|null $timezone = null, ) { $this->initLocalFactory(); if ($time instanceof Month) { $time = $time->name.' 1'; } elseif ($time instanceof WeekDay) { $time = $time->name; } elseif ($time instanceof DateTimeInterface) { $time = $this->constructTimezoneFromDateTime($time, $timezone)->format('Y-m-d H:i:s.u'); } if (\is_string($time) && str_starts_with($time, '@')) { $time = static::createFromTimestampUTC(substr($time, 1))->format('Y-m-d\TH:i:s.uP'); } elseif (is_numeric($time) && (!\is_string($time) || !preg_match('/^\d{1,14}$/', $time))) { $time = static::createFromTimestampUTC($time)->format('Y-m-d\TH:i:s.uP'); } // If the class has a test now set, and we are trying to create a now() // instance then override as required $isNow = \in_array($time, [null, '', 'now'], true); $timezone = static::safeCreateDateTimeZone($timezone) ?? null; if ( ($this->clock || ( method_exists(static::class, 'hasTestNow') && method_exists(static::class, 'getTestNow') && static::hasTestNow() )) && ($isNow || static::hasRelativeKeywords($time)) ) { $this->mockConstructorParameters($time, $timezone); } try { parent::__construct($time ?? 'now', $timezone); } catch (Exception $exception) { throw new InvalidFormatException($exception->getMessage(), 0, $exception); } $this->constructedObjectId = spl_object_hash($this); self::setLastErrors(parent::getLastErrors()); } /** * Get timezone from a datetime instance. */ private function constructTimezoneFromDateTime( DateTimeInterface $date, DateTimeZone|string|int|null &$timezone, ): DateTimeInterface { if ($timezone !== null) { $safeTz = static::safeCreateDateTimeZone($timezone); if ($safeTz) { $date = ($date instanceof DateTimeImmutable ? $date : clone $date)->setTimezone($safeTz); } return $date; } $timezone = $date->getTimezone(); return $date; } /** * Update constructedObjectId on cloned. */ public function __clone(): void { $this->constructedObjectId = spl_object_hash($this); } /** * Create a Carbon instance from a DateTime one. */ public static function instance(DateTimeInterface $date): static { if ($date instanceof static) { return clone $date; } $instance = parent::createFromFormat('U.u', $date->format('U.u')) ->setTimezone($date->getTimezone()); if ($date instanceof CarbonInterface) { $settings = $date->getSettings(); if (!$date->hasLocalTranslator()) { unset($settings['locale']); } $instance->settings($settings); } return $instance; } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function rawParse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { if ($time instanceof DateTimeInterface) { return static::instance($time); } try { return new static($time, $timezone); } catch (Exception $exception) { // @codeCoverageIgnoreStart try { $date = @static::now($timezone)->change($time); } catch (DateMalformedStringException|InvalidFormatException) { $date = null; } // @codeCoverageIgnoreEnd return $date ?? throw new InvalidFormatException("Could not parse '$time': ".$exception->getMessage(), 0, $exception); } } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function parse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { $function = static::$parseFunction; if (!$function) { return static::rawParse($time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.). * * @param string $time date/time string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be * used instead. * @param DateTimeZone|string|int|null $timezone optional timezone for the new instance. * * @throws InvalidFormatException */ public static function parseFromLocale( string $time, ?string $locale = null, DateTimeZone|string|int|null $timezone = null, ): static { return static::rawParse(static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Get a Carbon instance for the current date and time. */ public static function now(DateTimeZone|string|int|null $timezone = null): static { return new static(null, $timezone); } /** * Create a Carbon instance for today. */ public static function today(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('today', $timezone); } /** * Create a Carbon instance for tomorrow. */ public static function tomorrow(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('tomorrow', $timezone); } /** * Create a Carbon instance for yesterday. */ public static function yesterday(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('yesterday', $timezone); } private static function assertBetween($unit, $value, $min, $max): void { if (static::isStrictModeEnabled() && ($value < $min || $value > $max)) { throw new OutOfRangeException($unit, $min, $max, $value); } } private static function createNowInstance($timezone) { if (!static::hasTestNow()) { return static::now($timezone); } $now = static::getTestNow(); if ($now instanceof Closure) { return $now(static::now($timezone)); } $now = $now->avoidMutation(); return $timezone === null ? $now : $now->setTimezone($timezone); } /** * Create a new Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * @param DateTimeInterface|string|int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null): ?static { $month = self::monthToInt($month); if ((\is_string($year) && !is_numeric($year)) || $year instanceof DateTimeInterface) { return static::parse($year, $timezone ?? (\is_string($month) || $month instanceof DateTimeZone ? $month : null)); } $defaults = null; $getDefault = function ($unit) use ($timezone, &$defaults) { if ($defaults === null) { $now = self::createNowInstance($timezone); $defaults = array_combine([ 'year', 'month', 'day', 'hour', 'minute', 'second', ], explode('-', $now->rawFormat('Y-n-j-G-i-s.u'))); } return $defaults[$unit]; }; $year = $year ?? $getDefault('year'); $month = $month ?? $getDefault('month'); $day = $day ?? $getDefault('day'); $hour = $hour ?? $getDefault('hour'); $minute = $minute ?? $getDefault('minute'); $second = (float) ($second ?? $getDefault('second')); self::assertBetween('month', $month, 0, 99); self::assertBetween('day', $day, 0, 99); self::assertBetween('hour', $hour, 0, 99); self::assertBetween('minute', $minute, 0, 99); self::assertBetween('second', $second, 0, 99); $fixYear = null; if ($year < 0) { $fixYear = $year; $year = 0; } elseif ($year > 9999) { $fixYear = $year - 9999; $year = 9999; } $second = ($second < 10 ? '0' : '').number_format($second, 6); $instance = static::rawCreateFromFormat('!Y-n-j G:i:s.u', \sprintf('%s-%s-%s %s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $timezone); if ($instance && $fixYear !== null) { $instance = $instance->addYears($fixYear); } return $instance ?? null; } /** * Create a new safe Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * If one of the set values is not valid, an InvalidDateException * will be thrown. * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidDateException * * @return static|null */ public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null): ?static { $month = self::monthToInt($month); $fields = static::getRangesByUnit(); foreach ($fields as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field < $range[0] || $$field > $range[1])) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } $instance = static::create($year, $month, $day, $hour, $minute, $second, $timezone); foreach (array_reverse($fields) as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field !== $instance->$field)) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } return $instance; } /** * Create a new Carbon instance from a specific date and time using strict validation. * * @see create() * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $timezone = null): static { $initialStrictMode = static::isStrictModeEnabled(); static::useStrictMode(true); try { $date = static::create($year, $month, $day, $hour, $minute, $second, $timezone); } finally { static::useStrictMode($initialStrictMode); } return $date; } /** * Create a Carbon instance from just a date. The time portion is set to now. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, null, null, null, $timezone); } /** * Create a Carbon instance from just a date. The time portion is set to midnight. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createMidnightDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, 0, 0, 0, $timezone); } /** * Create a Carbon instance from just a time. The date portion is set to today. * * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromTime($hour = 0, $minute = 0, $second = 0, $timezone = null): static { return static::create(null, null, null, $hour, $minute, $second, $timezone); } /** * Create a Carbon instance from a time string. The date portion is set to today. * * @throws InvalidFormatException */ public static function createFromTimeString(string $time, DateTimeZone|string|int|null $timezone = null): static { return static::today($timezone)->setTimeFromTimeString($time); } private static function createFromFormatAndTimezone( string $format, string $time, DateTimeZone|string|int|null $originalTimezone, ): ?DateTimeInterface { if ($originalTimezone === null) { return parent::createFromFormat($format, $time) ?: null; } $timezone = \is_int($originalTimezone) ? self::getOffsetTimezone($originalTimezone) : $originalTimezone; $timezone = static::safeCreateDateTimeZone($timezone, $originalTimezone); return parent::createFromFormat($format, $time, $timezone) ?: null; } private static function getOffsetTimezone(int $offset): string { $minutes = (int) ($offset * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE); return @timezone_name_from_abbr('', $minutes, 1) ?: throw new InvalidTimeZoneException( "Invalid offset timezone $offset", ); } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function rawCreateFromFormat(string $format, string $time, $timezone = null): ?static { // Work-around for https://bugs.php.net/bug.php?id=80141 $format = preg_replace('/(?<!\\\\)((?:\\\\{2})*)c/', '$1Y-m-d\TH:i:sP', $format); if (preg_match('/(?<!\\\\)(?:\\\\{2})*(a|A)/', $format, $aMatches, PREG_OFFSET_CAPTURE) && preg_match('/(?<!\\\\)(?:\\\\{2})*(h|g|H|G)/', $format, $hMatches, PREG_OFFSET_CAPTURE) && $aMatches[1][1] < $hMatches[1][1] && preg_match('/(am|pm|AM|PM)/', $time) ) { $format = preg_replace('/^(.*)(?<!\\\\)((?:\\\\{2})*)(a|A)(.*)$/U', '$1$2$4 $3', $format); $time = preg_replace('/^(.*)(am|pm|AM|PM)(.*)$/U', '$1$3 $2', $time); } if ($timezone === false) { $timezone = null; } // First attempt to create an instance, so that error messages are based on the unmodified format. $date = self::createFromFormatAndTimezone($format, $time, $timezone); $lastErrors = parent::getLastErrors(); /** @var \Carbon\CarbonImmutable|\Carbon\Carbon|null $mock */ $mock = static::getMockedTestNow($timezone); if ($mock && $date instanceof DateTimeInterface) { // Set timezone from mock if custom timezone was neither given directly nor as a part of format. // First let's skip the part that will be ignored by the parser. $nonEscaped = '(?<!\\\\)(\\\\{2})*'; $nonIgnored = preg_replace("/^.*{$nonEscaped}!/s", '', $format); if ($timezone === null && !preg_match("/{$nonEscaped}[eOPT]/", $nonIgnored)) { $timezone = clone $mock->getTimezone(); } $mock = $mock->copy(); // Prepend mock datetime only if the format does not contain non escaped unix epoch reset flag. if (!preg_match("/{$nonEscaped}[!|]/", $format)) { if (preg_match('/[HhGgisvuB]/', $format)) { $mock = $mock->setTime(0, 0); } $format = static::MOCK_DATETIME_FORMAT.' '.$format; $time = ($mock instanceof self ? $mock->rawFormat(static::MOCK_DATETIME_FORMAT) : $mock->format(static::MOCK_DATETIME_FORMAT)).' '.$time; } // Regenerate date from the modified format to base result on the mocked instance instead of now. $date = self::createFromFormatAndTimezone($format, $time, $timezone); } if ($date instanceof DateTimeInterface) { $instance = static::instance($date); $instance::setLastErrors($lastErrors); return $instance; } if (static::isStrictModeEnabled()) { throw new InvalidFormatException(implode(PHP_EOL, (array) $lastErrors['errors'])); } return null; } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ #[ReturnTypeWillChange] public static function createFromFormat($format, $time, $timezone = null): ?static { $function = static::$createFromFormatFunction; // format is a single numeric unit if (\is_int($time) && \in_array(ltrim($format, '!'), ['U', 'Y', 'y', 'X', 'x', 'm', 'n', 'd', 'j', 'w', 'W', 'H', 'h', 'G', 'g', 'i', 's', 'u', 'z', 'v'], true)) { $time = (string) $time; } if (!\is_string($time)) { @trigger_error( 'createFromFormat() $time parameter will only accept string or integer for 1-letter format representing a numeric unit in the next version', \E_USER_DEPRECATED, ); $time = (string) $time; } if (!$function) { return static::rawCreateFromFormat($format, $time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()). * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone optional timezone * @param string|null $locale locale to be used for LTS, LT, LL, LLL, etc. macro-formats (en by fault, unneeded if no such macro-format in use) * @param TranslatorInterface|null $translator optional custom translator to use for macro-formats * * @throws InvalidFormatException * * @return static|null */ public static function createFromIsoFormat( string $format, string $time, $timezone = null, ?string $locale = CarbonInterface::DEFAULT_LOCALE, ?TranslatorInterface $translator = null ): ?static { $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*(LTS|LT|[Ll]{1,4})/', function ($match) use ($locale, $translator) { [$code] = $match; static $formats = null; if ($formats === null) { $translator ??= Translator::get($locale); $formats = [ 'LT' => static::getTranslationMessageWith($translator, 'formats.LT', $locale), 'LTS' => static::getTranslationMessageWith($translator, 'formats.LTS', $locale), 'L' => static::getTranslationMessageWith($translator, 'formats.L', $locale), 'LL' => static::getTranslationMessageWith($translator, 'formats.LL', $locale), 'LLL' => static::getTranslationMessageWith($translator, 'formats.LLL', $locale), 'LLLL' => static::getTranslationMessageWith($translator, 'formats.LLLL', $locale), ]; } return $formats[$code] ?? preg_replace_callback( '/MMMM|MM|DD|dddd/', static fn (array $code) => mb_substr($code[0], 1), $formats[strtoupper($code)] ?? '', ); }, $format); $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*('.CarbonInterface::ISO_FORMAT_REGEXP.'|[A-Za-z])/', function ($match) { [$code] = $match; static $replacements = null; if ($replacements === null) { $replacements = [ 'OD' => 'd', 'OM' => 'M', 'OY' => 'Y', 'OH' => 'G', 'Oh' => 'g', 'Om' => 'i', 'Os' => 's', 'D' => 'd', 'DD' => 'd', 'Do' => 'd', 'd' => '!', 'dd' => '!', 'ddd' => 'D', 'dddd' => 'D', 'DDD' => 'z', 'DDDD' => 'z', 'DDDo' => 'z', 'e' => '!', 'E' => '!', 'H' => 'G', 'HH' => 'H', 'h' => 'g', 'hh' => 'h', 'k' => 'G', 'kk' => 'G', 'hmm' => 'gi', 'hmmss' => 'gis', 'Hmm' => 'Gi', 'Hmmss' => 'Gis', 'm' => 'i', 'mm' => 'i', 'a' => 'a', 'A' => 'a', 's' => 's', 'ss' => 's', 'S' => '*', 'SS' => '*', 'SSS' => '*', 'SSSS' => '*', 'SSSSS' => '*', 'SSSSSS' => 'u', 'SSSSSSS' => 'u*', 'SSSSSSSS' => 'u*', 'SSSSSSSSS' => 'u*', 'M' => 'm', 'MM' => 'm', 'MMM' => 'M', 'MMMM' => 'M', 'Mo' => 'm', 'Q' => '!', 'Qo' => '!', 'G' => '!', 'GG' => '!', 'GGG' => '!', 'GGGG' => '!', 'GGGGG' => '!', 'g' => '!', 'gg' => '!', 'ggg' => '!', 'gggg' => '!', 'ggggg' => '!', 'W' => '!', 'WW' => '!', 'Wo' => '!', 'w' => '!', 'ww' => '!', 'wo' => '!', 'x' => 'U???', 'X' => 'U', 'Y' => 'Y', 'YY' => 'y', 'YYYY' => 'Y', 'YYYYY' => 'Y', 'YYYYYY' => 'Y', 'z' => 'e', 'zz' => 'e', 'Z' => 'e', 'ZZ' => 'e', ]; } $format = $replacements[$code] ?? '?'; if ($format === '!') { throw new InvalidFormatException("Format $code not supported for creation."); } return $format; }, $format); return static::rawCreateFromFormat($format, $time, $timezone); } /** * Create a Carbon instance from a specific format and a string in a given language. * * @param string $format Datetime format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null): ?static { $format = preg_replace_callback( '/(?:\\\\[a-zA-Z]|[bfkqCEJKQRV]){2,}/', static function (array $match) use ($locale): string { $word = str_replace('\\', '', $match[0]); $translatedWord = static::translateTimeString($word, $locale, static::DEFAULT_LOCALE); return $word === $translatedWord ? $match[0] : preg_replace('/[a-zA-Z]/', '\\\\$0', $translatedWord); }, $format ); return static::rawCreateFromFormat($format, static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Create a Carbon instance from a specific ISO format and a string in a given language. * * @param string $format Datetime ISO format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleIsoFormat(string $format, string $locale, string $time, $timezone = null): ?static { $time = static::translateTimeString($time, $locale, static::DEFAULT_LOCALE, CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS | CarbonInterface::TRANSLATE_MERIDIEM); return static::createFromIsoFormat($format, $time, $timezone, $locale); } /** * Make a Carbon instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed $var * * @throws InvalidFormatException * * @return static|null */ public static function make($var, DateTimeZone|string|null $timezone = null): ?static { if ($var instanceof DateTimeInterface) { return static::instance($var); } $date = null; if (\is_string($var)) { $var = trim($var); if (!preg_match('/^P[\dT]/', $var) && !preg_match('/^R\d/', $var) && preg_match('/[a-z\d]/i', $var) ) { $date = static::parse($var, $timezone); } } return $date; } /** * Set last errors. * * @param array|bool $lastErrors * * @return void */ private static function setLastErrors($lastErrors): void { static::$lastErrors = $lastErrors; } /** * {@inheritdoc} */ public static function getLastErrors(): array|false { return static::$lastErrors; } private static function monthToInt(mixed $value, string $unit = 'month'): mixed { if ($value instanceof Month) { if ($unit !== 'month') { throw new UnitException("Month enum cannot be used to set $unit"); } return Month::int($value); } return $value; } }
PHP
{ "end_line": 629, "name": "rawCreateFromFormat", "signature": "public static function rawCreateFromFormat(string $format, string $time, $timezone = null): ?static", "start_line": 566 }
{ "class_name": "Creator", "class_signature": "trait Creator", "namespace": "Carbon\\Traits" }
createFromFormat
Carbon/src/Carbon/Traits/Creator.php
#[ReturnTypeWillChange] public static function createFromFormat($format, $time, $timezone = null): ?static { $function = static::$createFromFormatFunction; // format is a single numeric unit if (\is_int($time) && \in_array(ltrim($format, '!'), ['U', 'Y', 'y', 'X', 'x', 'm', 'n', 'd', 'j', 'w', 'W', 'H', 'h', 'G', 'g', 'i', 's', 'u', 'z', 'v'], true)) { $time = (string) $time; } if (!\is_string($time)) { @trigger_error( 'createFromFormat() $time parameter will only accept string or integer for 1-letter format representing a numeric unit in the next version', \E_USER_DEPRECATED, ); $time = (string) $time; } if (!$function) { return static::rawCreateFromFormat($format, $time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\UnitException; use Carbon\Month; use Carbon\Translator; use Carbon\WeekDay; use Closure; use DateMalformedStringException; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Exception; use ReturnTypeWillChange; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Creator. * * Static creators. * * Depends on the following methods: * * @method static Carbon|CarbonImmutable getTestNow() */ trait Creator { use ObjectInitialisation; use LocalFactory; /** * The errors that can occur. */ protected static array|bool $lastErrors = false; /** * Create a new Carbon instance. * * Please see the testing aids section (specifically static::setTestNow()) * for more on the possibility of this constructor returning a test instance. * * @throws InvalidFormatException */ public function __construct( DateTimeInterface|WeekDay|Month|string|int|float|null $time = null, DateTimeZone|string|int|null $timezone = null, ) { $this->initLocalFactory(); if ($time instanceof Month) { $time = $time->name.' 1'; } elseif ($time instanceof WeekDay) { $time = $time->name; } elseif ($time instanceof DateTimeInterface) { $time = $this->constructTimezoneFromDateTime($time, $timezone)->format('Y-m-d H:i:s.u'); } if (\is_string($time) && str_starts_with($time, '@')) { $time = static::createFromTimestampUTC(substr($time, 1))->format('Y-m-d\TH:i:s.uP'); } elseif (is_numeric($time) && (!\is_string($time) || !preg_match('/^\d{1,14}$/', $time))) { $time = static::createFromTimestampUTC($time)->format('Y-m-d\TH:i:s.uP'); } // If the class has a test now set, and we are trying to create a now() // instance then override as required $isNow = \in_array($time, [null, '', 'now'], true); $timezone = static::safeCreateDateTimeZone($timezone) ?? null; if ( ($this->clock || ( method_exists(static::class, 'hasTestNow') && method_exists(static::class, 'getTestNow') && static::hasTestNow() )) && ($isNow || static::hasRelativeKeywords($time)) ) { $this->mockConstructorParameters($time, $timezone); } try { parent::__construct($time ?? 'now', $timezone); } catch (Exception $exception) { throw new InvalidFormatException($exception->getMessage(), 0, $exception); } $this->constructedObjectId = spl_object_hash($this); self::setLastErrors(parent::getLastErrors()); } /** * Get timezone from a datetime instance. */ private function constructTimezoneFromDateTime( DateTimeInterface $date, DateTimeZone|string|int|null &$timezone, ): DateTimeInterface { if ($timezone !== null) { $safeTz = static::safeCreateDateTimeZone($timezone); if ($safeTz) { $date = ($date instanceof DateTimeImmutable ? $date : clone $date)->setTimezone($safeTz); } return $date; } $timezone = $date->getTimezone(); return $date; } /** * Update constructedObjectId on cloned. */ public function __clone(): void { $this->constructedObjectId = spl_object_hash($this); } /** * Create a Carbon instance from a DateTime one. */ public static function instance(DateTimeInterface $date): static { if ($date instanceof static) { return clone $date; } $instance = parent::createFromFormat('U.u', $date->format('U.u')) ->setTimezone($date->getTimezone()); if ($date instanceof CarbonInterface) { $settings = $date->getSettings(); if (!$date->hasLocalTranslator()) { unset($settings['locale']); } $instance->settings($settings); } return $instance; } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function rawParse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { if ($time instanceof DateTimeInterface) { return static::instance($time); } try { return new static($time, $timezone); } catch (Exception $exception) { // @codeCoverageIgnoreStart try { $date = @static::now($timezone)->change($time); } catch (DateMalformedStringException|InvalidFormatException) { $date = null; } // @codeCoverageIgnoreEnd return $date ?? throw new InvalidFormatException("Could not parse '$time': ".$exception->getMessage(), 0, $exception); } } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function parse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { $function = static::$parseFunction; if (!$function) { return static::rawParse($time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.). * * @param string $time date/time string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be * used instead. * @param DateTimeZone|string|int|null $timezone optional timezone for the new instance. * * @throws InvalidFormatException */ public static function parseFromLocale( string $time, ?string $locale = null, DateTimeZone|string|int|null $timezone = null, ): static { return static::rawParse(static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Get a Carbon instance for the current date and time. */ public static function now(DateTimeZone|string|int|null $timezone = null): static { return new static(null, $timezone); } /** * Create a Carbon instance for today. */ public static function today(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('today', $timezone); } /** * Create a Carbon instance for tomorrow. */ public static function tomorrow(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('tomorrow', $timezone); } /** * Create a Carbon instance for yesterday. */ public static function yesterday(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('yesterday', $timezone); } private static function assertBetween($unit, $value, $min, $max): void { if (static::isStrictModeEnabled() && ($value < $min || $value > $max)) { throw new OutOfRangeException($unit, $min, $max, $value); } } private static function createNowInstance($timezone) { if (!static::hasTestNow()) { return static::now($timezone); } $now = static::getTestNow(); if ($now instanceof Closure) { return $now(static::now($timezone)); } $now = $now->avoidMutation(); return $timezone === null ? $now : $now->setTimezone($timezone); } /** * Create a new Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * @param DateTimeInterface|string|int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null): ?static { $month = self::monthToInt($month); if ((\is_string($year) && !is_numeric($year)) || $year instanceof DateTimeInterface) { return static::parse($year, $timezone ?? (\is_string($month) || $month instanceof DateTimeZone ? $month : null)); } $defaults = null; $getDefault = function ($unit) use ($timezone, &$defaults) { if ($defaults === null) { $now = self::createNowInstance($timezone); $defaults = array_combine([ 'year', 'month', 'day', 'hour', 'minute', 'second', ], explode('-', $now->rawFormat('Y-n-j-G-i-s.u'))); } return $defaults[$unit]; }; $year = $year ?? $getDefault('year'); $month = $month ?? $getDefault('month'); $day = $day ?? $getDefault('day'); $hour = $hour ?? $getDefault('hour'); $minute = $minute ?? $getDefault('minute'); $second = (float) ($second ?? $getDefault('second')); self::assertBetween('month', $month, 0, 99); self::assertBetween('day', $day, 0, 99); self::assertBetween('hour', $hour, 0, 99); self::assertBetween('minute', $minute, 0, 99); self::assertBetween('second', $second, 0, 99); $fixYear = null; if ($year < 0) { $fixYear = $year; $year = 0; } elseif ($year > 9999) { $fixYear = $year - 9999; $year = 9999; } $second = ($second < 10 ? '0' : '').number_format($second, 6); $instance = static::rawCreateFromFormat('!Y-n-j G:i:s.u', \sprintf('%s-%s-%s %s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $timezone); if ($instance && $fixYear !== null) { $instance = $instance->addYears($fixYear); } return $instance ?? null; } /** * Create a new safe Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * If one of the set values is not valid, an InvalidDateException * will be thrown. * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidDateException * * @return static|null */ public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null): ?static { $month = self::monthToInt($month); $fields = static::getRangesByUnit(); foreach ($fields as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field < $range[0] || $$field > $range[1])) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } $instance = static::create($year, $month, $day, $hour, $minute, $second, $timezone); foreach (array_reverse($fields) as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field !== $instance->$field)) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } return $instance; } /** * Create a new Carbon instance from a specific date and time using strict validation. * * @see create() * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $timezone = null): static { $initialStrictMode = static::isStrictModeEnabled(); static::useStrictMode(true); try { $date = static::create($year, $month, $day, $hour, $minute, $second, $timezone); } finally { static::useStrictMode($initialStrictMode); } return $date; } /** * Create a Carbon instance from just a date. The time portion is set to now. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, null, null, null, $timezone); } /** * Create a Carbon instance from just a date. The time portion is set to midnight. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createMidnightDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, 0, 0, 0, $timezone); } /** * Create a Carbon instance from just a time. The date portion is set to today. * * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromTime($hour = 0, $minute = 0, $second = 0, $timezone = null): static { return static::create(null, null, null, $hour, $minute, $second, $timezone); } /** * Create a Carbon instance from a time string. The date portion is set to today. * * @throws InvalidFormatException */ public static function createFromTimeString(string $time, DateTimeZone|string|int|null $timezone = null): static { return static::today($timezone)->setTimeFromTimeString($time); } private static function createFromFormatAndTimezone( string $format, string $time, DateTimeZone|string|int|null $originalTimezone, ): ?DateTimeInterface { if ($originalTimezone === null) { return parent::createFromFormat($format, $time) ?: null; } $timezone = \is_int($originalTimezone) ? self::getOffsetTimezone($originalTimezone) : $originalTimezone; $timezone = static::safeCreateDateTimeZone($timezone, $originalTimezone); return parent::createFromFormat($format, $time, $timezone) ?: null; } private static function getOffsetTimezone(int $offset): string { $minutes = (int) ($offset * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE); return @timezone_name_from_abbr('', $minutes, 1) ?: throw new InvalidTimeZoneException( "Invalid offset timezone $offset", ); } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function rawCreateFromFormat(string $format, string $time, $timezone = null): ?static { // Work-around for https://bugs.php.net/bug.php?id=80141 $format = preg_replace('/(?<!\\\\)((?:\\\\{2})*)c/', '$1Y-m-d\TH:i:sP', $format); if (preg_match('/(?<!\\\\)(?:\\\\{2})*(a|A)/', $format, $aMatches, PREG_OFFSET_CAPTURE) && preg_match('/(?<!\\\\)(?:\\\\{2})*(h|g|H|G)/', $format, $hMatches, PREG_OFFSET_CAPTURE) && $aMatches[1][1] < $hMatches[1][1] && preg_match('/(am|pm|AM|PM)/', $time) ) { $format = preg_replace('/^(.*)(?<!\\\\)((?:\\\\{2})*)(a|A)(.*)$/U', '$1$2$4 $3', $format); $time = preg_replace('/^(.*)(am|pm|AM|PM)(.*)$/U', '$1$3 $2', $time); } if ($timezone === false) { $timezone = null; } // First attempt to create an instance, so that error messages are based on the unmodified format. $date = self::createFromFormatAndTimezone($format, $time, $timezone); $lastErrors = parent::getLastErrors(); /** @var \Carbon\CarbonImmutable|\Carbon\Carbon|null $mock */ $mock = static::getMockedTestNow($timezone); if ($mock && $date instanceof DateTimeInterface) { // Set timezone from mock if custom timezone was neither given directly nor as a part of format. // First let's skip the part that will be ignored by the parser. $nonEscaped = '(?<!\\\\)(\\\\{2})*'; $nonIgnored = preg_replace("/^.*{$nonEscaped}!/s", '', $format); if ($timezone === null && !preg_match("/{$nonEscaped}[eOPT]/", $nonIgnored)) { $timezone = clone $mock->getTimezone(); } $mock = $mock->copy(); // Prepend mock datetime only if the format does not contain non escaped unix epoch reset flag. if (!preg_match("/{$nonEscaped}[!|]/", $format)) { if (preg_match('/[HhGgisvuB]/', $format)) { $mock = $mock->setTime(0, 0); } $format = static::MOCK_DATETIME_FORMAT.' '.$format; $time = ($mock instanceof self ? $mock->rawFormat(static::MOCK_DATETIME_FORMAT) : $mock->format(static::MOCK_DATETIME_FORMAT)).' '.$time; } // Regenerate date from the modified format to base result on the mocked instance instead of now. $date = self::createFromFormatAndTimezone($format, $time, $timezone); } if ($date instanceof DateTimeInterface) { $instance = static::instance($date); $instance::setLastErrors($lastErrors); return $instance; } if (static::isStrictModeEnabled()) { throw new InvalidFormatException(implode(PHP_EOL, (array) $lastErrors['errors'])); } return null; } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ #[ReturnTypeWillChange] public static function createFromFormat($format, $time, $timezone = null): ?static { $function = static::$createFromFormatFunction; // format is a single numeric unit if (\is_int($time) && \in_array(ltrim($format, '!'), ['U', 'Y', 'y', 'X', 'x', 'm', 'n', 'd', 'j', 'w', 'W', 'H', 'h', 'G', 'g', 'i', 's', 'u', 'z', 'v'], true)) { $time = (string) $time; } if (!\is_string($time)) { @trigger_error( 'createFromFormat() $time parameter will only accept string or integer for 1-letter format representing a numeric unit in the next version', \E_USER_DEPRECATED, ); $time = (string) $time; } if (!$function) { return static::rawCreateFromFormat($format, $time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()). * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone optional timezone * @param string|null $locale locale to be used for LTS, LT, LL, LLL, etc. macro-formats (en by fault, unneeded if no such macro-format in use) * @param TranslatorInterface|null $translator optional custom translator to use for macro-formats * * @throws InvalidFormatException * * @return static|null */ public static function createFromIsoFormat( string $format, string $time, $timezone = null, ?string $locale = CarbonInterface::DEFAULT_LOCALE, ?TranslatorInterface $translator = null ): ?static { $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*(LTS|LT|[Ll]{1,4})/', function ($match) use ($locale, $translator) { [$code] = $match; static $formats = null; if ($formats === null) { $translator ??= Translator::get($locale); $formats = [ 'LT' => static::getTranslationMessageWith($translator, 'formats.LT', $locale), 'LTS' => static::getTranslationMessageWith($translator, 'formats.LTS', $locale), 'L' => static::getTranslationMessageWith($translator, 'formats.L', $locale), 'LL' => static::getTranslationMessageWith($translator, 'formats.LL', $locale), 'LLL' => static::getTranslationMessageWith($translator, 'formats.LLL', $locale), 'LLLL' => static::getTranslationMessageWith($translator, 'formats.LLLL', $locale), ]; } return $formats[$code] ?? preg_replace_callback( '/MMMM|MM|DD|dddd/', static fn (array $code) => mb_substr($code[0], 1), $formats[strtoupper($code)] ?? '', ); }, $format); $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*('.CarbonInterface::ISO_FORMAT_REGEXP.'|[A-Za-z])/', function ($match) { [$code] = $match; static $replacements = null; if ($replacements === null) { $replacements = [ 'OD' => 'd', 'OM' => 'M', 'OY' => 'Y', 'OH' => 'G', 'Oh' => 'g', 'Om' => 'i', 'Os' => 's', 'D' => 'd', 'DD' => 'd', 'Do' => 'd', 'd' => '!', 'dd' => '!', 'ddd' => 'D', 'dddd' => 'D', 'DDD' => 'z', 'DDDD' => 'z', 'DDDo' => 'z', 'e' => '!', 'E' => '!', 'H' => 'G', 'HH' => 'H', 'h' => 'g', 'hh' => 'h', 'k' => 'G', 'kk' => 'G', 'hmm' => 'gi', 'hmmss' => 'gis', 'Hmm' => 'Gi', 'Hmmss' => 'Gis', 'm' => 'i', 'mm' => 'i', 'a' => 'a', 'A' => 'a', 's' => 's', 'ss' => 's', 'S' => '*', 'SS' => '*', 'SSS' => '*', 'SSSS' => '*', 'SSSSS' => '*', 'SSSSSS' => 'u', 'SSSSSSS' => 'u*', 'SSSSSSSS' => 'u*', 'SSSSSSSSS' => 'u*', 'M' => 'm', 'MM' => 'm', 'MMM' => 'M', 'MMMM' => 'M', 'Mo' => 'm', 'Q' => '!', 'Qo' => '!', 'G' => '!', 'GG' => '!', 'GGG' => '!', 'GGGG' => '!', 'GGGGG' => '!', 'g' => '!', 'gg' => '!', 'ggg' => '!', 'gggg' => '!', 'ggggg' => '!', 'W' => '!', 'WW' => '!', 'Wo' => '!', 'w' => '!', 'ww' => '!', 'wo' => '!', 'x' => 'U???', 'X' => 'U', 'Y' => 'Y', 'YY' => 'y', 'YYYY' => 'Y', 'YYYYY' => 'Y', 'YYYYYY' => 'Y', 'z' => 'e', 'zz' => 'e', 'Z' => 'e', 'ZZ' => 'e', ]; } $format = $replacements[$code] ?? '?'; if ($format === '!') { throw new InvalidFormatException("Format $code not supported for creation."); } return $format; }, $format); return static::rawCreateFromFormat($format, $time, $timezone); } /** * Create a Carbon instance from a specific format and a string in a given language. * * @param string $format Datetime format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null): ?static { $format = preg_replace_callback( '/(?:\\\\[a-zA-Z]|[bfkqCEJKQRV]){2,}/', static function (array $match) use ($locale): string { $word = str_replace('\\', '', $match[0]); $translatedWord = static::translateTimeString($word, $locale, static::DEFAULT_LOCALE); return $word === $translatedWord ? $match[0] : preg_replace('/[a-zA-Z]/', '\\\\$0', $translatedWord); }, $format ); return static::rawCreateFromFormat($format, static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Create a Carbon instance from a specific ISO format and a string in a given language. * * @param string $format Datetime ISO format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleIsoFormat(string $format, string $locale, string $time, $timezone = null): ?static { $time = static::translateTimeString($time, $locale, static::DEFAULT_LOCALE, CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS | CarbonInterface::TRANSLATE_MERIDIEM); return static::createFromIsoFormat($format, $time, $timezone, $locale); } /** * Make a Carbon instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed $var * * @throws InvalidFormatException * * @return static|null */ public static function make($var, DateTimeZone|string|null $timezone = null): ?static { if ($var instanceof DateTimeInterface) { return static::instance($var); } $date = null; if (\is_string($var)) { $var = trim($var); if (!preg_match('/^P[\dT]/', $var) && !preg_match('/^R\d/', $var) && preg_match('/[a-z\d]/i', $var) ) { $date = static::parse($var, $timezone); } } return $date; } /** * Set last errors. * * @param array|bool $lastErrors * * @return void */ private static function setLastErrors($lastErrors): void { static::$lastErrors = $lastErrors; } /** * {@inheritdoc} */ public static function getLastErrors(): array|false { return static::$lastErrors; } private static function monthToInt(mixed $value, string $unit = 'month'): mixed { if ($value instanceof Month) { if ($unit !== 'month') { throw new UnitException("Month enum cannot be used to set $unit"); } return Month::int($value); } return $value; } }
PHP
{ "end_line": 669, "name": "createFromFormat", "signature": "#[ReturnTypeWillChange]", "start_line": 642 }
{ "class_name": "Creator", "class_signature": "trait Creator", "namespace": "Carbon\\Traits" }
createFromLocaleFormat
Carbon/src/Carbon/Traits/Creator.php
public static function createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null): ?static { $format = preg_replace_callback( '/(?:\\\\[a-zA-Z]|[bfkqCEJKQRV]){2,}/', static function (array $match) use ($locale): string { $word = str_replace('\\', '', $match[0]); $translatedWord = static::translateTimeString($word, $locale, static::DEFAULT_LOCALE); return $word === $translatedWord ? $match[0] : preg_replace('/[a-zA-Z]/', '\\\\$0', $translatedWord); }, $format ); return static::rawCreateFromFormat($format, static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\UnitException; use Carbon\Month; use Carbon\Translator; use Carbon\WeekDay; use Closure; use DateMalformedStringException; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Exception; use ReturnTypeWillChange; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Creator. * * Static creators. * * Depends on the following methods: * * @method static Carbon|CarbonImmutable getTestNow() */ trait Creator { use ObjectInitialisation; use LocalFactory; /** * The errors that can occur. */ protected static array|bool $lastErrors = false; /** * Create a new Carbon instance. * * Please see the testing aids section (specifically static::setTestNow()) * for more on the possibility of this constructor returning a test instance. * * @throws InvalidFormatException */ public function __construct( DateTimeInterface|WeekDay|Month|string|int|float|null $time = null, DateTimeZone|string|int|null $timezone = null, ) { $this->initLocalFactory(); if ($time instanceof Month) { $time = $time->name.' 1'; } elseif ($time instanceof WeekDay) { $time = $time->name; } elseif ($time instanceof DateTimeInterface) { $time = $this->constructTimezoneFromDateTime($time, $timezone)->format('Y-m-d H:i:s.u'); } if (\is_string($time) && str_starts_with($time, '@')) { $time = static::createFromTimestampUTC(substr($time, 1))->format('Y-m-d\TH:i:s.uP'); } elseif (is_numeric($time) && (!\is_string($time) || !preg_match('/^\d{1,14}$/', $time))) { $time = static::createFromTimestampUTC($time)->format('Y-m-d\TH:i:s.uP'); } // If the class has a test now set, and we are trying to create a now() // instance then override as required $isNow = \in_array($time, [null, '', 'now'], true); $timezone = static::safeCreateDateTimeZone($timezone) ?? null; if ( ($this->clock || ( method_exists(static::class, 'hasTestNow') && method_exists(static::class, 'getTestNow') && static::hasTestNow() )) && ($isNow || static::hasRelativeKeywords($time)) ) { $this->mockConstructorParameters($time, $timezone); } try { parent::__construct($time ?? 'now', $timezone); } catch (Exception $exception) { throw new InvalidFormatException($exception->getMessage(), 0, $exception); } $this->constructedObjectId = spl_object_hash($this); self::setLastErrors(parent::getLastErrors()); } /** * Get timezone from a datetime instance. */ private function constructTimezoneFromDateTime( DateTimeInterface $date, DateTimeZone|string|int|null &$timezone, ): DateTimeInterface { if ($timezone !== null) { $safeTz = static::safeCreateDateTimeZone($timezone); if ($safeTz) { $date = ($date instanceof DateTimeImmutable ? $date : clone $date)->setTimezone($safeTz); } return $date; } $timezone = $date->getTimezone(); return $date; } /** * Update constructedObjectId on cloned. */ public function __clone(): void { $this->constructedObjectId = spl_object_hash($this); } /** * Create a Carbon instance from a DateTime one. */ public static function instance(DateTimeInterface $date): static { if ($date instanceof static) { return clone $date; } $instance = parent::createFromFormat('U.u', $date->format('U.u')) ->setTimezone($date->getTimezone()); if ($date instanceof CarbonInterface) { $settings = $date->getSettings(); if (!$date->hasLocalTranslator()) { unset($settings['locale']); } $instance->settings($settings); } return $instance; } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function rawParse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { if ($time instanceof DateTimeInterface) { return static::instance($time); } try { return new static($time, $timezone); } catch (Exception $exception) { // @codeCoverageIgnoreStart try { $date = @static::now($timezone)->change($time); } catch (DateMalformedStringException|InvalidFormatException) { $date = null; } // @codeCoverageIgnoreEnd return $date ?? throw new InvalidFormatException("Could not parse '$time': ".$exception->getMessage(), 0, $exception); } } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function parse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { $function = static::$parseFunction; if (!$function) { return static::rawParse($time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.). * * @param string $time date/time string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be * used instead. * @param DateTimeZone|string|int|null $timezone optional timezone for the new instance. * * @throws InvalidFormatException */ public static function parseFromLocale( string $time, ?string $locale = null, DateTimeZone|string|int|null $timezone = null, ): static { return static::rawParse(static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Get a Carbon instance for the current date and time. */ public static function now(DateTimeZone|string|int|null $timezone = null): static { return new static(null, $timezone); } /** * Create a Carbon instance for today. */ public static function today(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('today', $timezone); } /** * Create a Carbon instance for tomorrow. */ public static function tomorrow(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('tomorrow', $timezone); } /** * Create a Carbon instance for yesterday. */ public static function yesterday(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('yesterday', $timezone); } private static function assertBetween($unit, $value, $min, $max): void { if (static::isStrictModeEnabled() && ($value < $min || $value > $max)) { throw new OutOfRangeException($unit, $min, $max, $value); } } private static function createNowInstance($timezone) { if (!static::hasTestNow()) { return static::now($timezone); } $now = static::getTestNow(); if ($now instanceof Closure) { return $now(static::now($timezone)); } $now = $now->avoidMutation(); return $timezone === null ? $now : $now->setTimezone($timezone); } /** * Create a new Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * @param DateTimeInterface|string|int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null): ?static { $month = self::monthToInt($month); if ((\is_string($year) && !is_numeric($year)) || $year instanceof DateTimeInterface) { return static::parse($year, $timezone ?? (\is_string($month) || $month instanceof DateTimeZone ? $month : null)); } $defaults = null; $getDefault = function ($unit) use ($timezone, &$defaults) { if ($defaults === null) { $now = self::createNowInstance($timezone); $defaults = array_combine([ 'year', 'month', 'day', 'hour', 'minute', 'second', ], explode('-', $now->rawFormat('Y-n-j-G-i-s.u'))); } return $defaults[$unit]; }; $year = $year ?? $getDefault('year'); $month = $month ?? $getDefault('month'); $day = $day ?? $getDefault('day'); $hour = $hour ?? $getDefault('hour'); $minute = $minute ?? $getDefault('minute'); $second = (float) ($second ?? $getDefault('second')); self::assertBetween('month', $month, 0, 99); self::assertBetween('day', $day, 0, 99); self::assertBetween('hour', $hour, 0, 99); self::assertBetween('minute', $minute, 0, 99); self::assertBetween('second', $second, 0, 99); $fixYear = null; if ($year < 0) { $fixYear = $year; $year = 0; } elseif ($year > 9999) { $fixYear = $year - 9999; $year = 9999; } $second = ($second < 10 ? '0' : '').number_format($second, 6); $instance = static::rawCreateFromFormat('!Y-n-j G:i:s.u', \sprintf('%s-%s-%s %s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $timezone); if ($instance && $fixYear !== null) { $instance = $instance->addYears($fixYear); } return $instance ?? null; } /** * Create a new safe Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * If one of the set values is not valid, an InvalidDateException * will be thrown. * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidDateException * * @return static|null */ public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null): ?static { $month = self::monthToInt($month); $fields = static::getRangesByUnit(); foreach ($fields as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field < $range[0] || $$field > $range[1])) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } $instance = static::create($year, $month, $day, $hour, $minute, $second, $timezone); foreach (array_reverse($fields) as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field !== $instance->$field)) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } return $instance; } /** * Create a new Carbon instance from a specific date and time using strict validation. * * @see create() * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $timezone = null): static { $initialStrictMode = static::isStrictModeEnabled(); static::useStrictMode(true); try { $date = static::create($year, $month, $day, $hour, $minute, $second, $timezone); } finally { static::useStrictMode($initialStrictMode); } return $date; } /** * Create a Carbon instance from just a date. The time portion is set to now. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, null, null, null, $timezone); } /** * Create a Carbon instance from just a date. The time portion is set to midnight. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createMidnightDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, 0, 0, 0, $timezone); } /** * Create a Carbon instance from just a time. The date portion is set to today. * * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromTime($hour = 0, $minute = 0, $second = 0, $timezone = null): static { return static::create(null, null, null, $hour, $minute, $second, $timezone); } /** * Create a Carbon instance from a time string. The date portion is set to today. * * @throws InvalidFormatException */ public static function createFromTimeString(string $time, DateTimeZone|string|int|null $timezone = null): static { return static::today($timezone)->setTimeFromTimeString($time); } private static function createFromFormatAndTimezone( string $format, string $time, DateTimeZone|string|int|null $originalTimezone, ): ?DateTimeInterface { if ($originalTimezone === null) { return parent::createFromFormat($format, $time) ?: null; } $timezone = \is_int($originalTimezone) ? self::getOffsetTimezone($originalTimezone) : $originalTimezone; $timezone = static::safeCreateDateTimeZone($timezone, $originalTimezone); return parent::createFromFormat($format, $time, $timezone) ?: null; } private static function getOffsetTimezone(int $offset): string { $minutes = (int) ($offset * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE); return @timezone_name_from_abbr('', $minutes, 1) ?: throw new InvalidTimeZoneException( "Invalid offset timezone $offset", ); } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function rawCreateFromFormat(string $format, string $time, $timezone = null): ?static { // Work-around for https://bugs.php.net/bug.php?id=80141 $format = preg_replace('/(?<!\\\\)((?:\\\\{2})*)c/', '$1Y-m-d\TH:i:sP', $format); if (preg_match('/(?<!\\\\)(?:\\\\{2})*(a|A)/', $format, $aMatches, PREG_OFFSET_CAPTURE) && preg_match('/(?<!\\\\)(?:\\\\{2})*(h|g|H|G)/', $format, $hMatches, PREG_OFFSET_CAPTURE) && $aMatches[1][1] < $hMatches[1][1] && preg_match('/(am|pm|AM|PM)/', $time) ) { $format = preg_replace('/^(.*)(?<!\\\\)((?:\\\\{2})*)(a|A)(.*)$/U', '$1$2$4 $3', $format); $time = preg_replace('/^(.*)(am|pm|AM|PM)(.*)$/U', '$1$3 $2', $time); } if ($timezone === false) { $timezone = null; } // First attempt to create an instance, so that error messages are based on the unmodified format. $date = self::createFromFormatAndTimezone($format, $time, $timezone); $lastErrors = parent::getLastErrors(); /** @var \Carbon\CarbonImmutable|\Carbon\Carbon|null $mock */ $mock = static::getMockedTestNow($timezone); if ($mock && $date instanceof DateTimeInterface) { // Set timezone from mock if custom timezone was neither given directly nor as a part of format. // First let's skip the part that will be ignored by the parser. $nonEscaped = '(?<!\\\\)(\\\\{2})*'; $nonIgnored = preg_replace("/^.*{$nonEscaped}!/s", '', $format); if ($timezone === null && !preg_match("/{$nonEscaped}[eOPT]/", $nonIgnored)) { $timezone = clone $mock->getTimezone(); } $mock = $mock->copy(); // Prepend mock datetime only if the format does not contain non escaped unix epoch reset flag. if (!preg_match("/{$nonEscaped}[!|]/", $format)) { if (preg_match('/[HhGgisvuB]/', $format)) { $mock = $mock->setTime(0, 0); } $format = static::MOCK_DATETIME_FORMAT.' '.$format; $time = ($mock instanceof self ? $mock->rawFormat(static::MOCK_DATETIME_FORMAT) : $mock->format(static::MOCK_DATETIME_FORMAT)).' '.$time; } // Regenerate date from the modified format to base result on the mocked instance instead of now. $date = self::createFromFormatAndTimezone($format, $time, $timezone); } if ($date instanceof DateTimeInterface) { $instance = static::instance($date); $instance::setLastErrors($lastErrors); return $instance; } if (static::isStrictModeEnabled()) { throw new InvalidFormatException(implode(PHP_EOL, (array) $lastErrors['errors'])); } return null; } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ #[ReturnTypeWillChange] public static function createFromFormat($format, $time, $timezone = null): ?static { $function = static::$createFromFormatFunction; // format is a single numeric unit if (\is_int($time) && \in_array(ltrim($format, '!'), ['U', 'Y', 'y', 'X', 'x', 'm', 'n', 'd', 'j', 'w', 'W', 'H', 'h', 'G', 'g', 'i', 's', 'u', 'z', 'v'], true)) { $time = (string) $time; } if (!\is_string($time)) { @trigger_error( 'createFromFormat() $time parameter will only accept string or integer for 1-letter format representing a numeric unit in the next version', \E_USER_DEPRECATED, ); $time = (string) $time; } if (!$function) { return static::rawCreateFromFormat($format, $time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()). * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone optional timezone * @param string|null $locale locale to be used for LTS, LT, LL, LLL, etc. macro-formats (en by fault, unneeded if no such macro-format in use) * @param TranslatorInterface|null $translator optional custom translator to use for macro-formats * * @throws InvalidFormatException * * @return static|null */ public static function createFromIsoFormat( string $format, string $time, $timezone = null, ?string $locale = CarbonInterface::DEFAULT_LOCALE, ?TranslatorInterface $translator = null ): ?static { $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*(LTS|LT|[Ll]{1,4})/', function ($match) use ($locale, $translator) { [$code] = $match; static $formats = null; if ($formats === null) { $translator ??= Translator::get($locale); $formats = [ 'LT' => static::getTranslationMessageWith($translator, 'formats.LT', $locale), 'LTS' => static::getTranslationMessageWith($translator, 'formats.LTS', $locale), 'L' => static::getTranslationMessageWith($translator, 'formats.L', $locale), 'LL' => static::getTranslationMessageWith($translator, 'formats.LL', $locale), 'LLL' => static::getTranslationMessageWith($translator, 'formats.LLL', $locale), 'LLLL' => static::getTranslationMessageWith($translator, 'formats.LLLL', $locale), ]; } return $formats[$code] ?? preg_replace_callback( '/MMMM|MM|DD|dddd/', static fn (array $code) => mb_substr($code[0], 1), $formats[strtoupper($code)] ?? '', ); }, $format); $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*('.CarbonInterface::ISO_FORMAT_REGEXP.'|[A-Za-z])/', function ($match) { [$code] = $match; static $replacements = null; if ($replacements === null) { $replacements = [ 'OD' => 'd', 'OM' => 'M', 'OY' => 'Y', 'OH' => 'G', 'Oh' => 'g', 'Om' => 'i', 'Os' => 's', 'D' => 'd', 'DD' => 'd', 'Do' => 'd', 'd' => '!', 'dd' => '!', 'ddd' => 'D', 'dddd' => 'D', 'DDD' => 'z', 'DDDD' => 'z', 'DDDo' => 'z', 'e' => '!', 'E' => '!', 'H' => 'G', 'HH' => 'H', 'h' => 'g', 'hh' => 'h', 'k' => 'G', 'kk' => 'G', 'hmm' => 'gi', 'hmmss' => 'gis', 'Hmm' => 'Gi', 'Hmmss' => 'Gis', 'm' => 'i', 'mm' => 'i', 'a' => 'a', 'A' => 'a', 's' => 's', 'ss' => 's', 'S' => '*', 'SS' => '*', 'SSS' => '*', 'SSSS' => '*', 'SSSSS' => '*', 'SSSSSS' => 'u', 'SSSSSSS' => 'u*', 'SSSSSSSS' => 'u*', 'SSSSSSSSS' => 'u*', 'M' => 'm', 'MM' => 'm', 'MMM' => 'M', 'MMMM' => 'M', 'Mo' => 'm', 'Q' => '!', 'Qo' => '!', 'G' => '!', 'GG' => '!', 'GGG' => '!', 'GGGG' => '!', 'GGGGG' => '!', 'g' => '!', 'gg' => '!', 'ggg' => '!', 'gggg' => '!', 'ggggg' => '!', 'W' => '!', 'WW' => '!', 'Wo' => '!', 'w' => '!', 'ww' => '!', 'wo' => '!', 'x' => 'U???', 'X' => 'U', 'Y' => 'Y', 'YY' => 'y', 'YYYY' => 'Y', 'YYYYY' => 'Y', 'YYYYYY' => 'Y', 'z' => 'e', 'zz' => 'e', 'Z' => 'e', 'ZZ' => 'e', ]; } $format = $replacements[$code] ?? '?'; if ($format === '!') { throw new InvalidFormatException("Format $code not supported for creation."); } return $format; }, $format); return static::rawCreateFromFormat($format, $time, $timezone); } /** * Create a Carbon instance from a specific format and a string in a given language. * * @param string $format Datetime format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null): ?static { $format = preg_replace_callback( '/(?:\\\\[a-zA-Z]|[bfkqCEJKQRV]){2,}/', static function (array $match) use ($locale): string { $word = str_replace('\\', '', $match[0]); $translatedWord = static::translateTimeString($word, $locale, static::DEFAULT_LOCALE); return $word === $translatedWord ? $match[0] : preg_replace('/[a-zA-Z]/', '\\\\$0', $translatedWord); }, $format ); return static::rawCreateFromFormat($format, static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Create a Carbon instance from a specific ISO format and a string in a given language. * * @param string $format Datetime ISO format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleIsoFormat(string $format, string $locale, string $time, $timezone = null): ?static { $time = static::translateTimeString($time, $locale, static::DEFAULT_LOCALE, CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS | CarbonInterface::TRANSLATE_MERIDIEM); return static::createFromIsoFormat($format, $time, $timezone, $locale); } /** * Make a Carbon instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed $var * * @throws InvalidFormatException * * @return static|null */ public static function make($var, DateTimeZone|string|null $timezone = null): ?static { if ($var instanceof DateTimeInterface) { return static::instance($var); } $date = null; if (\is_string($var)) { $var = trim($var); if (!preg_match('/^P[\dT]/', $var) && !preg_match('/^R\d/', $var) && preg_match('/[a-z\d]/i', $var) ) { $date = static::parse($var, $timezone); } } return $date; } /** * Set last errors. * * @param array|bool $lastErrors * * @return void */ private static function setLastErrors($lastErrors): void { static::$lastErrors = $lastErrors; } /** * {@inheritdoc} */ public static function getLastErrors(): array|false { return static::$lastErrors; } private static function monthToInt(mixed $value, string $unit = 'month'): mixed { if ($value instanceof Month) { if ($unit !== 'month') { throw new UnitException("Month enum cannot be used to set $unit"); } return Month::int($value); } return $value; } }
PHP
{ "end_line": 844, "name": "createFromLocaleFormat", "signature": "public static function createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null): ?static", "start_line": 828 }
{ "class_name": "Creator", "class_signature": "trait Creator", "namespace": "Carbon\\Traits" }
make
Carbon/src/Carbon/Traits/Creator.php
public static function make($var, DateTimeZone|string|null $timezone = null): ?static { if ($var instanceof DateTimeInterface) { return static::instance($var); } $date = null; if (\is_string($var)) { $var = trim($var); if (!preg_match('/^P[\dT]/', $var) && !preg_match('/^R\d/', $var) && preg_match('/[a-z\d]/i', $var) ) { $date = static::parse($var, $timezone); } } return $date; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidDateException; use Carbon\Exceptions\InvalidFormatException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Exceptions\OutOfRangeException; use Carbon\Exceptions\UnitException; use Carbon\Month; use Carbon\Translator; use Carbon\WeekDay; use Closure; use DateMalformedStringException; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Exception; use ReturnTypeWillChange; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Creator. * * Static creators. * * Depends on the following methods: * * @method static Carbon|CarbonImmutable getTestNow() */ trait Creator { use ObjectInitialisation; use LocalFactory; /** * The errors that can occur. */ protected static array|bool $lastErrors = false; /** * Create a new Carbon instance. * * Please see the testing aids section (specifically static::setTestNow()) * for more on the possibility of this constructor returning a test instance. * * @throws InvalidFormatException */ public function __construct( DateTimeInterface|WeekDay|Month|string|int|float|null $time = null, DateTimeZone|string|int|null $timezone = null, ) { $this->initLocalFactory(); if ($time instanceof Month) { $time = $time->name.' 1'; } elseif ($time instanceof WeekDay) { $time = $time->name; } elseif ($time instanceof DateTimeInterface) { $time = $this->constructTimezoneFromDateTime($time, $timezone)->format('Y-m-d H:i:s.u'); } if (\is_string($time) && str_starts_with($time, '@')) { $time = static::createFromTimestampUTC(substr($time, 1))->format('Y-m-d\TH:i:s.uP'); } elseif (is_numeric($time) && (!\is_string($time) || !preg_match('/^\d{1,14}$/', $time))) { $time = static::createFromTimestampUTC($time)->format('Y-m-d\TH:i:s.uP'); } // If the class has a test now set, and we are trying to create a now() // instance then override as required $isNow = \in_array($time, [null, '', 'now'], true); $timezone = static::safeCreateDateTimeZone($timezone) ?? null; if ( ($this->clock || ( method_exists(static::class, 'hasTestNow') && method_exists(static::class, 'getTestNow') && static::hasTestNow() )) && ($isNow || static::hasRelativeKeywords($time)) ) { $this->mockConstructorParameters($time, $timezone); } try { parent::__construct($time ?? 'now', $timezone); } catch (Exception $exception) { throw new InvalidFormatException($exception->getMessage(), 0, $exception); } $this->constructedObjectId = spl_object_hash($this); self::setLastErrors(parent::getLastErrors()); } /** * Get timezone from a datetime instance. */ private function constructTimezoneFromDateTime( DateTimeInterface $date, DateTimeZone|string|int|null &$timezone, ): DateTimeInterface { if ($timezone !== null) { $safeTz = static::safeCreateDateTimeZone($timezone); if ($safeTz) { $date = ($date instanceof DateTimeImmutable ? $date : clone $date)->setTimezone($safeTz); } return $date; } $timezone = $date->getTimezone(); return $date; } /** * Update constructedObjectId on cloned. */ public function __clone(): void { $this->constructedObjectId = spl_object_hash($this); } /** * Create a Carbon instance from a DateTime one. */ public static function instance(DateTimeInterface $date): static { if ($date instanceof static) { return clone $date; } $instance = parent::createFromFormat('U.u', $date->format('U.u')) ->setTimezone($date->getTimezone()); if ($date instanceof CarbonInterface) { $settings = $date->getSettings(); if (!$date->hasLocalTranslator()) { unset($settings['locale']); } $instance->settings($settings); } return $instance; } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function rawParse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { if ($time instanceof DateTimeInterface) { return static::instance($time); } try { return new static($time, $timezone); } catch (Exception $exception) { // @codeCoverageIgnoreStart try { $date = @static::now($timezone)->change($time); } catch (DateMalformedStringException|InvalidFormatException) { $date = null; } // @codeCoverageIgnoreEnd return $date ?? throw new InvalidFormatException("Could not parse '$time': ".$exception->getMessage(), 0, $exception); } } /** * Create a carbon instance from a string. * * This is an alias for the constructor that allows better fluent syntax * as it allows you to do Carbon::parse('Monday next week')->fn() rather * than (new Carbon('Monday next week'))->fn(). * * @throws InvalidFormatException */ public static function parse( DateTimeInterface|WeekDay|Month|string|int|float|null $time, DateTimeZone|string|int|null $timezone = null, ): static { $function = static::$parseFunction; if (!$function) { return static::rawParse($time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a carbon instance from a localized string (in French, Japanese, Arabic, etc.). * * @param string $time date/time string in the given language (may also contain English). * @param string|null $locale if locale is null or not specified, current global locale will be * used instead. * @param DateTimeZone|string|int|null $timezone optional timezone for the new instance. * * @throws InvalidFormatException */ public static function parseFromLocale( string $time, ?string $locale = null, DateTimeZone|string|int|null $timezone = null, ): static { return static::rawParse(static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Get a Carbon instance for the current date and time. */ public static function now(DateTimeZone|string|int|null $timezone = null): static { return new static(null, $timezone); } /** * Create a Carbon instance for today. */ public static function today(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('today', $timezone); } /** * Create a Carbon instance for tomorrow. */ public static function tomorrow(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('tomorrow', $timezone); } /** * Create a Carbon instance for yesterday. */ public static function yesterday(DateTimeZone|string|int|null $timezone = null): static { return static::rawParse('yesterday', $timezone); } private static function assertBetween($unit, $value, $min, $max): void { if (static::isStrictModeEnabled() && ($value < $min || $value > $max)) { throw new OutOfRangeException($unit, $min, $max, $value); } } private static function createNowInstance($timezone) { if (!static::hasTestNow()) { return static::now($timezone); } $now = static::getTestNow(); if ($now instanceof Closure) { return $now(static::now($timezone)); } $now = $now->avoidMutation(); return $timezone === null ? $now : $now->setTimezone($timezone); } /** * Create a new Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * @param DateTimeInterface|string|int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $timezone = null): ?static { $month = self::monthToInt($month); if ((\is_string($year) && !is_numeric($year)) || $year instanceof DateTimeInterface) { return static::parse($year, $timezone ?? (\is_string($month) || $month instanceof DateTimeZone ? $month : null)); } $defaults = null; $getDefault = function ($unit) use ($timezone, &$defaults) { if ($defaults === null) { $now = self::createNowInstance($timezone); $defaults = array_combine([ 'year', 'month', 'day', 'hour', 'minute', 'second', ], explode('-', $now->rawFormat('Y-n-j-G-i-s.u'))); } return $defaults[$unit]; }; $year = $year ?? $getDefault('year'); $month = $month ?? $getDefault('month'); $day = $day ?? $getDefault('day'); $hour = $hour ?? $getDefault('hour'); $minute = $minute ?? $getDefault('minute'); $second = (float) ($second ?? $getDefault('second')); self::assertBetween('month', $month, 0, 99); self::assertBetween('day', $day, 0, 99); self::assertBetween('hour', $hour, 0, 99); self::assertBetween('minute', $minute, 0, 99); self::assertBetween('second', $second, 0, 99); $fixYear = null; if ($year < 0) { $fixYear = $year; $year = 0; } elseif ($year > 9999) { $fixYear = $year - 9999; $year = 9999; } $second = ($second < 10 ? '0' : '').number_format($second, 6); $instance = static::rawCreateFromFormat('!Y-n-j G:i:s.u', \sprintf('%s-%s-%s %s:%02s:%02s', $year, $month, $day, $hour, $minute, $second), $timezone); if ($instance && $fixYear !== null) { $instance = $instance->addYears($fixYear); } return $instance ?? null; } /** * Create a new safe Carbon instance from a specific date and time. * * If any of $year, $month or $day are set to null their now() values will * be used. * * If $hour is null it will be set to its now() value and the default * values for $minute and $second will be their now() values. * * If $hour is not null then the default values for $minute and $second * will be 0. * * If one of the set values is not valid, an InvalidDateException * will be thrown. * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidDateException * * @return static|null */ public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $timezone = null): ?static { $month = self::monthToInt($month); $fields = static::getRangesByUnit(); foreach ($fields as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field < $range[0] || $$field > $range[1])) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } $instance = static::create($year, $month, $day, $hour, $minute, $second, $timezone); foreach (array_reverse($fields) as $field => $range) { if ($$field !== null && (!\is_int($$field) || $$field !== $instance->$field)) { if (static::isStrictModeEnabled()) { throw new InvalidDateException($field, $$field); } return null; } } return $instance; } /** * Create a new Carbon instance from a specific date and time using strict validation. * * @see create() * * @param int|null $year * @param int|null $month * @param int|null $day * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createStrict(?int $year = 0, ?int $month = 1, ?int $day = 1, ?int $hour = 0, ?int $minute = 0, ?int $second = 0, $timezone = null): static { $initialStrictMode = static::isStrictModeEnabled(); static::useStrictMode(true); try { $date = static::create($year, $month, $day, $hour, $minute, $second, $timezone); } finally { static::useStrictMode($initialStrictMode); } return $date; } /** * Create a Carbon instance from just a date. The time portion is set to now. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, null, null, null, $timezone); } /** * Create a Carbon instance from just a date. The time portion is set to midnight. * * @param int|null $year * @param int|null $month * @param int|null $day * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createMidnightDate($year = null, $month = null, $day = null, $timezone = null) { return static::create($year, $month, $day, 0, 0, 0, $timezone); } /** * Create a Carbon instance from just a time. The date portion is set to today. * * @param int|null $hour * @param int|null $minute * @param int|null $second * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static */ public static function createFromTime($hour = 0, $minute = 0, $second = 0, $timezone = null): static { return static::create(null, null, null, $hour, $minute, $second, $timezone); } /** * Create a Carbon instance from a time string. The date portion is set to today. * * @throws InvalidFormatException */ public static function createFromTimeString(string $time, DateTimeZone|string|int|null $timezone = null): static { return static::today($timezone)->setTimeFromTimeString($time); } private static function createFromFormatAndTimezone( string $format, string $time, DateTimeZone|string|int|null $originalTimezone, ): ?DateTimeInterface { if ($originalTimezone === null) { return parent::createFromFormat($format, $time) ?: null; } $timezone = \is_int($originalTimezone) ? self::getOffsetTimezone($originalTimezone) : $originalTimezone; $timezone = static::safeCreateDateTimeZone($timezone, $originalTimezone); return parent::createFromFormat($format, $time, $timezone) ?: null; } private static function getOffsetTimezone(int $offset): string { $minutes = (int) ($offset * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE); return @timezone_name_from_abbr('', $minutes, 1) ?: throw new InvalidTimeZoneException( "Invalid offset timezone $offset", ); } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function rawCreateFromFormat(string $format, string $time, $timezone = null): ?static { // Work-around for https://bugs.php.net/bug.php?id=80141 $format = preg_replace('/(?<!\\\\)((?:\\\\{2})*)c/', '$1Y-m-d\TH:i:sP', $format); if (preg_match('/(?<!\\\\)(?:\\\\{2})*(a|A)/', $format, $aMatches, PREG_OFFSET_CAPTURE) && preg_match('/(?<!\\\\)(?:\\\\{2})*(h|g|H|G)/', $format, $hMatches, PREG_OFFSET_CAPTURE) && $aMatches[1][1] < $hMatches[1][1] && preg_match('/(am|pm|AM|PM)/', $time) ) { $format = preg_replace('/^(.*)(?<!\\\\)((?:\\\\{2})*)(a|A)(.*)$/U', '$1$2$4 $3', $format); $time = preg_replace('/^(.*)(am|pm|AM|PM)(.*)$/U', '$1$3 $2', $time); } if ($timezone === false) { $timezone = null; } // First attempt to create an instance, so that error messages are based on the unmodified format. $date = self::createFromFormatAndTimezone($format, $time, $timezone); $lastErrors = parent::getLastErrors(); /** @var \Carbon\CarbonImmutable|\Carbon\Carbon|null $mock */ $mock = static::getMockedTestNow($timezone); if ($mock && $date instanceof DateTimeInterface) { // Set timezone from mock if custom timezone was neither given directly nor as a part of format. // First let's skip the part that will be ignored by the parser. $nonEscaped = '(?<!\\\\)(\\\\{2})*'; $nonIgnored = preg_replace("/^.*{$nonEscaped}!/s", '', $format); if ($timezone === null && !preg_match("/{$nonEscaped}[eOPT]/", $nonIgnored)) { $timezone = clone $mock->getTimezone(); } $mock = $mock->copy(); // Prepend mock datetime only if the format does not contain non escaped unix epoch reset flag. if (!preg_match("/{$nonEscaped}[!|]/", $format)) { if (preg_match('/[HhGgisvuB]/', $format)) { $mock = $mock->setTime(0, 0); } $format = static::MOCK_DATETIME_FORMAT.' '.$format; $time = ($mock instanceof self ? $mock->rawFormat(static::MOCK_DATETIME_FORMAT) : $mock->format(static::MOCK_DATETIME_FORMAT)).' '.$time; } // Regenerate date from the modified format to base result on the mocked instance instead of now. $date = self::createFromFormatAndTimezone($format, $time, $timezone); } if ($date instanceof DateTimeInterface) { $instance = static::instance($date); $instance::setLastErrors($lastErrors); return $instance; } if (static::isStrictModeEnabled()) { throw new InvalidFormatException(implode(PHP_EOL, (array) $lastErrors['errors'])); } return null; } /** * Create a Carbon instance from a specific format. * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ #[ReturnTypeWillChange] public static function createFromFormat($format, $time, $timezone = null): ?static { $function = static::$createFromFormatFunction; // format is a single numeric unit if (\is_int($time) && \in_array(ltrim($format, '!'), ['U', 'Y', 'y', 'X', 'x', 'm', 'n', 'd', 'j', 'w', 'W', 'H', 'h', 'G', 'g', 'i', 's', 'u', 'z', 'v'], true)) { $time = (string) $time; } if (!\is_string($time)) { @trigger_error( 'createFromFormat() $time parameter will only accept string or integer for 1-letter format representing a numeric unit in the next version', \E_USER_DEPRECATED, ); $time = (string) $time; } if (!$function) { return static::rawCreateFromFormat($format, $time, $timezone); } if (\is_string($function) && method_exists(static::class, $function)) { $function = [static::class, $function]; } return $function(...\func_get_args()); } /** * Create a Carbon instance from a specific ISO format (same replacements as ->isoFormat()). * * @param string $format Datetime format * @param string $time * @param DateTimeZone|string|int|null $timezone optional timezone * @param string|null $locale locale to be used for LTS, LT, LL, LLL, etc. macro-formats (en by fault, unneeded if no such macro-format in use) * @param TranslatorInterface|null $translator optional custom translator to use for macro-formats * * @throws InvalidFormatException * * @return static|null */ public static function createFromIsoFormat( string $format, string $time, $timezone = null, ?string $locale = CarbonInterface::DEFAULT_LOCALE, ?TranslatorInterface $translator = null ): ?static { $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*(LTS|LT|[Ll]{1,4})/', function ($match) use ($locale, $translator) { [$code] = $match; static $formats = null; if ($formats === null) { $translator ??= Translator::get($locale); $formats = [ 'LT' => static::getTranslationMessageWith($translator, 'formats.LT', $locale), 'LTS' => static::getTranslationMessageWith($translator, 'formats.LTS', $locale), 'L' => static::getTranslationMessageWith($translator, 'formats.L', $locale), 'LL' => static::getTranslationMessageWith($translator, 'formats.LL', $locale), 'LLL' => static::getTranslationMessageWith($translator, 'formats.LLL', $locale), 'LLLL' => static::getTranslationMessageWith($translator, 'formats.LLLL', $locale), ]; } return $formats[$code] ?? preg_replace_callback( '/MMMM|MM|DD|dddd/', static fn (array $code) => mb_substr($code[0], 1), $formats[strtoupper($code)] ?? '', ); }, $format); $format = preg_replace_callback('/(?<!\\\\)(\\\\{2})*('.CarbonInterface::ISO_FORMAT_REGEXP.'|[A-Za-z])/', function ($match) { [$code] = $match; static $replacements = null; if ($replacements === null) { $replacements = [ 'OD' => 'd', 'OM' => 'M', 'OY' => 'Y', 'OH' => 'G', 'Oh' => 'g', 'Om' => 'i', 'Os' => 's', 'D' => 'd', 'DD' => 'd', 'Do' => 'd', 'd' => '!', 'dd' => '!', 'ddd' => 'D', 'dddd' => 'D', 'DDD' => 'z', 'DDDD' => 'z', 'DDDo' => 'z', 'e' => '!', 'E' => '!', 'H' => 'G', 'HH' => 'H', 'h' => 'g', 'hh' => 'h', 'k' => 'G', 'kk' => 'G', 'hmm' => 'gi', 'hmmss' => 'gis', 'Hmm' => 'Gi', 'Hmmss' => 'Gis', 'm' => 'i', 'mm' => 'i', 'a' => 'a', 'A' => 'a', 's' => 's', 'ss' => 's', 'S' => '*', 'SS' => '*', 'SSS' => '*', 'SSSS' => '*', 'SSSSS' => '*', 'SSSSSS' => 'u', 'SSSSSSS' => 'u*', 'SSSSSSSS' => 'u*', 'SSSSSSSSS' => 'u*', 'M' => 'm', 'MM' => 'm', 'MMM' => 'M', 'MMMM' => 'M', 'Mo' => 'm', 'Q' => '!', 'Qo' => '!', 'G' => '!', 'GG' => '!', 'GGG' => '!', 'GGGG' => '!', 'GGGGG' => '!', 'g' => '!', 'gg' => '!', 'ggg' => '!', 'gggg' => '!', 'ggggg' => '!', 'W' => '!', 'WW' => '!', 'Wo' => '!', 'w' => '!', 'ww' => '!', 'wo' => '!', 'x' => 'U???', 'X' => 'U', 'Y' => 'Y', 'YY' => 'y', 'YYYY' => 'Y', 'YYYYY' => 'Y', 'YYYYYY' => 'Y', 'z' => 'e', 'zz' => 'e', 'Z' => 'e', 'ZZ' => 'e', ]; } $format = $replacements[$code] ?? '?'; if ($format === '!') { throw new InvalidFormatException("Format $code not supported for creation."); } return $format; }, $format); return static::rawCreateFromFormat($format, $time, $timezone); } /** * Create a Carbon instance from a specific format and a string in a given language. * * @param string $format Datetime format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleFormat(string $format, string $locale, string $time, $timezone = null): ?static { $format = preg_replace_callback( '/(?:\\\\[a-zA-Z]|[bfkqCEJKQRV]){2,}/', static function (array $match) use ($locale): string { $word = str_replace('\\', '', $match[0]); $translatedWord = static::translateTimeString($word, $locale, static::DEFAULT_LOCALE); return $word === $translatedWord ? $match[0] : preg_replace('/[a-zA-Z]/', '\\\\$0', $translatedWord); }, $format ); return static::rawCreateFromFormat($format, static::translateTimeString($time, $locale, static::DEFAULT_LOCALE), $timezone); } /** * Create a Carbon instance from a specific ISO format and a string in a given language. * * @param string $format Datetime ISO format * @param string $locale * @param string $time * @param DateTimeZone|string|int|null $timezone * * @throws InvalidFormatException * * @return static|null */ public static function createFromLocaleIsoFormat(string $format, string $locale, string $time, $timezone = null): ?static { $time = static::translateTimeString($time, $locale, static::DEFAULT_LOCALE, CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS | CarbonInterface::TRANSLATE_MERIDIEM); return static::createFromIsoFormat($format, $time, $timezone, $locale); } /** * Make a Carbon instance from given variable if possible. * * Always return a new instance. Parse only strings and only these likely to be dates (skip intervals * and recurrences). Throw an exception for invalid format, but otherwise return null. * * @param mixed $var * * @throws InvalidFormatException * * @return static|null */ public static function make($var, DateTimeZone|string|null $timezone = null): ?static { if ($var instanceof DateTimeInterface) { return static::instance($var); } $date = null; if (\is_string($var)) { $var = trim($var); if (!preg_match('/^P[\dT]/', $var) && !preg_match('/^R\d/', $var) && preg_match('/[a-z\d]/i', $var) ) { $date = static::parse($var, $timezone); } } return $date; } /** * Set last errors. * * @param array|bool $lastErrors * * @return void */ private static function setLastErrors($lastErrors): void { static::$lastErrors = $lastErrors; } /** * {@inheritdoc} */ public static function getLastErrors(): array|false { return static::$lastErrors; } private static function monthToInt(mixed $value, string $unit = 'month'): mixed { if ($value instanceof Month) { if ($unit !== 'month') { throw new UnitException("Month enum cannot be used to set $unit"); } return Month::int($value); } return $value; } }
PHP
{ "end_line": 897, "name": "make", "signature": "public static function make($var, DateTimeZone|string|null $timezone = null): ?static", "start_line": 877 }
{ "class_name": "Creator", "class_signature": "trait Creator", "namespace": "Carbon\\Traits" }
carbonize
Carbon/src/Carbon/Traits/Date.php
public function carbonize($date = null) { if ($date instanceof DateInterval) { return $this->avoidMutation()->add($date); } if ($date instanceof DatePeriod || $date instanceof CarbonPeriod) { $date = $date->getStartDate(); } return $this->resolveCarbon($date); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use BadMethodCallException; use Carbon\Carbon; use Carbon\CarbonInterface; use Carbon\CarbonPeriod; use Carbon\CarbonTimeZone; use Carbon\Exceptions\BadComparisonUnitException; use Carbon\Exceptions\ImmutableException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Exceptions\UnitException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\FactoryImmutable; use Carbon\Month; use Carbon\Translator; use Carbon\Unit; use Carbon\WeekDay; use Closure; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use ReflectionException; use Symfony\Component\Clock\NativeClock; use Throwable; /** * A simple API extension for DateTime. * * <autodoc generated by `composer phpdoc`> * * @property string $localeDayOfWeek the day of week in current locale * @property string $shortLocaleDayOfWeek the abbreviated day of week in current locale * @property string $localeMonth the month in current locale * @property string $shortLocaleMonth the abbreviated month in current locale * @property int $year * @property int $yearIso * @property int $month * @property int $day * @property int $hour * @property int $minute * @property int $second * @property int $micro * @property int $microsecond * @property int $dayOfWeekIso 1 (for Monday) through 7 (for Sunday) * @property int|float|string $timestamp seconds since the Unix Epoch * @property string $englishDayOfWeek the day of week in English * @property string $shortEnglishDayOfWeek the abbreviated day of week in English * @property string $englishMonth the month in English * @property string $shortEnglishMonth the abbreviated month in English * @property int $milliseconds * @property int $millisecond * @property int $milli * @property int $week 1 through 53 * @property int $isoWeek 1 through 53 * @property int $weekYear year according to week format * @property int $isoWeekYear year according to ISO week format * @property int $age does a diffInYears() with default parameters * @property int $offset the timezone offset in seconds from UTC * @property int $offsetMinutes the timezone offset in minutes from UTC * @property int $offsetHours the timezone offset in hours from UTC * @property CarbonTimeZone $timezone the current timezone * @property CarbonTimeZone $tz alias of $timezone * @property int $centuryOfMillennium The value of the century starting from the beginning of the current millennium * @property int $dayOfCentury The value of the day starting from the beginning of the current century * @property int $dayOfDecade The value of the day starting from the beginning of the current decade * @property int $dayOfMillennium The value of the day starting from the beginning of the current millennium * @property int $dayOfMonth The value of the day starting from the beginning of the current month * @property int $dayOfQuarter The value of the day starting from the beginning of the current quarter * @property int $dayOfWeek 0 (for Sunday) through 6 (for Saturday) * @property int $dayOfYear 1 through 366 * @property int $decadeOfCentury The value of the decade starting from the beginning of the current century * @property int $decadeOfMillennium The value of the decade starting from the beginning of the current millennium * @property int $hourOfCentury The value of the hour starting from the beginning of the current century * @property int $hourOfDay The value of the hour starting from the beginning of the current day * @property int $hourOfDecade The value of the hour starting from the beginning of the current decade * @property int $hourOfMillennium The value of the hour starting from the beginning of the current millennium * @property int $hourOfMonth The value of the hour starting from the beginning of the current month * @property int $hourOfQuarter The value of the hour starting from the beginning of the current quarter * @property int $hourOfWeek The value of the hour starting from the beginning of the current week * @property int $hourOfYear The value of the hour starting from the beginning of the current year * @property int $microsecondOfCentury The value of the microsecond starting from the beginning of the current century * @property int $microsecondOfDay The value of the microsecond starting from the beginning of the current day * @property int $microsecondOfDecade The value of the microsecond starting from the beginning of the current decade * @property int $microsecondOfHour The value of the microsecond starting from the beginning of the current hour * @property int $microsecondOfMillennium The value of the microsecond starting from the beginning of the current millennium * @property int $microsecondOfMillisecond The value of the microsecond starting from the beginning of the current millisecond * @property int $microsecondOfMinute The value of the microsecond starting from the beginning of the current minute * @property int $microsecondOfMonth The value of the microsecond starting from the beginning of the current month * @property int $microsecondOfQuarter The value of the microsecond starting from the beginning of the current quarter * @property int $microsecondOfSecond The value of the microsecond starting from the beginning of the current second * @property int $microsecondOfWeek The value of the microsecond starting from the beginning of the current week * @property int $microsecondOfYear The value of the microsecond starting from the beginning of the current year * @property int $millisecondOfCentury The value of the millisecond starting from the beginning of the current century * @property int $millisecondOfDay The value of the millisecond starting from the beginning of the current day * @property int $millisecondOfDecade The value of the millisecond starting from the beginning of the current decade * @property int $millisecondOfHour The value of the millisecond starting from the beginning of the current hour * @property int $millisecondOfMillennium The value of the millisecond starting from the beginning of the current millennium * @property int $millisecondOfMinute The value of the millisecond starting from the beginning of the current minute * @property int $millisecondOfMonth The value of the millisecond starting from the beginning of the current month * @property int $millisecondOfQuarter The value of the millisecond starting from the beginning of the current quarter * @property int $millisecondOfSecond The value of the millisecond starting from the beginning of the current second * @property int $millisecondOfWeek The value of the millisecond starting from the beginning of the current week * @property int $millisecondOfYear The value of the millisecond starting from the beginning of the current year * @property int $minuteOfCentury The value of the minute starting from the beginning of the current century * @property int $minuteOfDay The value of the minute starting from the beginning of the current day * @property int $minuteOfDecade The value of the minute starting from the beginning of the current decade * @property int $minuteOfHour The value of the minute starting from the beginning of the current hour * @property int $minuteOfMillennium The value of the minute starting from the beginning of the current millennium * @property int $minuteOfMonth The value of the minute starting from the beginning of the current month * @property int $minuteOfQuarter The value of the minute starting from the beginning of the current quarter * @property int $minuteOfWeek The value of the minute starting from the beginning of the current week * @property int $minuteOfYear The value of the minute starting from the beginning of the current year * @property int $monthOfCentury The value of the month starting from the beginning of the current century * @property int $monthOfDecade The value of the month starting from the beginning of the current decade * @property int $monthOfMillennium The value of the month starting from the beginning of the current millennium * @property int $monthOfQuarter The value of the month starting from the beginning of the current quarter * @property int $monthOfYear The value of the month starting from the beginning of the current year * @property int $quarterOfCentury The value of the quarter starting from the beginning of the current century * @property int $quarterOfDecade The value of the quarter starting from the beginning of the current decade * @property int $quarterOfMillennium The value of the quarter starting from the beginning of the current millennium * @property int $quarterOfYear The value of the quarter starting from the beginning of the current year * @property int $secondOfCentury The value of the second starting from the beginning of the current century * @property int $secondOfDay The value of the second starting from the beginning of the current day * @property int $secondOfDecade The value of the second starting from the beginning of the current decade * @property int $secondOfHour The value of the second starting from the beginning of the current hour * @property int $secondOfMillennium The value of the second starting from the beginning of the current millennium * @property int $secondOfMinute The value of the second starting from the beginning of the current minute * @property int $secondOfMonth The value of the second starting from the beginning of the current month * @property int $secondOfQuarter The value of the second starting from the beginning of the current quarter * @property int $secondOfWeek The value of the second starting from the beginning of the current week * @property int $secondOfYear The value of the second starting from the beginning of the current year * @property int $weekOfCentury The value of the week starting from the beginning of the current century * @property int $weekOfDecade The value of the week starting from the beginning of the current decade * @property int $weekOfMillennium The value of the week starting from the beginning of the current millennium * @property int $weekOfMonth 1 through 5 * @property int $weekOfQuarter The value of the week starting from the beginning of the current quarter * @property int $weekOfYear ISO-8601 week number of year, weeks starting on Monday * @property int $yearOfCentury The value of the year starting from the beginning of the current century * @property int $yearOfDecade The value of the year starting from the beginning of the current decade * @property int $yearOfMillennium The value of the year starting from the beginning of the current millennium * @property-read string $latinMeridiem "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) * @property-read string $latinUpperMeridiem "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) * @property-read string $timezoneAbbreviatedName the current timezone abbreviated name * @property-read string $tzAbbrName alias of $timezoneAbbreviatedName * @property-read string $dayName long name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $shortDayName short name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $minDayName very short name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $monthName long name of month translated according to Carbon locale, in english if no translation available for current language * @property-read string $shortMonthName short name of month translated according to Carbon locale, in english if no translation available for current language * @property-read string $meridiem lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language * @property-read string $upperMeridiem uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language * @property-read int $noZeroHour current hour from 1 to 24 * @property-read int $isoWeeksInYear 51 through 53 * @property-read int $weekNumberInMonth 1 through 5 * @property-read int $firstWeekDay 0 through 6 * @property-read int $lastWeekDay 0 through 6 * @property-read int $quarter the quarter of this instance, 1 - 4 * @property-read int $decade the decade of this instance * @property-read int $century the century of this instance * @property-read int $millennium the millennium of this instance * @property-read bool $dst daylight savings time indicator, true if DST, false otherwise * @property-read bool $local checks if the timezone is local, true if local, false otherwise * @property-read bool $utc checks if the timezone is UTC, true if UTC, false otherwise * @property-read string $timezoneName the current timezone name * @property-read string $tzName alias of $timezoneName * @property-read string $locale locale of the current instance * @property-read int $centuriesInMillennium The number of centuries contained in the current millennium * @property-read int $daysInCentury The number of days contained in the current century * @property-read int $daysInDecade The number of days contained in the current decade * @property-read int $daysInMillennium The number of days contained in the current millennium * @property-read int $daysInMonth number of days in the given month * @property-read int $daysInQuarter The number of days contained in the current quarter * @property-read int $daysInWeek The number of days contained in the current week * @property-read int $daysInYear 365 or 366 * @property-read int $decadesInCentury The number of decades contained in the current century * @property-read int $decadesInMillennium The number of decades contained in the current millennium * @property-read int $hoursInCentury The number of hours contained in the current century * @property-read int $hoursInDay The number of hours contained in the current day * @property-read int $hoursInDecade The number of hours contained in the current decade * @property-read int $hoursInMillennium The number of hours contained in the current millennium * @property-read int $hoursInMonth The number of hours contained in the current month * @property-read int $hoursInQuarter The number of hours contained in the current quarter * @property-read int $hoursInWeek The number of hours contained in the current week * @property-read int $hoursInYear The number of hours contained in the current year * @property-read int $microsecondsInCentury The number of microseconds contained in the current century * @property-read int $microsecondsInDay The number of microseconds contained in the current day * @property-read int $microsecondsInDecade The number of microseconds contained in the current decade * @property-read int $microsecondsInHour The number of microseconds contained in the current hour * @property-read int $microsecondsInMillennium The number of microseconds contained in the current millennium * @property-read int $microsecondsInMillisecond The number of microseconds contained in the current millisecond * @property-read int $microsecondsInMinute The number of microseconds contained in the current minute * @property-read int $microsecondsInMonth The number of microseconds contained in the current month * @property-read int $microsecondsInQuarter The number of microseconds contained in the current quarter * @property-read int $microsecondsInSecond The number of microseconds contained in the current second * @property-read int $microsecondsInWeek The number of microseconds contained in the current week * @property-read int $microsecondsInYear The number of microseconds contained in the current year * @property-read int $millisecondsInCentury The number of milliseconds contained in the current century * @property-read int $millisecondsInDay The number of milliseconds contained in the current day * @property-read int $millisecondsInDecade The number of milliseconds contained in the current decade * @property-read int $millisecondsInHour The number of milliseconds contained in the current hour * @property-read int $millisecondsInMillennium The number of milliseconds contained in the current millennium * @property-read int $millisecondsInMinute The number of milliseconds contained in the current minute * @property-read int $millisecondsInMonth The number of milliseconds contained in the current month * @property-read int $millisecondsInQuarter The number of milliseconds contained in the current quarter * @property-read int $millisecondsInSecond The number of milliseconds contained in the current second * @property-read int $millisecondsInWeek The number of milliseconds contained in the current week * @property-read int $millisecondsInYear The number of milliseconds contained in the current year * @property-read int $minutesInCentury The number of minutes contained in the current century * @property-read int $minutesInDay The number of minutes contained in the current day * @property-read int $minutesInDecade The number of minutes contained in the current decade * @property-read int $minutesInHour The number of minutes contained in the current hour * @property-read int $minutesInMillennium The number of minutes contained in the current millennium * @property-read int $minutesInMonth The number of minutes contained in the current month * @property-read int $minutesInQuarter The number of minutes contained in the current quarter * @property-read int $minutesInWeek The number of minutes contained in the current week * @property-read int $minutesInYear The number of minutes contained in the current year * @property-read int $monthsInCentury The number of months contained in the current century * @property-read int $monthsInDecade The number of months contained in the current decade * @property-read int $monthsInMillennium The number of months contained in the current millennium * @property-read int $monthsInQuarter The number of months contained in the current quarter * @property-read int $monthsInYear The number of months contained in the current year * @property-read int $quartersInCentury The number of quarters contained in the current century * @property-read int $quartersInDecade The number of quarters contained in the current decade * @property-read int $quartersInMillennium The number of quarters contained in the current millennium * @property-read int $quartersInYear The number of quarters contained in the current year * @property-read int $secondsInCentury The number of seconds contained in the current century * @property-read int $secondsInDay The number of seconds contained in the current day * @property-read int $secondsInDecade The number of seconds contained in the current decade * @property-read int $secondsInHour The number of seconds contained in the current hour * @property-read int $secondsInMillennium The number of seconds contained in the current millennium * @property-read int $secondsInMinute The number of seconds contained in the current minute * @property-read int $secondsInMonth The number of seconds contained in the current month * @property-read int $secondsInQuarter The number of seconds contained in the current quarter * @property-read int $secondsInWeek The number of seconds contained in the current week * @property-read int $secondsInYear The number of seconds contained in the current year * @property-read int $weeksInCentury The number of weeks contained in the current century * @property-read int $weeksInDecade The number of weeks contained in the current decade * @property-read int $weeksInMillennium The number of weeks contained in the current millennium * @property-read int $weeksInMonth The number of weeks contained in the current month * @property-read int $weeksInQuarter The number of weeks contained in the current quarter * @property-read int $weeksInYear 51 through 53 * @property-read int $yearsInCentury The number of years contained in the current century * @property-read int $yearsInDecade The number of years contained in the current decade * @property-read int $yearsInMillennium The number of years contained in the current millennium * * @method bool isUtc() Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) * @method bool isLocal() Check if the current instance has non-UTC timezone. * @method bool isValid() Check if the current instance is a valid date. * @method bool isDST() Check if the current instance is in a daylight saving time. * @method bool isSunday() Checks if the instance day is sunday. * @method bool isMonday() Checks if the instance day is monday. * @method bool isTuesday() Checks if the instance day is tuesday. * @method bool isWednesday() Checks if the instance day is wednesday. * @method bool isThursday() Checks if the instance day is thursday. * @method bool isFriday() Checks if the instance day is friday. * @method bool isSaturday() Checks if the instance day is saturday. * @method bool isSameYear(DateTimeInterface|string $date) Checks if the given date is in the same year as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentYear() Checks if the instance is in the same year as the current moment. * @method bool isNextYear() Checks if the instance is in the same year as the current moment next year. * @method bool isLastYear() Checks if the instance is in the same year as the current moment last year. * @method bool isCurrentMonth() Checks if the instance is in the same month as the current moment. * @method bool isNextMonth() Checks if the instance is in the same month as the current moment next month. * @method bool isLastMonth() Checks if the instance is in the same month as the current moment last month. * @method bool isSameWeek(DateTimeInterface|string $date) Checks if the given date is in the same week as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentWeek() Checks if the instance is in the same week as the current moment. * @method bool isNextWeek() Checks if the instance is in the same week as the current moment next week. * @method bool isLastWeek() Checks if the instance is in the same week as the current moment last week. * @method bool isSameDay(DateTimeInterface|string $date) Checks if the given date is in the same day as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentDay() Checks if the instance is in the same day as the current moment. * @method bool isNextDay() Checks if the instance is in the same day as the current moment next day. * @method bool isLastDay() Checks if the instance is in the same day as the current moment last day. * @method bool isSameHour(DateTimeInterface|string $date) Checks if the given date is in the same hour as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentHour() Checks if the instance is in the same hour as the current moment. * @method bool isNextHour() Checks if the instance is in the same hour as the current moment next hour. * @method bool isLastHour() Checks if the instance is in the same hour as the current moment last hour. * @method bool isSameMinute(DateTimeInterface|string $date) Checks if the given date is in the same minute as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMinute() Checks if the instance is in the same minute as the current moment. * @method bool isNextMinute() Checks if the instance is in the same minute as the current moment next minute. * @method bool isLastMinute() Checks if the instance is in the same minute as the current moment last minute. * @method bool isSameSecond(DateTimeInterface|string $date) Checks if the given date is in the same second as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentSecond() Checks if the instance is in the same second as the current moment. * @method bool isNextSecond() Checks if the instance is in the same second as the current moment next second. * @method bool isLastSecond() Checks if the instance is in the same second as the current moment last second. * @method bool isSameMilli(DateTimeInterface|string $date) Checks if the given date is in the same millisecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMilli() Checks if the instance is in the same millisecond as the current moment. * @method bool isNextMilli() Checks if the instance is in the same millisecond as the current moment next millisecond. * @method bool isLastMilli() Checks if the instance is in the same millisecond as the current moment last millisecond. * @method bool isSameMillisecond(DateTimeInterface|string $date) Checks if the given date is in the same millisecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMillisecond() Checks if the instance is in the same millisecond as the current moment. * @method bool isNextMillisecond() Checks if the instance is in the same millisecond as the current moment next millisecond. * @method bool isLastMillisecond() Checks if the instance is in the same millisecond as the current moment last millisecond. * @method bool isSameMicro(DateTimeInterface|string $date) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMicro() Checks if the instance is in the same microsecond as the current moment. * @method bool isNextMicro() Checks if the instance is in the same microsecond as the current moment next microsecond. * @method bool isLastMicro() Checks if the instance is in the same microsecond as the current moment last microsecond. * @method bool isSameMicrosecond(DateTimeInterface|string $date) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMicrosecond() Checks if the instance is in the same microsecond as the current moment. * @method bool isNextMicrosecond() Checks if the instance is in the same microsecond as the current moment next microsecond. * @method bool isLastMicrosecond() Checks if the instance is in the same microsecond as the current moment last microsecond. * @method bool isSameDecade(DateTimeInterface|string $date) Checks if the given date is in the same decade as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentDecade() Checks if the instance is in the same decade as the current moment. * @method bool isNextDecade() Checks if the instance is in the same decade as the current moment next decade. * @method bool isLastDecade() Checks if the instance is in the same decade as the current moment last decade. * @method bool isSameCentury(DateTimeInterface|string $date) Checks if the given date is in the same century as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentCentury() Checks if the instance is in the same century as the current moment. * @method bool isNextCentury() Checks if the instance is in the same century as the current moment next century. * @method bool isLastCentury() Checks if the instance is in the same century as the current moment last century. * @method bool isSameMillennium(DateTimeInterface|string $date) Checks if the given date is in the same millennium as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMillennium() Checks if the instance is in the same millennium as the current moment. * @method bool isNextMillennium() Checks if the instance is in the same millennium as the current moment next millennium. * @method bool isLastMillennium() Checks if the instance is in the same millennium as the current moment last millennium. * @method bool isCurrentQuarter() Checks if the instance is in the same quarter as the current moment. * @method bool isNextQuarter() Checks if the instance is in the same quarter as the current moment next quarter. * @method bool isLastQuarter() Checks if the instance is in the same quarter as the current moment last quarter. * @method CarbonInterface years(int $value) Set current instance year to the given value. * @method CarbonInterface year(int $value) Set current instance year to the given value. * @method CarbonInterface setYears(int $value) Set current instance year to the given value. * @method CarbonInterface setYear(int $value) Set current instance year to the given value. * @method CarbonInterface months(Month|int $value) Set current instance month to the given value. * @method CarbonInterface month(Month|int $value) Set current instance month to the given value. * @method CarbonInterface setMonths(Month|int $value) Set current instance month to the given value. * @method CarbonInterface setMonth(Month|int $value) Set current instance month to the given value. * @method CarbonInterface days(int $value) Set current instance day to the given value. * @method CarbonInterface day(int $value) Set current instance day to the given value. * @method CarbonInterface setDays(int $value) Set current instance day to the given value. * @method CarbonInterface setDay(int $value) Set current instance day to the given value. * @method CarbonInterface hours(int $value) Set current instance hour to the given value. * @method CarbonInterface hour(int $value) Set current instance hour to the given value. * @method CarbonInterface setHours(int $value) Set current instance hour to the given value. * @method CarbonInterface setHour(int $value) Set current instance hour to the given value. * @method CarbonInterface minutes(int $value) Set current instance minute to the given value. * @method CarbonInterface minute(int $value) Set current instance minute to the given value. * @method CarbonInterface setMinutes(int $value) Set current instance minute to the given value. * @method CarbonInterface setMinute(int $value) Set current instance minute to the given value. * @method CarbonInterface seconds(int $value) Set current instance second to the given value. * @method CarbonInterface second(int $value) Set current instance second to the given value. * @method CarbonInterface setSeconds(int $value) Set current instance second to the given value. * @method CarbonInterface setSecond(int $value) Set current instance second to the given value. * @method CarbonInterface millis(int $value) Set current instance millisecond to the given value. * @method CarbonInterface milli(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMillis(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMilli(int $value) Set current instance millisecond to the given value. * @method CarbonInterface milliseconds(int $value) Set current instance millisecond to the given value. * @method CarbonInterface millisecond(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMilliseconds(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMillisecond(int $value) Set current instance millisecond to the given value. * @method CarbonInterface micros(int $value) Set current instance microsecond to the given value. * @method CarbonInterface micro(int $value) Set current instance microsecond to the given value. * @method CarbonInterface setMicros(int $value) Set current instance microsecond to the given value. * @method CarbonInterface setMicro(int $value) Set current instance microsecond to the given value. * @method CarbonInterface microseconds(int $value) Set current instance microsecond to the given value. * @method CarbonInterface microsecond(int $value) Set current instance microsecond to the given value. * @method CarbonInterface setMicroseconds(int $value) Set current instance microsecond to the given value. * @method self setMicrosecond(int $value) Set current instance microsecond to the given value. * @method CarbonInterface addYears(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addYear() Add one year to the instance (using date interval). * @method CarbonInterface subYears(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subYear() Sub one year to the instance (using date interval). * @method CarbonInterface addYearsWithOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addYearWithOverflow() Add one year to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subYearsWithOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subYearWithOverflow() Sub one year to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addYearsWithoutOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearWithoutOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearsWithoutOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearWithoutOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearsWithNoOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearWithNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearsWithNoOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearWithNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearsNoOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearsNoOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonths(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMonth() Add one month to the instance (using date interval). * @method CarbonInterface subMonths(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMonth() Sub one month to the instance (using date interval). * @method CarbonInterface addMonthsWithOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMonthWithOverflow() Add one month to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMonthsWithOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMonthWithOverflow() Sub one month to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMonthsWithoutOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthWithoutOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthsWithoutOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthWithoutOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthsWithNoOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthWithNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthsWithNoOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthWithNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthsNoOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthsNoOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDays(int|float $value = 1) Add days (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addDay() Add one day to the instance (using date interval). * @method CarbonInterface subDays(int|float $value = 1) Sub days (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subDay() Sub one day to the instance (using date interval). * @method CarbonInterface addHours(int|float $value = 1) Add hours (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addHour() Add one hour to the instance (using date interval). * @method CarbonInterface subHours(int|float $value = 1) Sub hours (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subHour() Sub one hour to the instance (using date interval). * @method CarbonInterface addMinutes(int|float $value = 1) Add minutes (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMinute() Add one minute to the instance (using date interval). * @method CarbonInterface subMinutes(int|float $value = 1) Sub minutes (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMinute() Sub one minute to the instance (using date interval). * @method CarbonInterface addSeconds(int|float $value = 1) Add seconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addSecond() Add one second to the instance (using date interval). * @method CarbonInterface subSeconds(int|float $value = 1) Sub seconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subSecond() Sub one second to the instance (using date interval). * @method CarbonInterface addMillis(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMilli() Add one millisecond to the instance (using date interval). * @method CarbonInterface subMillis(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMilli() Sub one millisecond to the instance (using date interval). * @method CarbonInterface addMilliseconds(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMillisecond() Add one millisecond to the instance (using date interval). * @method CarbonInterface subMilliseconds(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMillisecond() Sub one millisecond to the instance (using date interval). * @method CarbonInterface addMicros(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMicro() Add one microsecond to the instance (using date interval). * @method CarbonInterface subMicros(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMicro() Sub one microsecond to the instance (using date interval). * @method CarbonInterface addMicroseconds(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMicrosecond() Add one microsecond to the instance (using date interval). * @method CarbonInterface subMicroseconds(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMicrosecond() Sub one microsecond to the instance (using date interval). * @method CarbonInterface addMillennia(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMillennium() Add one millennium to the instance (using date interval). * @method CarbonInterface subMillennia(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMillennium() Sub one millennium to the instance (using date interval). * @method CarbonInterface addMillenniaWithOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMillenniumWithOverflow() Add one millennium to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMillenniaWithOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMillenniumWithOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMillenniaWithoutOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniumWithoutOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniaWithoutOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniumWithoutOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniaWithNoOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniumWithNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniaWithNoOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniumWithNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniaNoOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniumNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniaNoOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniumNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturies(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addCentury() Add one century to the instance (using date interval). * @method CarbonInterface subCenturies(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subCentury() Sub one century to the instance (using date interval). * @method CarbonInterface addCenturiesWithOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addCenturyWithOverflow() Add one century to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subCenturiesWithOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subCenturyWithOverflow() Sub one century to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addCenturiesWithoutOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturyWithoutOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturiesWithoutOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturyWithoutOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturiesWithNoOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturyWithNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturiesWithNoOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturyWithNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturiesNoOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturyNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturiesNoOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturyNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecades(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addDecade() Add one decade to the instance (using date interval). * @method CarbonInterface subDecades(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subDecade() Sub one decade to the instance (using date interval). * @method CarbonInterface addDecadesWithOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addDecadeWithOverflow() Add one decade to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subDecadesWithOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subDecadeWithOverflow() Sub one decade to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addDecadesWithoutOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadeWithoutOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadesWithoutOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadeWithoutOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadesWithNoOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadeWithNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadesWithNoOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadeWithNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadesNoOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadeNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadesNoOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadeNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarters(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addQuarter() Add one quarter to the instance (using date interval). * @method CarbonInterface subQuarters(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subQuarter() Sub one quarter to the instance (using date interval). * @method CarbonInterface addQuartersWithOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addQuarterWithOverflow() Add one quarter to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subQuartersWithOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subQuarterWithOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addQuartersWithoutOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarterWithoutOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuartersWithoutOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuarterWithoutOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuartersWithNoOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarterWithNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuartersWithNoOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuarterWithNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuartersNoOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarterNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuartersNoOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuarterNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addWeeks(int|float $value = 1) Add weeks (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addWeek() Add one week to the instance (using date interval). * @method CarbonInterface subWeeks(int|float $value = 1) Sub weeks (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subWeek() Sub one week to the instance (using date interval). * @method CarbonInterface addWeekdays(int|float $value = 1) Add weekdays (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addWeekday() Add one weekday to the instance (using date interval). * @method CarbonInterface subWeekdays(int|float $value = 1) Sub weekdays (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subWeekday() Sub one weekday to the instance (using date interval). * @method CarbonInterface addUTCMicros(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMicro() Add one microsecond to the instance (using timestamp). * @method CarbonInterface subUTCMicros(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMicro() Sub one microsecond to the instance (using timestamp). * @method CarbonPeriod microsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. * @method float diffInUTCMicros(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of microseconds. * @method CarbonInterface addUTCMicroseconds(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMicrosecond() Add one microsecond to the instance (using timestamp). * @method CarbonInterface subUTCMicroseconds(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMicrosecond() Sub one microsecond to the instance (using timestamp). * @method CarbonPeriod microsecondsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. * @method float diffInUTCMicroseconds(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of microseconds. * @method CarbonInterface addUTCMillis(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMilli() Add one millisecond to the instance (using timestamp). * @method CarbonInterface subUTCMillis(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMilli() Sub one millisecond to the instance (using timestamp). * @method CarbonPeriod millisUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. * @method float diffInUTCMillis(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of milliseconds. * @method CarbonInterface addUTCMilliseconds(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMillisecond() Add one millisecond to the instance (using timestamp). * @method CarbonInterface subUTCMilliseconds(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMillisecond() Sub one millisecond to the instance (using timestamp). * @method CarbonPeriod millisecondsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. * @method float diffInUTCMilliseconds(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of milliseconds. * @method CarbonInterface addUTCSeconds(int|float $value = 1) Add seconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCSecond() Add one second to the instance (using timestamp). * @method CarbonInterface subUTCSeconds(int|float $value = 1) Sub seconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCSecond() Sub one second to the instance (using timestamp). * @method CarbonPeriod secondsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each second or every X seconds if a factor is given. * @method float diffInUTCSeconds(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of seconds. * @method CarbonInterface addUTCMinutes(int|float $value = 1) Add minutes (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMinute() Add one minute to the instance (using timestamp). * @method CarbonInterface subUTCMinutes(int|float $value = 1) Sub minutes (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMinute() Sub one minute to the instance (using timestamp). * @method CarbonPeriod minutesUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each minute or every X minutes if a factor is given. * @method float diffInUTCMinutes(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of minutes. * @method CarbonInterface addUTCHours(int|float $value = 1) Add hours (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCHour() Add one hour to the instance (using timestamp). * @method CarbonInterface subUTCHours(int|float $value = 1) Sub hours (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCHour() Sub one hour to the instance (using timestamp). * @method CarbonPeriod hoursUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each hour or every X hours if a factor is given. * @method float diffInUTCHours(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of hours. * @method CarbonInterface addUTCDays(int|float $value = 1) Add days (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCDay() Add one day to the instance (using timestamp). * @method CarbonInterface subUTCDays(int|float $value = 1) Sub days (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCDay() Sub one day to the instance (using timestamp). * @method CarbonPeriod daysUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each day or every X days if a factor is given. * @method float diffInUTCDays(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of days. * @method CarbonInterface addUTCWeeks(int|float $value = 1) Add weeks (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCWeek() Add one week to the instance (using timestamp). * @method CarbonInterface subUTCWeeks(int|float $value = 1) Sub weeks (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCWeek() Sub one week to the instance (using timestamp). * @method CarbonPeriod weeksUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each week or every X weeks if a factor is given. * @method float diffInUTCWeeks(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of weeks. * @method CarbonInterface addUTCMonths(int|float $value = 1) Add months (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMonth() Add one month to the instance (using timestamp). * @method CarbonInterface subUTCMonths(int|float $value = 1) Sub months (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMonth() Sub one month to the instance (using timestamp). * @method CarbonPeriod monthsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each month or every X months if a factor is given. * @method float diffInUTCMonths(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of months. * @method CarbonInterface addUTCQuarters(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCQuarter() Add one quarter to the instance (using timestamp). * @method CarbonInterface subUTCQuarters(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCQuarter() Sub one quarter to the instance (using timestamp). * @method CarbonPeriod quartersUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each quarter or every X quarters if a factor is given. * @method float diffInUTCQuarters(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of quarters. * @method CarbonInterface addUTCYears(int|float $value = 1) Add years (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCYear() Add one year to the instance (using timestamp). * @method CarbonInterface subUTCYears(int|float $value = 1) Sub years (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCYear() Sub one year to the instance (using timestamp). * @method CarbonPeriod yearsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each year or every X years if a factor is given. * @method float diffInUTCYears(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of years. * @method CarbonInterface addUTCDecades(int|float $value = 1) Add decades (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCDecade() Add one decade to the instance (using timestamp). * @method CarbonInterface subUTCDecades(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCDecade() Sub one decade to the instance (using timestamp). * @method CarbonPeriod decadesUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each decade or every X decades if a factor is given. * @method float diffInUTCDecades(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of decades. * @method CarbonInterface addUTCCenturies(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCCentury() Add one century to the instance (using timestamp). * @method CarbonInterface subUTCCenturies(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCCentury() Sub one century to the instance (using timestamp). * @method CarbonPeriod centuriesUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each century or every X centuries if a factor is given. * @method float diffInUTCCenturies(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of centuries. * @method CarbonInterface addUTCMillennia(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMillennium() Add one millennium to the instance (using timestamp). * @method CarbonInterface subUTCMillennia(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMillennium() Sub one millennium to the instance (using timestamp). * @method CarbonPeriod millenniaUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millennium or every X millennia if a factor is given. * @method float diffInUTCMillennia(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of millennia. * @method CarbonInterface roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method CarbonInterface roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method CarbonInterface floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method CarbonInterface floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method CarbonInterface ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method CarbonInterface ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method CarbonInterface roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method CarbonInterface roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method CarbonInterface floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method CarbonInterface floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method CarbonInterface ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method CarbonInterface ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method CarbonInterface roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method CarbonInterface roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method CarbonInterface floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method CarbonInterface floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method CarbonInterface ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method CarbonInterface ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method CarbonInterface roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method CarbonInterface roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method CarbonInterface floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method CarbonInterface floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method CarbonInterface ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method CarbonInterface ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method CarbonInterface roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method CarbonInterface roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method CarbonInterface floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method CarbonInterface floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method CarbonInterface ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method CarbonInterface ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method CarbonInterface roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method CarbonInterface roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method CarbonInterface floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method CarbonInterface floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method CarbonInterface ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method CarbonInterface ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method CarbonInterface roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method CarbonInterface roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method CarbonInterface floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method CarbonInterface floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method CarbonInterface ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method CarbonInterface ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method CarbonInterface roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method CarbonInterface roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method CarbonInterface floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method CarbonInterface floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method CarbonInterface ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method CarbonInterface ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method CarbonInterface roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method CarbonInterface roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method CarbonInterface floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method CarbonInterface floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method CarbonInterface ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method CarbonInterface ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method CarbonInterface roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method CarbonInterface roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method CarbonInterface floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method CarbonInterface floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method CarbonInterface ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method CarbonInterface ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method CarbonInterface roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method CarbonInterface roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method CarbonInterface floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method CarbonInterface floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method CarbonInterface ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method CarbonInterface ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method CarbonInterface roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method CarbonInterface roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method CarbonInterface floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method CarbonInterface floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method CarbonInterface ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method CarbonInterface ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * @method string shortAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string shortRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string shortRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string shortRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method int centuriesInMillennium() Return the number of centuries contained in the current millennium * @method int|static centuryOfMillennium(?int $century = null) Return the value of the century starting from the beginning of the current millennium when called with no parameters, change the current century when called with an integer value * @method int|static dayOfCentury(?int $day = null) Return the value of the day starting from the beginning of the current century when called with no parameters, change the current day when called with an integer value * @method int|static dayOfDecade(?int $day = null) Return the value of the day starting from the beginning of the current decade when called with no parameters, change the current day when called with an integer value * @method int|static dayOfMillennium(?int $day = null) Return the value of the day starting from the beginning of the current millennium when called with no parameters, change the current day when called with an integer value * @method int|static dayOfMonth(?int $day = null) Return the value of the day starting from the beginning of the current month when called with no parameters, change the current day when called with an integer value * @method int|static dayOfQuarter(?int $day = null) Return the value of the day starting from the beginning of the current quarter when called with no parameters, change the current day when called with an integer value * @method int|static dayOfWeek(?int $day = null) Return the value of the day starting from the beginning of the current week when called with no parameters, change the current day when called with an integer value * @method int daysInCentury() Return the number of days contained in the current century * @method int daysInDecade() Return the number of days contained in the current decade * @method int daysInMillennium() Return the number of days contained in the current millennium * @method int daysInMonth() Return the number of days contained in the current month * @method int daysInQuarter() Return the number of days contained in the current quarter * @method int daysInWeek() Return the number of days contained in the current week * @method int daysInYear() Return the number of days contained in the current year * @method int|static decadeOfCentury(?int $decade = null) Return the value of the decade starting from the beginning of the current century when called with no parameters, change the current decade when called with an integer value * @method int|static decadeOfMillennium(?int $decade = null) Return the value of the decade starting from the beginning of the current millennium when called with no parameters, change the current decade when called with an integer value * @method int decadesInCentury() Return the number of decades contained in the current century * @method int decadesInMillennium() Return the number of decades contained in the current millennium * @method int|static hourOfCentury(?int $hour = null) Return the value of the hour starting from the beginning of the current century when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfDay(?int $hour = null) Return the value of the hour starting from the beginning of the current day when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfDecade(?int $hour = null) Return the value of the hour starting from the beginning of the current decade when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfMillennium(?int $hour = null) Return the value of the hour starting from the beginning of the current millennium when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfMonth(?int $hour = null) Return the value of the hour starting from the beginning of the current month when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfQuarter(?int $hour = null) Return the value of the hour starting from the beginning of the current quarter when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfWeek(?int $hour = null) Return the value of the hour starting from the beginning of the current week when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfYear(?int $hour = null) Return the value of the hour starting from the beginning of the current year when called with no parameters, change the current hour when called with an integer value * @method int hoursInCentury() Return the number of hours contained in the current century * @method int hoursInDay() Return the number of hours contained in the current day * @method int hoursInDecade() Return the number of hours contained in the current decade * @method int hoursInMillennium() Return the number of hours contained in the current millennium * @method int hoursInMonth() Return the number of hours contained in the current month * @method int hoursInQuarter() Return the number of hours contained in the current quarter * @method int hoursInWeek() Return the number of hours contained in the current week * @method int hoursInYear() Return the number of hours contained in the current year * @method int|static microsecondOfCentury(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current century when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfDay(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current day when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfDecade(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current decade when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfHour(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current hour when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMillennium(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current millennium when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMillisecond(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current millisecond when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMinute(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current minute when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMonth(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current month when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfQuarter(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current quarter when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfSecond(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current second when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfWeek(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current week when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfYear(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current year when called with no parameters, change the current microsecond when called with an integer value * @method int microsecondsInCentury() Return the number of microseconds contained in the current century * @method int microsecondsInDay() Return the number of microseconds contained in the current day * @method int microsecondsInDecade() Return the number of microseconds contained in the current decade * @method int microsecondsInHour() Return the number of microseconds contained in the current hour * @method int microsecondsInMillennium() Return the number of microseconds contained in the current millennium * @method int microsecondsInMillisecond() Return the number of microseconds contained in the current millisecond * @method int microsecondsInMinute() Return the number of microseconds contained in the current minute * @method int microsecondsInMonth() Return the number of microseconds contained in the current month * @method int microsecondsInQuarter() Return the number of microseconds contained in the current quarter * @method int microsecondsInSecond() Return the number of microseconds contained in the current second * @method int microsecondsInWeek() Return the number of microseconds contained in the current week * @method int microsecondsInYear() Return the number of microseconds contained in the current year * @method int|static millisecondOfCentury(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current century when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfDay(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current day when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfDecade(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current decade when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfHour(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current hour when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfMillennium(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current millennium when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfMinute(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current minute when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfMonth(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current month when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfQuarter(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current quarter when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfSecond(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current second when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfWeek(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current week when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfYear(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current year when called with no parameters, change the current millisecond when called with an integer value * @method int millisecondsInCentury() Return the number of milliseconds contained in the current century * @method int millisecondsInDay() Return the number of milliseconds contained in the current day * @method int millisecondsInDecade() Return the number of milliseconds contained in the current decade * @method int millisecondsInHour() Return the number of milliseconds contained in the current hour * @method int millisecondsInMillennium() Return the number of milliseconds contained in the current millennium * @method int millisecondsInMinute() Return the number of milliseconds contained in the current minute * @method int millisecondsInMonth() Return the number of milliseconds contained in the current month * @method int millisecondsInQuarter() Return the number of milliseconds contained in the current quarter * @method int millisecondsInSecond() Return the number of milliseconds contained in the current second * @method int millisecondsInWeek() Return the number of milliseconds contained in the current week * @method int millisecondsInYear() Return the number of milliseconds contained in the current year * @method int|static minuteOfCentury(?int $minute = null) Return the value of the minute starting from the beginning of the current century when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfDay(?int $minute = null) Return the value of the minute starting from the beginning of the current day when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfDecade(?int $minute = null) Return the value of the minute starting from the beginning of the current decade when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfHour(?int $minute = null) Return the value of the minute starting from the beginning of the current hour when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfMillennium(?int $minute = null) Return the value of the minute starting from the beginning of the current millennium when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfMonth(?int $minute = null) Return the value of the minute starting from the beginning of the current month when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfQuarter(?int $minute = null) Return the value of the minute starting from the beginning of the current quarter when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfWeek(?int $minute = null) Return the value of the minute starting from the beginning of the current week when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfYear(?int $minute = null) Return the value of the minute starting from the beginning of the current year when called with no parameters, change the current minute when called with an integer value * @method int minutesInCentury() Return the number of minutes contained in the current century * @method int minutesInDay() Return the number of minutes contained in the current day * @method int minutesInDecade() Return the number of minutes contained in the current decade * @method int minutesInHour() Return the number of minutes contained in the current hour * @method int minutesInMillennium() Return the number of minutes contained in the current millennium * @method int minutesInMonth() Return the number of minutes contained in the current month * @method int minutesInQuarter() Return the number of minutes contained in the current quarter * @method int minutesInWeek() Return the number of minutes contained in the current week * @method int minutesInYear() Return the number of minutes contained in the current year * @method int|static monthOfCentury(?int $month = null) Return the value of the month starting from the beginning of the current century when called with no parameters, change the current month when called with an integer value * @method int|static monthOfDecade(?int $month = null) Return the value of the month starting from the beginning of the current decade when called with no parameters, change the current month when called with an integer value * @method int|static monthOfMillennium(?int $month = null) Return the value of the month starting from the beginning of the current millennium when called with no parameters, change the current month when called with an integer value * @method int|static monthOfQuarter(?int $month = null) Return the value of the month starting from the beginning of the current quarter when called with no parameters, change the current month when called with an integer value * @method int|static monthOfYear(?int $month = null) Return the value of the month starting from the beginning of the current year when called with no parameters, change the current month when called with an integer value * @method int monthsInCentury() Return the number of months contained in the current century * @method int monthsInDecade() Return the number of months contained in the current decade * @method int monthsInMillennium() Return the number of months contained in the current millennium * @method int monthsInQuarter() Return the number of months contained in the current quarter * @method int monthsInYear() Return the number of months contained in the current year * @method int|static quarterOfCentury(?int $quarter = null) Return the value of the quarter starting from the beginning of the current century when called with no parameters, change the current quarter when called with an integer value * @method int|static quarterOfDecade(?int $quarter = null) Return the value of the quarter starting from the beginning of the current decade when called with no parameters, change the current quarter when called with an integer value * @method int|static quarterOfMillennium(?int $quarter = null) Return the value of the quarter starting from the beginning of the current millennium when called with no parameters, change the current quarter when called with an integer value * @method int|static quarterOfYear(?int $quarter = null) Return the value of the quarter starting from the beginning of the current year when called with no parameters, change the current quarter when called with an integer value * @method int quartersInCentury() Return the number of quarters contained in the current century * @method int quartersInDecade() Return the number of quarters contained in the current decade * @method int quartersInMillennium() Return the number of quarters contained in the current millennium * @method int quartersInYear() Return the number of quarters contained in the current year * @method int|static secondOfCentury(?int $second = null) Return the value of the second starting from the beginning of the current century when called with no parameters, change the current second when called with an integer value * @method int|static secondOfDay(?int $second = null) Return the value of the second starting from the beginning of the current day when called with no parameters, change the current second when called with an integer value * @method int|static secondOfDecade(?int $second = null) Return the value of the second starting from the beginning of the current decade when called with no parameters, change the current second when called with an integer value * @method int|static secondOfHour(?int $second = null) Return the value of the second starting from the beginning of the current hour when called with no parameters, change the current second when called with an integer value * @method int|static secondOfMillennium(?int $second = null) Return the value of the second starting from the beginning of the current millennium when called with no parameters, change the current second when called with an integer value * @method int|static secondOfMinute(?int $second = null) Return the value of the second starting from the beginning of the current minute when called with no parameters, change the current second when called with an integer value * @method int|static secondOfMonth(?int $second = null) Return the value of the second starting from the beginning of the current month when called with no parameters, change the current second when called with an integer value * @method int|static secondOfQuarter(?int $second = null) Return the value of the second starting from the beginning of the current quarter when called with no parameters, change the current second when called with an integer value * @method int|static secondOfWeek(?int $second = null) Return the value of the second starting from the beginning of the current week when called with no parameters, change the current second when called with an integer value * @method int|static secondOfYear(?int $second = null) Return the value of the second starting from the beginning of the current year when called with no parameters, change the current second when called with an integer value * @method int secondsInCentury() Return the number of seconds contained in the current century * @method int secondsInDay() Return the number of seconds contained in the current day * @method int secondsInDecade() Return the number of seconds contained in the current decade * @method int secondsInHour() Return the number of seconds contained in the current hour * @method int secondsInMillennium() Return the number of seconds contained in the current millennium * @method int secondsInMinute() Return the number of seconds contained in the current minute * @method int secondsInMonth() Return the number of seconds contained in the current month * @method int secondsInQuarter() Return the number of seconds contained in the current quarter * @method int secondsInWeek() Return the number of seconds contained in the current week * @method int secondsInYear() Return the number of seconds contained in the current year * @method int|static weekOfCentury(?int $week = null) Return the value of the week starting from the beginning of the current century when called with no parameters, change the current week when called with an integer value * @method int|static weekOfDecade(?int $week = null) Return the value of the week starting from the beginning of the current decade when called with no parameters, change the current week when called with an integer value * @method int|static weekOfMillennium(?int $week = null) Return the value of the week starting from the beginning of the current millennium when called with no parameters, change the current week when called with an integer value * @method int|static weekOfMonth(?int $week = null) Return the value of the week starting from the beginning of the current month when called with no parameters, change the current week when called with an integer value * @method int|static weekOfQuarter(?int $week = null) Return the value of the week starting from the beginning of the current quarter when called with no parameters, change the current week when called with an integer value * @method int|static weekOfYear(?int $week = null) Return the value of the week starting from the beginning of the current year when called with no parameters, change the current week when called with an integer value * @method int weeksInCentury() Return the number of weeks contained in the current century * @method int weeksInDecade() Return the number of weeks contained in the current decade * @method int weeksInMillennium() Return the number of weeks contained in the current millennium * @method int weeksInMonth() Return the number of weeks contained in the current month * @method int weeksInQuarter() Return the number of weeks contained in the current quarter * @method int|static yearOfCentury(?int $year = null) Return the value of the year starting from the beginning of the current century when called with no parameters, change the current year when called with an integer value * @method int|static yearOfDecade(?int $year = null) Return the value of the year starting from the beginning of the current decade when called with no parameters, change the current year when called with an integer value * @method int|static yearOfMillennium(?int $year = null) Return the value of the year starting from the beginning of the current millennium when called with no parameters, change the current year when called with an integer value * @method int yearsInCentury() Return the number of years contained in the current century * @method int yearsInDecade() Return the number of years contained in the current decade * @method int yearsInMillennium() Return the number of years contained in the current millennium * * </autodoc> */ trait Date { use Boundaries; use Comparison; use Converter; use Creator; use Difference; use Macro; use MagicParameter; use Modifiers; use Mutability; use ObjectInitialisation; use Options; use Rounding; use Serialization; use Test; use Timestamp; use Units; use Week; /** * Names of days of the week. * * @var array */ protected static $days = [ // @call isDayOfWeek CarbonInterface::SUNDAY => 'Sunday', // @call isDayOfWeek CarbonInterface::MONDAY => 'Monday', // @call isDayOfWeek CarbonInterface::TUESDAY => 'Tuesday', // @call isDayOfWeek CarbonInterface::WEDNESDAY => 'Wednesday', // @call isDayOfWeek CarbonInterface::THURSDAY => 'Thursday', // @call isDayOfWeek CarbonInterface::FRIDAY => 'Friday', // @call isDayOfWeek CarbonInterface::SATURDAY => 'Saturday', ]; /** * List of unit and magic methods associated as doc-comments. * * @var array */ protected static $units = [ // @call setUnit // @call addUnit 'year', // @call setUnit // @call addUnit 'month', // @call setUnit // @call addUnit 'day', // @call setUnit // @call addUnit 'hour', // @call setUnit // @call addUnit 'minute', // @call setUnit // @call addUnit 'second', // @call setUnit // @call addUnit 'milli', // @call setUnit // @call addUnit 'millisecond', // @call setUnit // @call addUnit 'micro', // @call setUnit // @call addUnit 'microsecond', ]; /** * Creates a DateTimeZone from a string, DateTimeZone or integer offset. * * @param DateTimeZone|string|int|false|null $object original value to get CarbonTimeZone from it. * @param DateTimeZone|string|int|false|null $objectDump dump of the object for error messages. * * @throws InvalidTimeZoneException * * @return CarbonTimeZone|null */ protected static function safeCreateDateTimeZone( DateTimeZone|string|int|false|null $object, DateTimeZone|string|int|false|null $objectDump = null, ): ?CarbonTimeZone { return CarbonTimeZone::instance($object, $objectDump); } /** * Get the TimeZone associated with the Carbon instance (as CarbonTimeZone). * * @link https://php.net/manual/en/datetime.gettimezone.php */ public function getTimezone(): CarbonTimeZone { return $this->transmitFactory(fn () => CarbonTimeZone::instance(parent::getTimezone())); } /** * List of minimum and maximums for each unit. */ protected static function getRangesByUnit(int $daysInMonth = 31): array { return [ // @call roundUnit 'year' => [1, 9999], // @call roundUnit 'month' => [1, static::MONTHS_PER_YEAR], // @call roundUnit 'day' => [1, $daysInMonth], // @call roundUnit 'hour' => [0, static::HOURS_PER_DAY - 1], // @call roundUnit 'minute' => [0, static::MINUTES_PER_HOUR - 1], // @call roundUnit 'second' => [0, static::SECONDS_PER_MINUTE - 1], ]; } /** * Get a copy of the instance. * * @return static */ public function copy() { return clone $this; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Clone the current instance if it's mutable. * * This method is convenient to ensure you don't mutate the initial object * but avoid to make a useless copy of it if it's already immutable. * * @return static */ public function avoidMutation(): static { if ($this instanceof DateTimeImmutable) { return $this; } return clone $this; } /** * Returns a present instance in the same timezone. * * @return static */ public function nowWithSameTz(): static { $timezone = $this->getTimezone(); return $this->getClock()?->nowAs(static::class, $timezone) ?? static::now($timezone); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|DateTimeInterface|string|null $date * * @return static */ public function carbonize($date = null) { if ($date instanceof DateInterval) { return $this->avoidMutation()->add($date); } if ($date instanceof DatePeriod || $date instanceof CarbonPeriod) { $date = $date->getStartDate(); } return $this->resolveCarbon($date); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the Carbon object. * * @throws UnknownGetterException * * @return string|int|bool|DateTimeZone|null */ public function __get(string $name): mixed { return $this->get($name); } /** * Get a part of the Carbon object. * * @throws UnknownGetterException * * @return string|int|bool|DateTimeZone */ public function get(Unit|string $name): mixed { static $localizedFormats = [ // @property string the day of week in current locale 'localeDayOfWeek' => 'dddd', // @property string the abbreviated day of week in current locale 'shortLocaleDayOfWeek' => 'ddd', // @property string the month in current locale 'localeMonth' => 'MMMM', // @property string the abbreviated month in current locale 'shortLocaleMonth' => 'MMM', ]; $name = Unit::toName($name); if (isset($localizedFormats[$name])) { return $this->isoFormat($localizedFormats[$name]); } static $formats = [ // @property int 'year' => 'Y', // @property int 'yearIso' => 'o', // @--property-read int // @--property-write Month|int // @property int 'month' => 'n', // @property int 'day' => 'j', // @property int 'hour' => 'G', // @property int 'minute' => 'i', // @property int 'second' => 's', // @property int 'micro' => 'u', // @property int 'microsecond' => 'u', // @property int 0 (for Sunday) through 6 (for Saturday) 'dayOfWeek' => 'w', // @property int 1 (for Monday) through 7 (for Sunday) 'dayOfWeekIso' => 'N', // @property int ISO-8601 week number of year, weeks starting on Monday 'weekOfYear' => 'W', // @property-read int number of days in the given month 'daysInMonth' => 't', // @property int|float|string seconds since the Unix Epoch 'timestamp' => 'U', // @property-read string "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) 'latinMeridiem' => 'a', // @property-read string "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) 'latinUpperMeridiem' => 'A', // @property string the day of week in English 'englishDayOfWeek' => 'l', // @property string the abbreviated day of week in English 'shortEnglishDayOfWeek' => 'D', // @property string the month in English 'englishMonth' => 'F', // @property string the abbreviated month in English 'shortEnglishMonth' => 'M', // @property-read string $timezoneAbbreviatedName the current timezone abbreviated name 'timezoneAbbreviatedName' => 'T', // @property-read string $tzAbbrName alias of $timezoneAbbreviatedName 'tzAbbrName' => 'T', ]; switch (true) { case isset($formats[$name]): $value = $this->rawFormat($formats[$name]); return is_numeric($value) ? (int) $value : $value; // @property-read string long name of weekday translated according to Carbon locale, in english if no translation available for current language case $name === 'dayName': return $this->getTranslatedDayName(); // @property-read string short name of weekday translated according to Carbon locale, in english if no translation available for current language case $name === 'shortDayName': return $this->getTranslatedShortDayName(); // @property-read string very short name of weekday translated according to Carbon locale, in english if no translation available for current language case $name === 'minDayName': return $this->getTranslatedMinDayName(); // @property-read string long name of month translated according to Carbon locale, in english if no translation available for current language case $name === 'monthName': return $this->getTranslatedMonthName(); // @property-read string short name of month translated according to Carbon locale, in english if no translation available for current language case $name === 'shortMonthName': return $this->getTranslatedShortMonthName(); // @property-read string lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language case $name === 'meridiem': return $this->meridiem(true); // @property-read string uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language case $name === 'upperMeridiem': return $this->meridiem(); // @property-read int current hour from 1 to 24 case $name === 'noZeroHour': return $this->hour ?: 24; // @property int case $name === 'milliseconds': // @property int case $name === 'millisecond': // @property int case $name === 'milli': return (int) floor(((int) $this->rawFormat('u')) / 1000); // @property int 1 through 53 case $name === 'week': return (int) $this->week(); // @property int 1 through 53 case $name === 'isoWeek': return (int) $this->isoWeek(); // @property int year according to week format case $name === 'weekYear': return (int) $this->weekYear(); // @property int year according to ISO week format case $name === 'isoWeekYear': return (int) $this->isoWeekYear(); // @property-read int 51 through 53 case $name === 'weeksInYear': return $this->weeksInYear(); // @property-read int 51 through 53 case $name === 'isoWeeksInYear': return $this->isoWeeksInYear(); // @property int 1 through 5 case $name === 'weekOfMonth': return (int) ceil($this->day / static::DAYS_PER_WEEK); // @property-read int 1 through 5 case $name === 'weekNumberInMonth': return (int) ceil(($this->day + $this->avoidMutation()->startOfMonth()->dayOfWeekIso - 1) / static::DAYS_PER_WEEK); // @property-read int 0 through 6 case $name === 'firstWeekDay': return (int) $this->getTranslationMessage('first_day_of_week'); // @property-read int 0 through 6 case $name === 'lastWeekDay': return $this->transmitFactory(fn () => static::weekRotate((int) $this->getTranslationMessage('first_day_of_week'), -1)); // @property int 1 through 366 case $name === 'dayOfYear': return 1 + (int) ($this->rawFormat('z')); // @property-read int 365 or 366 case $name === 'daysInYear': return static::DAYS_PER_YEAR + ($this->isLeapYear() ? 1 : 0); // @property int does a diffInYears() with default parameters case $name === 'age': return (int) $this->diffInYears(); // @property-read int the quarter of this instance, 1 - 4 case $name === 'quarter': return (int) ceil($this->month / static::MONTHS_PER_QUARTER); // @property-read int the decade of this instance // @call isSameUnit case $name === 'decade': return (int) ceil($this->year / static::YEARS_PER_DECADE); // @property-read int the century of this instance // @call isSameUnit case $name === 'century': $factor = 1; $year = $this->year; if ($year < 0) { $year = -$year; $factor = -1; } return (int) ($factor * ceil($year / static::YEARS_PER_CENTURY)); // @property-read int the millennium of this instance // @call isSameUnit case $name === 'millennium': $factor = 1; $year = $this->year; if ($year < 0) { $year = -$year; $factor = -1; } return (int) ($factor * ceil($year / static::YEARS_PER_MILLENNIUM)); // @property int the timezone offset in seconds from UTC case $name === 'offset': return $this->getOffset(); // @property int the timezone offset in minutes from UTC case $name === 'offsetMinutes': return $this->getOffset() / static::SECONDS_PER_MINUTE; // @property int the timezone offset in hours from UTC case $name === 'offsetHours': return $this->getOffset() / static::SECONDS_PER_MINUTE / static::MINUTES_PER_HOUR; // @property-read bool daylight savings time indicator, true if DST, false otherwise case $name === 'dst': return $this->rawFormat('I') === '1'; // @property-read bool checks if the timezone is local, true if local, false otherwise case $name === 'local': return $this->getOffset() === $this->avoidMutation()->setTimezone(date_default_timezone_get())->getOffset(); // @property-read bool checks if the timezone is UTC, true if UTC, false otherwise case $name === 'utc': return $this->getOffset() === 0; // @--property-write DateTimeZone|string|int $timezone the current timezone // @--property-write DateTimeZone|string|int $tz alias of $timezone // @--property-read CarbonTimeZone $timezone the current timezone // @--property-read CarbonTimeZone $tz alias of $timezone // @property CarbonTimeZone $timezone the current timezone // @property CarbonTimeZone $tz alias of $timezone case $name === 'timezone' || $name === 'tz': return $this->getTimezone(); // @property-read string $timezoneName the current timezone name // @property-read string $tzName alias of $timezoneName case $name === 'timezoneName' || $name === 'tzName': return $this->getTimezone()->getName(); // @property-read string locale of the current instance case $name === 'locale': return $this->getTranslatorLocale(); case preg_match('/^([a-z]{2,})(In|Of)([A-Z][a-z]+)$/', $name, $match): [, $firstUnit, $operator, $secondUnit] = $match; try { $start = $this->avoidMutation()->startOf($secondUnit); $value = $operator === 'Of' ? (\in_array($firstUnit, [ // Unit with indexes starting at 1 (other units start at 0) 'day', 'week', 'month', 'quarter', ], true) ? 1 : 0) + floor($start->diffInUnit($firstUnit, $this)) : round($start->diffInUnit($firstUnit, $start->avoidMutation()->add($secondUnit, 1))); return (int) $value; } catch (UnknownUnitException) { // default to macro } default: $macro = $this->getLocalMacro('get'.ucfirst($name)); if ($macro) { return $this->executeCallableWithContext($macro); } throw new UnknownGetterException($name); } } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset($name) { try { $this->__get($name); } catch (UnknownGetterException | ReflectionException) { return false; } return true; } /** * Set a part of the Carbon object * * @param string $name * @param string|int|DateTimeZone $value * * @throws UnknownSetterException|ReflectionException * * @return void */ public function __set($name, $value) { if ($this->constructedObjectId === spl_object_hash($this)) { $this->set($name, $value); return; } $this->$name = $value; } /** * Set a part of the Carbon object. * * @throws ImmutableException|UnknownSetterException * * @return $this */ public function set(Unit|array|string $name, DateTimeZone|Month|string|int|float|null $value = null): static { if ($this->isImmutable()) { throw new ImmutableException(\sprintf('%s class', static::class)); } if (\is_array($name)) { foreach ($name as $key => $value) { $this->set($key, $value); } return $this; } $name = Unit::toName($name); switch ($name) { case 'milliseconds': case 'millisecond': case 'milli': case 'microseconds': case 'microsecond': case 'micro': if (str_starts_with($name, 'milli')) { $value *= 1000; } while ($value < 0) { $this->subSecond(); $value += static::MICROSECONDS_PER_SECOND; } while ($value >= static::MICROSECONDS_PER_SECOND) { $this->addSecond(); $value -= static::MICROSECONDS_PER_SECOND; } $this->modify($this->rawFormat('H:i:s.').str_pad((string) round($value), 6, '0', STR_PAD_LEFT)); break; case 'year': case 'month': case 'day': case 'hour': case 'minute': case 'second': [$year, $month, $day, $hour, $minute, $second] = array_map('intval', explode('-', $this->rawFormat('Y-n-j-G-i-s'))); $$name = self::monthToInt($value, $name); $this->setDateTime($year, $month, $day, $hour, $minute, $second); break; case 'week': $this->week($value); break; case 'isoWeek': $this->isoWeek($value); break; case 'weekYear': $this->weekYear($value); break; case 'isoWeekYear': $this->isoWeekYear($value); break; case 'dayOfYear': $this->addDays($value - $this->dayOfYear); break; case 'dayOfWeek': $this->addDays($value - $this->dayOfWeek); break; case 'dayOfWeekIso': $this->addDays($value - $this->dayOfWeekIso); break; case 'timestamp': $this->setTimestamp($value); break; case 'offset': $this->setTimezone(static::safeCreateDateTimeZone($value / static::SECONDS_PER_MINUTE / static::MINUTES_PER_HOUR)); break; case 'offsetMinutes': $this->setTimezone(static::safeCreateDateTimeZone($value / static::MINUTES_PER_HOUR)); break; case 'offsetHours': $this->setTimezone(static::safeCreateDateTimeZone($value)); break; case 'timezone': case 'tz': $this->setTimezone($value); break; default: if (preg_match('/^([a-z]{2,})Of([A-Z][a-z]+)$/', $name, $match)) { [, $firstUnit, $secondUnit] = $match; try { $start = $this->avoidMutation()->startOf($secondUnit); $currentValue = (\in_array($firstUnit, [ // Unit with indexes starting at 1 (other units start at 0) 'day', 'week', 'month', 'quarter', ], true) ? 1 : 0) + (int) floor($start->diffInUnit($firstUnit, $this)); // We check $value a posteriori to give precedence to UnknownUnitException if (!\is_int($value)) { throw new UnitException("->$name expects integer value"); } $this->addUnit($firstUnit, $value - $currentValue); break; } catch (UnknownUnitException) { // default to macro } } $macro = $this->getLocalMacro('set'.ucfirst($name)); if ($macro) { $this->executeCallableWithContext($macro, $value); break; } if ($this->isLocalStrictModeEnabled()) { throw new UnknownSetterException($name); } $this->$name = $value; } return $this; } /** * Get the translation of the current week day name (with context for languages with multiple forms). * * @param string|null $context whole format string * @param string $keySuffix "", "_short" or "_min" * @param string|null $defaultValue default value if translation missing */ public function getTranslatedDayName( ?string $context = null, string $keySuffix = '', ?string $defaultValue = null, ): string { return $this->getTranslatedFormByRegExp('weekdays', $keySuffix, $context, $this->dayOfWeek, $defaultValue ?: $this->englishDayOfWeek); } /** * Get the translation of the current short week day name (with context for languages with multiple forms). * * @param string|null $context whole format string */ public function getTranslatedShortDayName(?string $context = null): string { return $this->getTranslatedDayName($context, '_short', $this->shortEnglishDayOfWeek); } /** * Get the translation of the current abbreviated week day name (with context for languages with multiple forms). * * @param string|null $context whole format string */ public function getTranslatedMinDayName(?string $context = null): string { return $this->getTranslatedDayName($context, '_min', $this->shortEnglishDayOfWeek); } /** * Get the translation of the current month day name (with context for languages with multiple forms). * * @param string|null $context whole format string * @param string $keySuffix "" or "_short" * @param string|null $defaultValue default value if translation missing */ public function getTranslatedMonthName( ?string $context = null, string $keySuffix = '', ?string $defaultValue = null, ): string { return $this->getTranslatedFormByRegExp('months', $keySuffix, $context, $this->month - 1, $defaultValue ?: $this->englishMonth); } /** * Get the translation of the current short month day name (with context for languages with multiple forms). * * @param string|null $context whole format string */ public function getTranslatedShortMonthName(?string $context = null): string { return $this->getTranslatedMonthName($context, '_short', $this->shortEnglishMonth); } /** * Get/set the day of year. * * @template T of int|null * * @param int|null $value new value for day of year if using as setter. * * @psalm-param T $value * * @return static|int * * @psalm-return (T is int ? static : int) */ public function dayOfYear(?int $value = null): static|int { $dayOfYear = $this->dayOfYear; return $value === null ? $dayOfYear : $this->addDays($value - $dayOfYear); } /** * Get/set the weekday from 0 (Sunday) to 6 (Saturday). * * @param WeekDay|int|null $value new value for weekday if using as setter. */ public function weekday(WeekDay|int|null $value = null): static|int { if ($value === null) { return $this->dayOfWeek; } $firstDay = (int) ($this->getTranslationMessage('first_day_of_week') ?? 0); $dayOfWeek = ($this->dayOfWeek + 7 - $firstDay) % 7; return $this->addDays(((WeekDay::int($value) + 7 - $firstDay) % 7) - $dayOfWeek); } /** * Get/set the ISO weekday from 1 (Monday) to 7 (Sunday). * * @param WeekDay|int|null $value new value for weekday if using as setter. */ public function isoWeekday(WeekDay|int|null $value = null): static|int { $dayOfWeekIso = $this->dayOfWeekIso; return $value === null ? $dayOfWeekIso : $this->addDays(WeekDay::int($value) - $dayOfWeekIso); } /** * Return the number of days since the start of the week (using the current locale or the first parameter * if explicitly given). * * @param WeekDay|int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week, * if not provided, start of week is inferred from the locale * (Sunday for en_US, Monday for de_DE, etc.) */ public function getDaysFromStartOfWeek(WeekDay|int|null $weekStartsAt = null): int { $firstDay = (int) (WeekDay::int($weekStartsAt) ?? $this->getTranslationMessage('first_day_of_week') ?? 0); return ($this->dayOfWeek + 7 - $firstDay) % 7; } /** * Set the day (keeping the current time) to the start of the week + the number of days passed as the first * parameter. First day of week is driven by the locale unless explicitly set with the second parameter. * * @param int $numberOfDays number of days to add after the start of the current week * @param WeekDay|int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week, * if not provided, start of week is inferred from the locale * (Sunday for en_US, Monday for de_DE, etc.) */ public function setDaysFromStartOfWeek(int $numberOfDays, WeekDay|int|null $weekStartsAt = null): static { return $this->addDays($numberOfDays - $this->getDaysFromStartOfWeek(WeekDay::int($weekStartsAt))); } /** * Set any unit to a new value without overflowing current other unit given. * * @param string $valueUnit unit name to modify * @param int $value new value for the input unit * @param string $overflowUnit unit name to not overflow */ public function setUnitNoOverflow(string $valueUnit, int $value, string $overflowUnit): static { try { $start = $this->avoidMutation()->startOf($overflowUnit); $end = $this->avoidMutation()->endOf($overflowUnit); /** @var static $date */ $date = $this->$valueUnit($value); if ($date < $start) { return $date->mutateIfMutable($start); } if ($date > $end) { return $date->mutateIfMutable($end); } return $date; } catch (BadMethodCallException | ReflectionException $exception) { throw new UnknownUnitException($valueUnit, 0, $exception); } } /** * Add any unit to a new value without overflowing current other unit given. * * @param string $valueUnit unit name to modify * @param int $value amount to add to the input unit * @param string $overflowUnit unit name to not overflow */ public function addUnitNoOverflow(string $valueUnit, int $value, string $overflowUnit): static { return $this->setUnitNoOverflow($valueUnit, $this->$valueUnit + $value, $overflowUnit); } /** * Subtract any unit to a new value without overflowing current other unit given. * * @param string $valueUnit unit name to modify * @param int $value amount to subtract to the input unit * @param string $overflowUnit unit name to not overflow */ public function subUnitNoOverflow(string $valueUnit, int $value, string $overflowUnit): static { return $this->setUnitNoOverflow($valueUnit, $this->$valueUnit - $value, $overflowUnit); } /** * Returns the minutes offset to UTC if no arguments passed, else set the timezone with given minutes shift passed. */ public function utcOffset(?int $minuteOffset = null): static|int { if ($minuteOffset === null) { return $this->offsetMinutes; } return $this->setTimezone(CarbonTimeZone::createFromMinuteOffset($minuteOffset)); } /** * Set the date with gregorian year, month and day numbers. * * @see https://php.net/manual/en/datetime.setdate.php */ public function setDate(int $year, int $month, int $day): static { return parent::setDate($year, $month, $day); } /** * Set a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates. * * @see https://php.net/manual/en/datetime.setisodate.php */ public function setISODate(int $year, int $week, int $day = 1): static { return parent::setISODate($year, $week, $day); } /** * Set the date and time all together. */ public function setDateTime( int $year, int $month, int $day, int $hour, int $minute, int $second = 0, int $microseconds = 0, ): static { return $this->setDate($year, $month, $day)->setTime($hour, $minute, $second, $microseconds); } /** * Resets the current time of the DateTime object to a different time. * * @see https://php.net/manual/en/datetime.settime.php */ public function setTime(int $hour, int $minute, int $second = 0, int $microseconds = 0): static { return parent::setTime($hour, $minute, $second, $microseconds); } /** * Set the instance's timestamp. * * Timestamp input can be given as int, float or a string containing one or more numbers. */ public function setTimestamp(float|int|string $timestamp): static { [$seconds, $microseconds] = self::getIntegerAndDecimalParts($timestamp); return parent::setTimestamp((int) $seconds)->setMicroseconds((int) $microseconds); } /** * Set the time by time string. */ public function setTimeFromTimeString(string $time): static { if (!str_contains($time, ':')) { $time .= ':0'; } return $this->modify($time); } /** * @alias setTimezone */ public function timezone(DateTimeZone|string|int $value): static { return $this->setTimezone($value); } /** * Set the timezone or returns the timezone name if no arguments passed. * * @return ($value is null ? string : static) */ public function tz(DateTimeZone|string|int|null $value = null): static|string { if ($value === null) { return $this->tzName; } return $this->setTimezone($value); } /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timeZone): static { return parent::setTimezone(static::safeCreateDateTimeZone($timeZone)); } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string $value): static { $dateTimeString = $this->format('Y-m-d H:i:s.u'); return $this ->setTimezone($value) ->modify($dateTimeString); } /** * Set the instance's timezone to UTC. */ public function utc(): static { return $this->setTimezone('UTC'); } /** * Set the year, month, and date for this instance to that of the passed instance. */ public function setDateFrom(DateTimeInterface|string $date): static { $date = $this->resolveCarbon($date); return $this->setDate($date->year, $date->month, $date->day); } /** * Set the hour, minute, second and microseconds for this instance to that of the passed instance. */ public function setTimeFrom(DateTimeInterface|string $date): static { $date = $this->resolveCarbon($date); return $this->setTime($date->hour, $date->minute, $date->second, $date->microsecond); } /** * Set the date and time for this instance to that of the passed instance. */ public function setDateTimeFrom(DateTimeInterface|string $date): static { $date = $this->resolveCarbon($date); return $this->modify($date->rawFormat('Y-m-d H:i:s.u')); } /** * Get the days of the week. */ public static function getDays(): array { return static::$days; } /////////////////////////////////////////////////////////////////// /////////////////////// WEEK SPECIAL DAYS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Get the first day of week. * * @return int */ public static function getWeekStartsAt(?string $locale = null): int { return (int) static::getTranslationMessageWith( $locale ? Translator::get($locale) : static::getTranslator(), 'first_day_of_week', ); } /** * Get the last day of week. * * @param string $locale local to consider the last day of week. * * @return int */ public static function getWeekEndsAt(?string $locale = null): int { return static::weekRotate(static::getWeekStartsAt($locale), -1); } /** * Get weekend days */ public static function getWeekendDays(): array { return FactoryImmutable::getInstance()->getWeekendDays(); } /** * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. * You should rather consider week-end is always saturday and sunday, and if you have some custom * week-end days to handle, give to those days an other name and create a macro for them: * * ``` * Carbon::macro('isDayOff', function ($date) { * return $date->isSunday() || $date->isMonday(); * }); * Carbon::macro('isNotDayOff', function ($date) { * return !$date->isDayOff(); * }); * if ($someDate->isDayOff()) ... * if ($someDate->isNotDayOff()) ... * // Add 5 not-off days * $count = 5; * while ($someDate->isDayOff() || ($count-- > 0)) { * $someDate->addDay(); * } * ``` * * Set weekend days */ public static function setWeekendDays(array $days): void { FactoryImmutable::getDefaultInstance()->setWeekendDays($days); } /** * Determine if a time string will produce a relative date. * * @return bool true if time match a relative date, false if absolute or invalid time string */ public static function hasRelativeKeywords(?string $time): bool { if (!$time || strtotime($time) === false) { return false; } $date1 = new DateTime('2000-01-01T00:00:00Z'); $date1->modify($time); $date2 = new DateTime('2001-12-25T00:00:00Z'); $date2->modify($time); return $date1 != $date2; } /////////////////////////////////////////////////////////////////// /////////////////////// STRING FORMATTING ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Returns list of locale formats for ISO formatting. * * @param string|null $locale current locale used if null */ public function getIsoFormats(?string $locale = null): array { return [ 'LT' => $this->getTranslationMessage('formats.LT', $locale), 'LTS' => $this->getTranslationMessage('formats.LTS', $locale), 'L' => $this->getTranslationMessage('formats.L', $locale), 'LL' => $this->getTranslationMessage('formats.LL', $locale), 'LLL' => $this->getTranslationMessage('formats.LLL', $locale), 'LLLL' => $this->getTranslationMessage('formats.LLLL', $locale), 'l' => $this->getTranslationMessage('formats.l', $locale), 'll' => $this->getTranslationMessage('formats.ll', $locale), 'lll' => $this->getTranslationMessage('formats.lll', $locale), 'llll' => $this->getTranslationMessage('formats.llll', $locale), ]; } /** * Returns list of calendar formats for ISO formatting. * * @param string|null $locale current locale used if null */ public function getCalendarFormats(?string $locale = null): array { return [ 'sameDay' => $this->getTranslationMessage('calendar.sameDay', $locale, '[Today at] LT'), 'nextDay' => $this->getTranslationMessage('calendar.nextDay', $locale, '[Tomorrow at] LT'), 'nextWeek' => $this->getTranslationMessage('calendar.nextWeek', $locale, 'dddd [at] LT'), 'lastDay' => $this->getTranslationMessage('calendar.lastDay', $locale, '[Yesterday at] LT'), 'lastWeek' => $this->getTranslationMessage('calendar.lastWeek', $locale, '[Last] dddd [at] LT'), 'sameElse' => $this->getTranslationMessage('calendar.sameElse', $locale, 'L'), ]; } /** * Returns list of locale units for ISO formatting. */ public static function getIsoUnits(): array { static $units = null; $units ??= [ 'OD' => ['getAltNumber', ['day']], 'OM' => ['getAltNumber', ['month']], 'OY' => ['getAltNumber', ['year']], 'OH' => ['getAltNumber', ['hour']], 'Oh' => ['getAltNumber', ['h']], 'Om' => ['getAltNumber', ['minute']], 'Os' => ['getAltNumber', ['second']], 'D' => 'day', 'DD' => ['rawFormat', ['d']], 'Do' => ['ordinal', ['day', 'D']], 'd' => 'dayOfWeek', 'dd' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedMinDayName( $originalFormat, ), 'ddd' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedShortDayName( $originalFormat, ), 'dddd' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedDayName( $originalFormat, ), 'DDD' => 'dayOfYear', 'DDDD' => ['getPaddedUnit', ['dayOfYear', 3]], 'DDDo' => ['ordinal', ['dayOfYear', 'DDD']], 'e' => ['weekday', []], 'E' => 'dayOfWeekIso', 'H' => ['rawFormat', ['G']], 'HH' => ['rawFormat', ['H']], 'h' => ['rawFormat', ['g']], 'hh' => ['rawFormat', ['h']], 'k' => 'noZeroHour', 'kk' => ['getPaddedUnit', ['noZeroHour']], 'hmm' => ['rawFormat', ['gi']], 'hmmss' => ['rawFormat', ['gis']], 'Hmm' => ['rawFormat', ['Gi']], 'Hmmss' => ['rawFormat', ['Gis']], 'm' => 'minute', 'mm' => ['rawFormat', ['i']], 'a' => 'meridiem', 'A' => 'upperMeridiem', 's' => 'second', 'ss' => ['getPaddedUnit', ['second']], 'S' => static fn (CarbonInterface $date) => (string) floor($date->micro / 100000), 'SS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 10000, 2), 'SSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 1000, 3), 'SSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 100, 4), 'SSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 10, 5), 'SSSSSS' => ['getPaddedUnit', ['micro', 6]], 'SSSSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro * 10, 7), 'SSSSSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro * 100, 8), 'SSSSSSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro * 1000, 9), 'M' => 'month', 'MM' => ['rawFormat', ['m']], 'MMM' => static function (CarbonInterface $date, $originalFormat = null) { $month = $date->getTranslatedShortMonthName($originalFormat); $suffix = $date->getTranslationMessage('mmm_suffix'); if ($suffix && $month !== $date->monthName) { $month .= $suffix; } return $month; }, 'MMMM' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedMonthName( $originalFormat, ), 'Mo' => ['ordinal', ['month', 'M']], 'Q' => 'quarter', 'Qo' => ['ordinal', ['quarter', 'M']], 'G' => 'isoWeekYear', 'GG' => ['getPaddedUnit', ['isoWeekYear']], 'GGG' => ['getPaddedUnit', ['isoWeekYear', 3]], 'GGGG' => ['getPaddedUnit', ['isoWeekYear', 4]], 'GGGGG' => ['getPaddedUnit', ['isoWeekYear', 5]], 'g' => 'weekYear', 'gg' => ['getPaddedUnit', ['weekYear']], 'ggg' => ['getPaddedUnit', ['weekYear', 3]], 'gggg' => ['getPaddedUnit', ['weekYear', 4]], 'ggggg' => ['getPaddedUnit', ['weekYear', 5]], 'W' => 'isoWeek', 'WW' => ['getPaddedUnit', ['isoWeek']], 'Wo' => ['ordinal', ['isoWeek', 'W']], 'w' => 'week', 'ww' => ['getPaddedUnit', ['week']], 'wo' => ['ordinal', ['week', 'w']], 'x' => ['valueOf', []], 'X' => 'timestamp', 'Y' => 'year', 'YY' => ['rawFormat', ['y']], 'YYYY' => ['getPaddedUnit', ['year', 4]], 'YYYYY' => ['getPaddedUnit', ['year', 5]], 'YYYYYY' => static fn (CarbonInterface $date) => ($date->year < 0 ? '' : '+'). $date->getPaddedUnit('year', 6), 'z' => ['rawFormat', ['T']], 'zz' => 'tzName', 'Z' => ['getOffsetString', []], 'ZZ' => ['getOffsetString', ['']], ]; return $units; } /** * Returns a unit of the instance padded with 0 by default or any other string if specified. * * @param string $unit Carbon unit name * @param int $length Length of the output (2 by default) * @param string $padString String to use for padding ("0" by default) * @param int $padType Side(s) to pad (STR_PAD_LEFT by default) */ public function getPaddedUnit($unit, $length = 2, $padString = '0', $padType = STR_PAD_LEFT): string { return ($this->$unit < 0 ? '-' : '').str_pad((string) abs($this->$unit), $length, $padString, $padType); } /** * Return a property with its ordinal. */ public function ordinal(string $key, ?string $period = null): string { $number = $this->$key; $result = $this->translate('ordinal', [ ':number' => $number, ':period' => (string) $period, ]); return (string) ($result === 'ordinal' ? $number : $result); } /** * Return the meridiem of the current time in the current locale. * * @param bool $isLower if true, returns lowercase variant if available in the current locale. */ public function meridiem(bool $isLower = false): string { $hour = $this->hour; $index = $hour < static::HOURS_PER_DAY / 2 ? 0 : 1; if ($isLower) { $key = 'meridiem.'.($index + 2); $result = $this->translate($key); if ($result !== $key) { return $result; } } $key = "meridiem.$index"; $result = $this->translate($key); if ($result === $key) { $result = $this->translate('meridiem', [ ':hour' => $this->hour, ':minute' => $this->minute, ':isLower' => $isLower, ]); if ($result === 'meridiem') { return $isLower ? $this->latinMeridiem : $this->latinUpperMeridiem; } } elseif ($isLower) { $result = mb_strtolower($result); } return $result; } /** * Returns the alternative number for a given date property if available in the current locale. * * @param string $key date property */ public function getAltNumber(string $key): string { return $this->translateNumber((int) (\strlen($key) > 1 ? $this->$key : $this->rawFormat($key))); } /** * Format in the current language using ISO replacement patterns. * * @param string|null $originalFormat provide context if a chunk has been passed alone */ public function isoFormat(string $format, ?string $originalFormat = null): string { $result = ''; $length = mb_strlen($format); $originalFormat ??= $format; $inEscaped = false; $formats = null; $units = null; for ($i = 0; $i < $length; $i++) { $char = mb_substr($format, $i, 1); if ($char === '\\') { $result .= mb_substr($format, ++$i, 1); continue; } if ($char === '[' && !$inEscaped) { $inEscaped = true; continue; } if ($char === ']' && $inEscaped) { $inEscaped = false; continue; } if ($inEscaped) { $result .= $char; continue; } $input = mb_substr($format, $i); if (preg_match('/^(LTS|LT|l{1,4}|L{1,4})/', $input, $match)) { if ($formats === null) { $formats = $this->getIsoFormats(); } $code = $match[0]; $sequence = $formats[$code] ?? preg_replace_callback( '/MMMM|MM|DD|dddd/', static fn ($code) => mb_substr($code[0], 1), $formats[strtoupper($code)] ?? '', ); $rest = mb_substr($format, $i + mb_strlen($code)); $format = mb_substr($format, 0, $i).$sequence.$rest; $length = mb_strlen($format); $input = $sequence.$rest; } if (preg_match('/^'.CarbonInterface::ISO_FORMAT_REGEXP.'/', $input, $match)) { $code = $match[0]; if ($units === null) { $units = static::getIsoUnits(); } $sequence = $units[$code] ?? ''; if ($sequence instanceof Closure) { $sequence = $sequence($this, $originalFormat); } elseif (\is_array($sequence)) { try { $sequence = $this->{$sequence[0]}(...$sequence[1]); } catch (ReflectionException | InvalidArgumentException | BadMethodCallException) { $sequence = ''; } } elseif (\is_string($sequence)) { $sequence = $this->$sequence ?? $code; } $format = mb_substr($format, 0, $i).$sequence.mb_substr($format, $i + mb_strlen($code)); $i += mb_strlen((string) $sequence) - 1; $length = mb_strlen($format); $char = $sequence; } $result .= $char; } return $result; } /** * List of replacements from date() format to isoFormat(). */ public static function getFormatsToIsoReplacements(): array { static $replacements = null; $replacements ??= [ 'd' => true, 'D' => 'ddd', 'j' => true, 'l' => 'dddd', 'N' => true, 'S' => static fn ($date) => str_replace((string) $date->rawFormat('j'), '', $date->isoFormat('Do')), 'w' => true, 'z' => true, 'W' => true, 'F' => 'MMMM', 'm' => true, 'M' => 'MMM', 'n' => true, 't' => true, 'L' => true, 'o' => true, 'Y' => true, 'y' => true, 'a' => 'a', 'A' => 'A', 'B' => true, 'g' => true, 'G' => true, 'h' => true, 'H' => true, 'i' => true, 's' => true, 'u' => true, 'v' => true, 'E' => true, 'I' => true, 'O' => true, 'P' => true, 'Z' => true, 'c' => true, 'r' => true, 'U' => true, 'T' => true, ]; return $replacements; } /** * Format as ->format() do (using date replacements patterns from https://php.net/manual/en/function.date.php) * but translate words whenever possible (months, day names, etc.) using the current locale. */ public function translatedFormat(string $format): string { $replacements = static::getFormatsToIsoReplacements(); $context = ''; $isoFormat = ''; $length = mb_strlen($format); for ($i = 0; $i < $length; $i++) { $char = mb_substr($format, $i, 1); if ($char === '\\') { $replacement = mb_substr($format, $i, 2); $isoFormat .= $replacement; $i++; continue; } if (!isset($replacements[$char])) { $replacement = preg_match('/^[A-Za-z]$/', $char) ? "\\$char" : $char; $isoFormat .= $replacement; $context .= $replacement; continue; } $replacement = $replacements[$char]; if ($replacement === true) { static $contextReplacements = null; if ($contextReplacements === null) { $contextReplacements = [ 'm' => 'MM', 'd' => 'DD', 't' => 'D', 'j' => 'D', 'N' => 'e', 'w' => 'e', 'n' => 'M', 'o' => 'YYYY', 'Y' => 'YYYY', 'y' => 'YY', 'g' => 'h', 'G' => 'H', 'h' => 'hh', 'H' => 'HH', 'i' => 'mm', 's' => 'ss', ]; } $isoFormat .= '['.$this->rawFormat($char).']'; $context .= $contextReplacements[$char] ?? ' '; continue; } if ($replacement instanceof Closure) { $replacement = '['.$replacement($this).']'; $isoFormat .= $replacement; $context .= $replacement; continue; } $isoFormat .= $replacement; $context .= $replacement; } return $this->isoFormat($isoFormat, $context); } /** * Returns the offset hour and minute formatted with +/- and a given separator (":" by default). * For example, if the time zone is 9 hours 30 minutes, you'll get "+09:30", with "@@" as first * argument, "+09@@30", with "" as first argument, "+0930". Negative offset will return something * like "-12:00". * * @param string $separator string to place between hours and minutes (":" by default) */ public function getOffsetString(string $separator = ':'): string { $second = $this->getOffset(); $symbol = $second < 0 ? '-' : '+'; $minute = abs($second) / static::SECONDS_PER_MINUTE; $hour = self::floorZeroPad($minute / static::MINUTES_PER_HOUR, 2); $minute = self::floorZeroPad(((int) $minute) % static::MINUTES_PER_HOUR, 2); return "$symbol$hour$separator$minute"; } /** * Dynamically handle calls to the class. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadMethodCallException */ public static function __callStatic(string $method, array $parameters): mixed { if (!static::hasMacro($method)) { foreach (static::getGenericMacros() as $callback) { try { return static::executeStaticCallable($callback, $method, ...$parameters); } catch (BadMethodCallException) { continue; } } if (static::isStrictModeEnabled()) { throw new UnknownMethodException(\sprintf('%s::%s', static::class, $method)); } return null; } return static::executeStaticCallable(static::getMacro($method), ...$parameters); } /** * Set specified unit to new given value. * * @param string $unit year, month, day, hour, minute, second or microsecond * @param Month|int $value new value for given unit */ public function setUnit(string $unit, Month|int|float|null $value = null): static { if (\is_float($value)) { $int = (int) $value; if ((float) $int !== $value) { throw new InvalidArgumentException( "$unit cannot be changed to float value $value, integer expected", ); } $value = $int; } $unit = static::singularUnit($unit); $value = self::monthToInt($value, $unit); $dateUnits = ['year', 'month', 'day']; if (\in_array($unit, $dateUnits)) { return $this->setDate(...array_map( fn ($name) => (int) ($name === $unit ? $value : $this->$name), $dateUnits, )); } $units = ['hour', 'minute', 'second', 'micro']; if ($unit === 'millisecond' || $unit === 'milli') { $value *= 1000; $unit = 'micro'; } elseif ($unit === 'microsecond') { $unit = 'micro'; } return $this->setTime(...array_map( fn ($name) => (int) ($name === $unit ? $value : $this->$name), $units, )); } /** * Returns standardized singular of a given singular/plural unit name (in English). */ public static function singularUnit(string $unit): string { $unit = rtrim(mb_strtolower($unit), 's'); return match ($unit) { 'centurie' => 'century', 'millennia' => 'millennium', default => $unit, }; } /** * Returns standardized plural of a given singular/plural unit name (in English). */ public static function pluralUnit(string $unit): string { $unit = rtrim(strtolower($unit), 's'); return match ($unit) { 'century' => 'centuries', 'millennium', 'millennia' => 'millennia', default => "{$unit}s", }; } public static function sleep(int|float $seconds): void { if (static::hasTestNow()) { static::setTestNow(static::getTestNow()->avoidMutation()->addSeconds($seconds)); return; } (new NativeClock('UTC'))->sleep($seconds); } /** * Dynamically handle calls to the class. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws UnknownMethodException|BadMethodCallException|ReflectionException|Throwable */ public function __call(string $method, array $parameters): mixed { $unit = rtrim($method, 's'); return $this->callDiffAlias($unit, $parameters) ?? $this->callHumanDiffAlias($unit, $parameters) ?? $this->callRoundMethod($unit, $parameters) ?? $this->callIsMethod($unit, $parameters) ?? $this->callModifierMethod($unit, $parameters) ?? $this->callPeriodMethod($method, $parameters) ?? $this->callGetOrSetMethod($method, $parameters) ?? $this->callMacroMethod($method, $parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. */ protected function resolveCarbon(DateTimeInterface|string|null $date): self { if (!$date) { return $this->nowWithSameTz(); } if (\is_string($date)) { return $this->transmitFactory(fn () => static::parse($date, $this->getTimezone())); } return $date instanceof self ? $date : $this->transmitFactory(static fn () => static::instance($date)); } protected static function weekRotate(int $day, int $rotation): int { return (static::DAYS_PER_WEEK + $rotation % static::DAYS_PER_WEEK + $day) % static::DAYS_PER_WEEK; } protected function executeCallable(callable $macro, ...$parameters) { if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return \call_user_func_array($boundMacro ?: $macro, $parameters); } return \call_user_func_array($macro, $parameters); } protected function executeCallableWithContext(callable $macro, ...$parameters) { return static::bindMacroContext($this, function () use (&$macro, &$parameters) { return $this->executeCallable($macro, ...$parameters); }); } protected function getAllGenericMacros(): Generator { yield from $this->localGenericMacros ?? []; yield from $this->transmitFactory(static fn () => static::getGenericMacros()); } protected static function getGenericMacros(): Generator { foreach ((FactoryImmutable::getInstance()->getSettings()['genericMacros'] ?? []) as $list) { foreach ($list as $macro) { yield $macro; } } } protected static function executeStaticCallable(callable $macro, ...$parameters) { return static::bindMacroContext(null, function () use (&$macro, &$parameters) { if ($macro instanceof Closure) { $boundMacro = @Closure::bind($macro, null, static::class); return \call_user_func_array($boundMacro ?: $macro, $parameters); } return \call_user_func_array($macro, $parameters); }); } protected function getTranslatedFormByRegExp($baseKey, $keySuffix, $context, $subKey, $defaultValue) { $key = $baseKey.$keySuffix; $standaloneKey = $key.'_standalone'; $baseTranslation = $this->getTranslationMessage($key); if ($baseTranslation instanceof Closure) { return $baseTranslation($this, $context, $subKey) ?: $defaultValue; } if ( $this->getTranslationMessage("$standaloneKey.$subKey") && (!$context || (($regExp = $this->getTranslationMessage($baseKey.'_regexp')) && !preg_match($regExp, $context))) ) { $key = $standaloneKey; } return $this->getTranslationMessage("$key.$subKey", null, $defaultValue); } private function callGetOrSetMethod(string $method, array $parameters): mixed { if (preg_match('/^([a-z]{2,})(In|Of)([A-Z][a-z]+)$/', $method)) { $localStrictModeEnabled = $this->localStrictModeEnabled; $this->localStrictModeEnabled = true; try { return $this->callGetOrSet($method, $parameters[0] ?? null); } catch (UnknownGetterException|UnknownSetterException|ImmutableException) { // continue to macro } finally { $this->localStrictModeEnabled = $localStrictModeEnabled; } } return null; } private function callGetOrSet(string $name, mixed $value): mixed { if ($value !== null) { if (\is_string($value) || \is_int($value) || \is_float($value) || $value instanceof DateTimeZone || $value instanceof Month) { return $this->set($name, $value); } return null; } return $this->get($name); } private function getUTCUnit(string $unit): ?string { if (str_starts_with($unit, 'Real')) { return substr($unit, 4); } if (str_starts_with($unit, 'UTC')) { return substr($unit, 3); } return null; } private function callDiffAlias(string $method, array $parameters): mixed { if (preg_match('/^(diff|floatDiff)In(Real|UTC|Utc)?(.+)$/', $method, $match)) { $mode = strtoupper($match[2] ?? ''); $betterMethod = $match[1] === 'floatDiff' ? str_replace('floatDiff', 'diff', $method) : null; if ($mode === 'REAL') { $mode = 'UTC'; $betterMethod = str_replace($match[2], 'UTC', $betterMethod ?? $method); } if ($betterMethod) { @trigger_error( "Use the method $betterMethod instead to make it more explicit about what it does.\n". 'On next major version, "float" prefix will be removed (as all diff are now returning floating numbers)'. ' and "Real" methods will be removed in favor of "UTC" because what it actually does is to convert both'. ' dates to UTC timezone before comparison, while by default it does it only if both dates don\'t have'. ' exactly the same timezone (Note: 2 timezones with the same offset but different names are considered'. " different as it's not safe to assume they will always have the same offset).", \E_USER_DEPRECATED, ); } $unit = self::pluralUnit($match[3]); $diffMethod = 'diffIn'.ucfirst($unit); if (\in_array($unit, ['days', 'weeks', 'months', 'quarters', 'years'])) { $parameters['utc'] = ($mode === 'UTC'); } if (method_exists($this, $diffMethod)) { return $this->$diffMethod(...$parameters); } } return null; } private function callHumanDiffAlias(string $method, array $parameters): ?string { $diffSizes = [ // @mode diffForHumans 'short' => true, // @mode diffForHumans 'long' => false, ]; $diffSyntaxModes = [ // @call diffForHumans 'Absolute' => CarbonInterface::DIFF_ABSOLUTE, // @call diffForHumans 'Relative' => CarbonInterface::DIFF_RELATIVE_AUTO, // @call diffForHumans 'RelativeToNow' => CarbonInterface::DIFF_RELATIVE_TO_NOW, // @call diffForHumans 'RelativeToOther' => CarbonInterface::DIFF_RELATIVE_TO_OTHER, ]; $sizePattern = implode('|', array_keys($diffSizes)); $syntaxPattern = implode('|', array_keys($diffSyntaxModes)); if (preg_match("/^(?<size>$sizePattern)(?<syntax>$syntaxPattern)DiffForHuman$/", $method, $match)) { $dates = array_filter($parameters, function ($parameter) { return $parameter instanceof DateTimeInterface; }); $other = null; if (\count($dates)) { $key = key($dates); $other = current($dates); array_splice($parameters, $key, 1); } return $this->diffForHumans($other, $diffSyntaxModes[$match['syntax']], $diffSizes[$match['size']], ...$parameters); } return null; } private function callIsMethod(string $unit, array $parameters): ?bool { if (!str_starts_with($unit, 'is')) { return null; } $word = substr($unit, 2); if (\in_array($word, static::$days, true)) { return $this->isDayOfWeek($word); } return match ($word) { // @call is Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) 'Utc', 'UTC' => $this->utc, // @call is Check if the current instance has non-UTC timezone. 'Local' => $this->local, // @call is Check if the current instance is a valid date. 'Valid' => $this->year !== 0, // @call is Check if the current instance is in a daylight saving time. 'DST' => $this->dst, default => $this->callComparatorMethod($word, $parameters), }; } private function callComparatorMethod(string $unit, array $parameters): ?bool { $start = substr($unit, 0, 4); $factor = -1; if ($start === 'Last') { $start = 'Next'; $factor = 1; } if ($start === 'Next') { $lowerUnit = strtolower(substr($unit, 4)); if (static::isModifiableUnit($lowerUnit)) { return $this->avoidMutation()->addUnit($lowerUnit, $factor, false)->isSameUnit($lowerUnit, ...($parameters ?: ['now'])); } } if ($start === 'Same') { try { return $this->isSameUnit(strtolower(substr($unit, 4)), ...$parameters); } catch (BadComparisonUnitException) { // Try next } } if (str_starts_with($unit, 'Current')) { try { return $this->isCurrentUnit(strtolower(substr($unit, 7))); } catch (BadComparisonUnitException | BadMethodCallException) { // Try next } } return null; } private function callModifierMethod(string $unit, array $parameters): ?static { $action = substr($unit, 0, 3); $overflow = null; if ($action === 'set') { $unit = strtolower(substr($unit, 3)); } if (\in_array($unit, static::$units, true)) { return $this->setUnit($unit, ...$parameters); } if ($action === 'add' || $action === 'sub') { $unit = substr($unit, 3); $utcUnit = $this->getUTCUnit($unit); if ($utcUnit) { $unit = static::singularUnit($utcUnit); return $this->{"{$action}UTCUnit"}($unit, ...$parameters); } if (preg_match('/^(Month|Quarter|Year|Decade|Century|Centurie|Millennium|Millennia)s?(No|With|Without|WithNo)Overflow$/', $unit, $match)) { $unit = $match[1]; $overflow = $match[2] === 'With'; } $unit = static::singularUnit($unit); } if (static::isModifiableUnit($unit)) { return $this->{"{$action}Unit"}($unit, $this->getMagicParameter($parameters, 0, 'value', 1), $overflow); } return null; } private function callPeriodMethod(string $method, array $parameters): ?CarbonPeriod { if (str_ends_with($method, 'Until')) { try { $unit = static::singularUnit(substr($method, 0, -5)); return $this->range( $this->getMagicParameter($parameters, 0, 'endDate', $this), $this->getMagicParameter($parameters, 1, 'factor', 1), $unit ); } catch (InvalidArgumentException) { // Try macros } } return null; } private function callMacroMethod(string $method, array $parameters): mixed { return static::bindMacroContext($this, function () use (&$method, &$parameters) { $macro = $this->getLocalMacro($method); if (!$macro) { foreach ($this->getAllGenericMacros() as $callback) { try { return $this->executeCallable($callback, $method, ...$parameters); } catch (BadMethodCallException) { continue; } } if ($this->isLocalStrictModeEnabled()) { throw new UnknownMethodException($method); } return null; } return $this->executeCallable($macro, ...$parameters); }); } private static function floorZeroPad(int|float $value, int $length): string { return str_pad((string) floor($value), $length, '0', STR_PAD_LEFT); } /** * @template T of CarbonInterface * * @param T $date * * @return T */ private function mutateIfMutable(CarbonInterface $date): CarbonInterface { return $this instanceof DateTimeImmutable ? $date : $this->modify('@'.$date->rawFormat('U.u'))->setTimezone($date->getTimezone()); } }
PHP
{ "end_line": 1061, "name": "carbonize", "signature": "public function carbonize($date = null)", "start_line": 1050 }
{ "class_name": "Date", "class_signature": "trait Date", "namespace": "Carbon\\Traits" }
hasRelativeKeywords
Carbon/src/Carbon/Traits/Date.php
public static function hasRelativeKeywords(?string $time): bool { if (!$time || strtotime($time) === false) { return false; } $date1 = new DateTime('2000-01-01T00:00:00Z'); $date1->modify($time); $date2 = new DateTime('2001-12-25T00:00:00Z'); $date2->modify($time); return $date1 != $date2; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use BadMethodCallException; use Carbon\Carbon; use Carbon\CarbonInterface; use Carbon\CarbonPeriod; use Carbon\CarbonTimeZone; use Carbon\Exceptions\BadComparisonUnitException; use Carbon\Exceptions\ImmutableException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Exceptions\UnitException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\FactoryImmutable; use Carbon\Month; use Carbon\Translator; use Carbon\Unit; use Carbon\WeekDay; use Closure; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use ReflectionException; use Symfony\Component\Clock\NativeClock; use Throwable; /** * A simple API extension for DateTime. * * <autodoc generated by `composer phpdoc`> * * @property string $localeDayOfWeek the day of week in current locale * @property string $shortLocaleDayOfWeek the abbreviated day of week in current locale * @property string $localeMonth the month in current locale * @property string $shortLocaleMonth the abbreviated month in current locale * @property int $year * @property int $yearIso * @property int $month * @property int $day * @property int $hour * @property int $minute * @property int $second * @property int $micro * @property int $microsecond * @property int $dayOfWeekIso 1 (for Monday) through 7 (for Sunday) * @property int|float|string $timestamp seconds since the Unix Epoch * @property string $englishDayOfWeek the day of week in English * @property string $shortEnglishDayOfWeek the abbreviated day of week in English * @property string $englishMonth the month in English * @property string $shortEnglishMonth the abbreviated month in English * @property int $milliseconds * @property int $millisecond * @property int $milli * @property int $week 1 through 53 * @property int $isoWeek 1 through 53 * @property int $weekYear year according to week format * @property int $isoWeekYear year according to ISO week format * @property int $age does a diffInYears() with default parameters * @property int $offset the timezone offset in seconds from UTC * @property int $offsetMinutes the timezone offset in minutes from UTC * @property int $offsetHours the timezone offset in hours from UTC * @property CarbonTimeZone $timezone the current timezone * @property CarbonTimeZone $tz alias of $timezone * @property int $centuryOfMillennium The value of the century starting from the beginning of the current millennium * @property int $dayOfCentury The value of the day starting from the beginning of the current century * @property int $dayOfDecade The value of the day starting from the beginning of the current decade * @property int $dayOfMillennium The value of the day starting from the beginning of the current millennium * @property int $dayOfMonth The value of the day starting from the beginning of the current month * @property int $dayOfQuarter The value of the day starting from the beginning of the current quarter * @property int $dayOfWeek 0 (for Sunday) through 6 (for Saturday) * @property int $dayOfYear 1 through 366 * @property int $decadeOfCentury The value of the decade starting from the beginning of the current century * @property int $decadeOfMillennium The value of the decade starting from the beginning of the current millennium * @property int $hourOfCentury The value of the hour starting from the beginning of the current century * @property int $hourOfDay The value of the hour starting from the beginning of the current day * @property int $hourOfDecade The value of the hour starting from the beginning of the current decade * @property int $hourOfMillennium The value of the hour starting from the beginning of the current millennium * @property int $hourOfMonth The value of the hour starting from the beginning of the current month * @property int $hourOfQuarter The value of the hour starting from the beginning of the current quarter * @property int $hourOfWeek The value of the hour starting from the beginning of the current week * @property int $hourOfYear The value of the hour starting from the beginning of the current year * @property int $microsecondOfCentury The value of the microsecond starting from the beginning of the current century * @property int $microsecondOfDay The value of the microsecond starting from the beginning of the current day * @property int $microsecondOfDecade The value of the microsecond starting from the beginning of the current decade * @property int $microsecondOfHour The value of the microsecond starting from the beginning of the current hour * @property int $microsecondOfMillennium The value of the microsecond starting from the beginning of the current millennium * @property int $microsecondOfMillisecond The value of the microsecond starting from the beginning of the current millisecond * @property int $microsecondOfMinute The value of the microsecond starting from the beginning of the current minute * @property int $microsecondOfMonth The value of the microsecond starting from the beginning of the current month * @property int $microsecondOfQuarter The value of the microsecond starting from the beginning of the current quarter * @property int $microsecondOfSecond The value of the microsecond starting from the beginning of the current second * @property int $microsecondOfWeek The value of the microsecond starting from the beginning of the current week * @property int $microsecondOfYear The value of the microsecond starting from the beginning of the current year * @property int $millisecondOfCentury The value of the millisecond starting from the beginning of the current century * @property int $millisecondOfDay The value of the millisecond starting from the beginning of the current day * @property int $millisecondOfDecade The value of the millisecond starting from the beginning of the current decade * @property int $millisecondOfHour The value of the millisecond starting from the beginning of the current hour * @property int $millisecondOfMillennium The value of the millisecond starting from the beginning of the current millennium * @property int $millisecondOfMinute The value of the millisecond starting from the beginning of the current minute * @property int $millisecondOfMonth The value of the millisecond starting from the beginning of the current month * @property int $millisecondOfQuarter The value of the millisecond starting from the beginning of the current quarter * @property int $millisecondOfSecond The value of the millisecond starting from the beginning of the current second * @property int $millisecondOfWeek The value of the millisecond starting from the beginning of the current week * @property int $millisecondOfYear The value of the millisecond starting from the beginning of the current year * @property int $minuteOfCentury The value of the minute starting from the beginning of the current century * @property int $minuteOfDay The value of the minute starting from the beginning of the current day * @property int $minuteOfDecade The value of the minute starting from the beginning of the current decade * @property int $minuteOfHour The value of the minute starting from the beginning of the current hour * @property int $minuteOfMillennium The value of the minute starting from the beginning of the current millennium * @property int $minuteOfMonth The value of the minute starting from the beginning of the current month * @property int $minuteOfQuarter The value of the minute starting from the beginning of the current quarter * @property int $minuteOfWeek The value of the minute starting from the beginning of the current week * @property int $minuteOfYear The value of the minute starting from the beginning of the current year * @property int $monthOfCentury The value of the month starting from the beginning of the current century * @property int $monthOfDecade The value of the month starting from the beginning of the current decade * @property int $monthOfMillennium The value of the month starting from the beginning of the current millennium * @property int $monthOfQuarter The value of the month starting from the beginning of the current quarter * @property int $monthOfYear The value of the month starting from the beginning of the current year * @property int $quarterOfCentury The value of the quarter starting from the beginning of the current century * @property int $quarterOfDecade The value of the quarter starting from the beginning of the current decade * @property int $quarterOfMillennium The value of the quarter starting from the beginning of the current millennium * @property int $quarterOfYear The value of the quarter starting from the beginning of the current year * @property int $secondOfCentury The value of the second starting from the beginning of the current century * @property int $secondOfDay The value of the second starting from the beginning of the current day * @property int $secondOfDecade The value of the second starting from the beginning of the current decade * @property int $secondOfHour The value of the second starting from the beginning of the current hour * @property int $secondOfMillennium The value of the second starting from the beginning of the current millennium * @property int $secondOfMinute The value of the second starting from the beginning of the current minute * @property int $secondOfMonth The value of the second starting from the beginning of the current month * @property int $secondOfQuarter The value of the second starting from the beginning of the current quarter * @property int $secondOfWeek The value of the second starting from the beginning of the current week * @property int $secondOfYear The value of the second starting from the beginning of the current year * @property int $weekOfCentury The value of the week starting from the beginning of the current century * @property int $weekOfDecade The value of the week starting from the beginning of the current decade * @property int $weekOfMillennium The value of the week starting from the beginning of the current millennium * @property int $weekOfMonth 1 through 5 * @property int $weekOfQuarter The value of the week starting from the beginning of the current quarter * @property int $weekOfYear ISO-8601 week number of year, weeks starting on Monday * @property int $yearOfCentury The value of the year starting from the beginning of the current century * @property int $yearOfDecade The value of the year starting from the beginning of the current decade * @property int $yearOfMillennium The value of the year starting from the beginning of the current millennium * @property-read string $latinMeridiem "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) * @property-read string $latinUpperMeridiem "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) * @property-read string $timezoneAbbreviatedName the current timezone abbreviated name * @property-read string $tzAbbrName alias of $timezoneAbbreviatedName * @property-read string $dayName long name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $shortDayName short name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $minDayName very short name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $monthName long name of month translated according to Carbon locale, in english if no translation available for current language * @property-read string $shortMonthName short name of month translated according to Carbon locale, in english if no translation available for current language * @property-read string $meridiem lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language * @property-read string $upperMeridiem uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language * @property-read int $noZeroHour current hour from 1 to 24 * @property-read int $isoWeeksInYear 51 through 53 * @property-read int $weekNumberInMonth 1 through 5 * @property-read int $firstWeekDay 0 through 6 * @property-read int $lastWeekDay 0 through 6 * @property-read int $quarter the quarter of this instance, 1 - 4 * @property-read int $decade the decade of this instance * @property-read int $century the century of this instance * @property-read int $millennium the millennium of this instance * @property-read bool $dst daylight savings time indicator, true if DST, false otherwise * @property-read bool $local checks if the timezone is local, true if local, false otherwise * @property-read bool $utc checks if the timezone is UTC, true if UTC, false otherwise * @property-read string $timezoneName the current timezone name * @property-read string $tzName alias of $timezoneName * @property-read string $locale locale of the current instance * @property-read int $centuriesInMillennium The number of centuries contained in the current millennium * @property-read int $daysInCentury The number of days contained in the current century * @property-read int $daysInDecade The number of days contained in the current decade * @property-read int $daysInMillennium The number of days contained in the current millennium * @property-read int $daysInMonth number of days in the given month * @property-read int $daysInQuarter The number of days contained in the current quarter * @property-read int $daysInWeek The number of days contained in the current week * @property-read int $daysInYear 365 or 366 * @property-read int $decadesInCentury The number of decades contained in the current century * @property-read int $decadesInMillennium The number of decades contained in the current millennium * @property-read int $hoursInCentury The number of hours contained in the current century * @property-read int $hoursInDay The number of hours contained in the current day * @property-read int $hoursInDecade The number of hours contained in the current decade * @property-read int $hoursInMillennium The number of hours contained in the current millennium * @property-read int $hoursInMonth The number of hours contained in the current month * @property-read int $hoursInQuarter The number of hours contained in the current quarter * @property-read int $hoursInWeek The number of hours contained in the current week * @property-read int $hoursInYear The number of hours contained in the current year * @property-read int $microsecondsInCentury The number of microseconds contained in the current century * @property-read int $microsecondsInDay The number of microseconds contained in the current day * @property-read int $microsecondsInDecade The number of microseconds contained in the current decade * @property-read int $microsecondsInHour The number of microseconds contained in the current hour * @property-read int $microsecondsInMillennium The number of microseconds contained in the current millennium * @property-read int $microsecondsInMillisecond The number of microseconds contained in the current millisecond * @property-read int $microsecondsInMinute The number of microseconds contained in the current minute * @property-read int $microsecondsInMonth The number of microseconds contained in the current month * @property-read int $microsecondsInQuarter The number of microseconds contained in the current quarter * @property-read int $microsecondsInSecond The number of microseconds contained in the current second * @property-read int $microsecondsInWeek The number of microseconds contained in the current week * @property-read int $microsecondsInYear The number of microseconds contained in the current year * @property-read int $millisecondsInCentury The number of milliseconds contained in the current century * @property-read int $millisecondsInDay The number of milliseconds contained in the current day * @property-read int $millisecondsInDecade The number of milliseconds contained in the current decade * @property-read int $millisecondsInHour The number of milliseconds contained in the current hour * @property-read int $millisecondsInMillennium The number of milliseconds contained in the current millennium * @property-read int $millisecondsInMinute The number of milliseconds contained in the current minute * @property-read int $millisecondsInMonth The number of milliseconds contained in the current month * @property-read int $millisecondsInQuarter The number of milliseconds contained in the current quarter * @property-read int $millisecondsInSecond The number of milliseconds contained in the current second * @property-read int $millisecondsInWeek The number of milliseconds contained in the current week * @property-read int $millisecondsInYear The number of milliseconds contained in the current year * @property-read int $minutesInCentury The number of minutes contained in the current century * @property-read int $minutesInDay The number of minutes contained in the current day * @property-read int $minutesInDecade The number of minutes contained in the current decade * @property-read int $minutesInHour The number of minutes contained in the current hour * @property-read int $minutesInMillennium The number of minutes contained in the current millennium * @property-read int $minutesInMonth The number of minutes contained in the current month * @property-read int $minutesInQuarter The number of minutes contained in the current quarter * @property-read int $minutesInWeek The number of minutes contained in the current week * @property-read int $minutesInYear The number of minutes contained in the current year * @property-read int $monthsInCentury The number of months contained in the current century * @property-read int $monthsInDecade The number of months contained in the current decade * @property-read int $monthsInMillennium The number of months contained in the current millennium * @property-read int $monthsInQuarter The number of months contained in the current quarter * @property-read int $monthsInYear The number of months contained in the current year * @property-read int $quartersInCentury The number of quarters contained in the current century * @property-read int $quartersInDecade The number of quarters contained in the current decade * @property-read int $quartersInMillennium The number of quarters contained in the current millennium * @property-read int $quartersInYear The number of quarters contained in the current year * @property-read int $secondsInCentury The number of seconds contained in the current century * @property-read int $secondsInDay The number of seconds contained in the current day * @property-read int $secondsInDecade The number of seconds contained in the current decade * @property-read int $secondsInHour The number of seconds contained in the current hour * @property-read int $secondsInMillennium The number of seconds contained in the current millennium * @property-read int $secondsInMinute The number of seconds contained in the current minute * @property-read int $secondsInMonth The number of seconds contained in the current month * @property-read int $secondsInQuarter The number of seconds contained in the current quarter * @property-read int $secondsInWeek The number of seconds contained in the current week * @property-read int $secondsInYear The number of seconds contained in the current year * @property-read int $weeksInCentury The number of weeks contained in the current century * @property-read int $weeksInDecade The number of weeks contained in the current decade * @property-read int $weeksInMillennium The number of weeks contained in the current millennium * @property-read int $weeksInMonth The number of weeks contained in the current month * @property-read int $weeksInQuarter The number of weeks contained in the current quarter * @property-read int $weeksInYear 51 through 53 * @property-read int $yearsInCentury The number of years contained in the current century * @property-read int $yearsInDecade The number of years contained in the current decade * @property-read int $yearsInMillennium The number of years contained in the current millennium * * @method bool isUtc() Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) * @method bool isLocal() Check if the current instance has non-UTC timezone. * @method bool isValid() Check if the current instance is a valid date. * @method bool isDST() Check if the current instance is in a daylight saving time. * @method bool isSunday() Checks if the instance day is sunday. * @method bool isMonday() Checks if the instance day is monday. * @method bool isTuesday() Checks if the instance day is tuesday. * @method bool isWednesday() Checks if the instance day is wednesday. * @method bool isThursday() Checks if the instance day is thursday. * @method bool isFriday() Checks if the instance day is friday. * @method bool isSaturday() Checks if the instance day is saturday. * @method bool isSameYear(DateTimeInterface|string $date) Checks if the given date is in the same year as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentYear() Checks if the instance is in the same year as the current moment. * @method bool isNextYear() Checks if the instance is in the same year as the current moment next year. * @method bool isLastYear() Checks if the instance is in the same year as the current moment last year. * @method bool isCurrentMonth() Checks if the instance is in the same month as the current moment. * @method bool isNextMonth() Checks if the instance is in the same month as the current moment next month. * @method bool isLastMonth() Checks if the instance is in the same month as the current moment last month. * @method bool isSameWeek(DateTimeInterface|string $date) Checks if the given date is in the same week as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentWeek() Checks if the instance is in the same week as the current moment. * @method bool isNextWeek() Checks if the instance is in the same week as the current moment next week. * @method bool isLastWeek() Checks if the instance is in the same week as the current moment last week. * @method bool isSameDay(DateTimeInterface|string $date) Checks if the given date is in the same day as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentDay() Checks if the instance is in the same day as the current moment. * @method bool isNextDay() Checks if the instance is in the same day as the current moment next day. * @method bool isLastDay() Checks if the instance is in the same day as the current moment last day. * @method bool isSameHour(DateTimeInterface|string $date) Checks if the given date is in the same hour as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentHour() Checks if the instance is in the same hour as the current moment. * @method bool isNextHour() Checks if the instance is in the same hour as the current moment next hour. * @method bool isLastHour() Checks if the instance is in the same hour as the current moment last hour. * @method bool isSameMinute(DateTimeInterface|string $date) Checks if the given date is in the same minute as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMinute() Checks if the instance is in the same minute as the current moment. * @method bool isNextMinute() Checks if the instance is in the same minute as the current moment next minute. * @method bool isLastMinute() Checks if the instance is in the same minute as the current moment last minute. * @method bool isSameSecond(DateTimeInterface|string $date) Checks if the given date is in the same second as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentSecond() Checks if the instance is in the same second as the current moment. * @method bool isNextSecond() Checks if the instance is in the same second as the current moment next second. * @method bool isLastSecond() Checks if the instance is in the same second as the current moment last second. * @method bool isSameMilli(DateTimeInterface|string $date) Checks if the given date is in the same millisecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMilli() Checks if the instance is in the same millisecond as the current moment. * @method bool isNextMilli() Checks if the instance is in the same millisecond as the current moment next millisecond. * @method bool isLastMilli() Checks if the instance is in the same millisecond as the current moment last millisecond. * @method bool isSameMillisecond(DateTimeInterface|string $date) Checks if the given date is in the same millisecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMillisecond() Checks if the instance is in the same millisecond as the current moment. * @method bool isNextMillisecond() Checks if the instance is in the same millisecond as the current moment next millisecond. * @method bool isLastMillisecond() Checks if the instance is in the same millisecond as the current moment last millisecond. * @method bool isSameMicro(DateTimeInterface|string $date) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMicro() Checks if the instance is in the same microsecond as the current moment. * @method bool isNextMicro() Checks if the instance is in the same microsecond as the current moment next microsecond. * @method bool isLastMicro() Checks if the instance is in the same microsecond as the current moment last microsecond. * @method bool isSameMicrosecond(DateTimeInterface|string $date) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMicrosecond() Checks if the instance is in the same microsecond as the current moment. * @method bool isNextMicrosecond() Checks if the instance is in the same microsecond as the current moment next microsecond. * @method bool isLastMicrosecond() Checks if the instance is in the same microsecond as the current moment last microsecond. * @method bool isSameDecade(DateTimeInterface|string $date) Checks if the given date is in the same decade as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentDecade() Checks if the instance is in the same decade as the current moment. * @method bool isNextDecade() Checks if the instance is in the same decade as the current moment next decade. * @method bool isLastDecade() Checks if the instance is in the same decade as the current moment last decade. * @method bool isSameCentury(DateTimeInterface|string $date) Checks if the given date is in the same century as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentCentury() Checks if the instance is in the same century as the current moment. * @method bool isNextCentury() Checks if the instance is in the same century as the current moment next century. * @method bool isLastCentury() Checks if the instance is in the same century as the current moment last century. * @method bool isSameMillennium(DateTimeInterface|string $date) Checks if the given date is in the same millennium as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMillennium() Checks if the instance is in the same millennium as the current moment. * @method bool isNextMillennium() Checks if the instance is in the same millennium as the current moment next millennium. * @method bool isLastMillennium() Checks if the instance is in the same millennium as the current moment last millennium. * @method bool isCurrentQuarter() Checks if the instance is in the same quarter as the current moment. * @method bool isNextQuarter() Checks if the instance is in the same quarter as the current moment next quarter. * @method bool isLastQuarter() Checks if the instance is in the same quarter as the current moment last quarter. * @method CarbonInterface years(int $value) Set current instance year to the given value. * @method CarbonInterface year(int $value) Set current instance year to the given value. * @method CarbonInterface setYears(int $value) Set current instance year to the given value. * @method CarbonInterface setYear(int $value) Set current instance year to the given value. * @method CarbonInterface months(Month|int $value) Set current instance month to the given value. * @method CarbonInterface month(Month|int $value) Set current instance month to the given value. * @method CarbonInterface setMonths(Month|int $value) Set current instance month to the given value. * @method CarbonInterface setMonth(Month|int $value) Set current instance month to the given value. * @method CarbonInterface days(int $value) Set current instance day to the given value. * @method CarbonInterface day(int $value) Set current instance day to the given value. * @method CarbonInterface setDays(int $value) Set current instance day to the given value. * @method CarbonInterface setDay(int $value) Set current instance day to the given value. * @method CarbonInterface hours(int $value) Set current instance hour to the given value. * @method CarbonInterface hour(int $value) Set current instance hour to the given value. * @method CarbonInterface setHours(int $value) Set current instance hour to the given value. * @method CarbonInterface setHour(int $value) Set current instance hour to the given value. * @method CarbonInterface minutes(int $value) Set current instance minute to the given value. * @method CarbonInterface minute(int $value) Set current instance minute to the given value. * @method CarbonInterface setMinutes(int $value) Set current instance minute to the given value. * @method CarbonInterface setMinute(int $value) Set current instance minute to the given value. * @method CarbonInterface seconds(int $value) Set current instance second to the given value. * @method CarbonInterface second(int $value) Set current instance second to the given value. * @method CarbonInterface setSeconds(int $value) Set current instance second to the given value. * @method CarbonInterface setSecond(int $value) Set current instance second to the given value. * @method CarbonInterface millis(int $value) Set current instance millisecond to the given value. * @method CarbonInterface milli(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMillis(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMilli(int $value) Set current instance millisecond to the given value. * @method CarbonInterface milliseconds(int $value) Set current instance millisecond to the given value. * @method CarbonInterface millisecond(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMilliseconds(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMillisecond(int $value) Set current instance millisecond to the given value. * @method CarbonInterface micros(int $value) Set current instance microsecond to the given value. * @method CarbonInterface micro(int $value) Set current instance microsecond to the given value. * @method CarbonInterface setMicros(int $value) Set current instance microsecond to the given value. * @method CarbonInterface setMicro(int $value) Set current instance microsecond to the given value. * @method CarbonInterface microseconds(int $value) Set current instance microsecond to the given value. * @method CarbonInterface microsecond(int $value) Set current instance microsecond to the given value. * @method CarbonInterface setMicroseconds(int $value) Set current instance microsecond to the given value. * @method self setMicrosecond(int $value) Set current instance microsecond to the given value. * @method CarbonInterface addYears(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addYear() Add one year to the instance (using date interval). * @method CarbonInterface subYears(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subYear() Sub one year to the instance (using date interval). * @method CarbonInterface addYearsWithOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addYearWithOverflow() Add one year to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subYearsWithOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subYearWithOverflow() Sub one year to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addYearsWithoutOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearWithoutOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearsWithoutOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearWithoutOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearsWithNoOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearWithNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearsWithNoOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearWithNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearsNoOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearsNoOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonths(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMonth() Add one month to the instance (using date interval). * @method CarbonInterface subMonths(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMonth() Sub one month to the instance (using date interval). * @method CarbonInterface addMonthsWithOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMonthWithOverflow() Add one month to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMonthsWithOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMonthWithOverflow() Sub one month to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMonthsWithoutOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthWithoutOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthsWithoutOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthWithoutOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthsWithNoOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthWithNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthsWithNoOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthWithNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthsNoOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthsNoOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDays(int|float $value = 1) Add days (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addDay() Add one day to the instance (using date interval). * @method CarbonInterface subDays(int|float $value = 1) Sub days (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subDay() Sub one day to the instance (using date interval). * @method CarbonInterface addHours(int|float $value = 1) Add hours (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addHour() Add one hour to the instance (using date interval). * @method CarbonInterface subHours(int|float $value = 1) Sub hours (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subHour() Sub one hour to the instance (using date interval). * @method CarbonInterface addMinutes(int|float $value = 1) Add minutes (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMinute() Add one minute to the instance (using date interval). * @method CarbonInterface subMinutes(int|float $value = 1) Sub minutes (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMinute() Sub one minute to the instance (using date interval). * @method CarbonInterface addSeconds(int|float $value = 1) Add seconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addSecond() Add one second to the instance (using date interval). * @method CarbonInterface subSeconds(int|float $value = 1) Sub seconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subSecond() Sub one second to the instance (using date interval). * @method CarbonInterface addMillis(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMilli() Add one millisecond to the instance (using date interval). * @method CarbonInterface subMillis(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMilli() Sub one millisecond to the instance (using date interval). * @method CarbonInterface addMilliseconds(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMillisecond() Add one millisecond to the instance (using date interval). * @method CarbonInterface subMilliseconds(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMillisecond() Sub one millisecond to the instance (using date interval). * @method CarbonInterface addMicros(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMicro() Add one microsecond to the instance (using date interval). * @method CarbonInterface subMicros(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMicro() Sub one microsecond to the instance (using date interval). * @method CarbonInterface addMicroseconds(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMicrosecond() Add one microsecond to the instance (using date interval). * @method CarbonInterface subMicroseconds(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMicrosecond() Sub one microsecond to the instance (using date interval). * @method CarbonInterface addMillennia(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMillennium() Add one millennium to the instance (using date interval). * @method CarbonInterface subMillennia(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMillennium() Sub one millennium to the instance (using date interval). * @method CarbonInterface addMillenniaWithOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMillenniumWithOverflow() Add one millennium to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMillenniaWithOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMillenniumWithOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMillenniaWithoutOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniumWithoutOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniaWithoutOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniumWithoutOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniaWithNoOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniumWithNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniaWithNoOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniumWithNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniaNoOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniumNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniaNoOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniumNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturies(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addCentury() Add one century to the instance (using date interval). * @method CarbonInterface subCenturies(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subCentury() Sub one century to the instance (using date interval). * @method CarbonInterface addCenturiesWithOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addCenturyWithOverflow() Add one century to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subCenturiesWithOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subCenturyWithOverflow() Sub one century to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addCenturiesWithoutOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturyWithoutOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturiesWithoutOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturyWithoutOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturiesWithNoOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturyWithNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturiesWithNoOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturyWithNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturiesNoOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturyNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturiesNoOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturyNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecades(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addDecade() Add one decade to the instance (using date interval). * @method CarbonInterface subDecades(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subDecade() Sub one decade to the instance (using date interval). * @method CarbonInterface addDecadesWithOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addDecadeWithOverflow() Add one decade to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subDecadesWithOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subDecadeWithOverflow() Sub one decade to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addDecadesWithoutOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadeWithoutOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadesWithoutOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadeWithoutOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadesWithNoOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadeWithNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadesWithNoOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadeWithNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadesNoOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadeNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadesNoOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadeNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarters(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addQuarter() Add one quarter to the instance (using date interval). * @method CarbonInterface subQuarters(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subQuarter() Sub one quarter to the instance (using date interval). * @method CarbonInterface addQuartersWithOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addQuarterWithOverflow() Add one quarter to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subQuartersWithOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subQuarterWithOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addQuartersWithoutOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarterWithoutOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuartersWithoutOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuarterWithoutOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuartersWithNoOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarterWithNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuartersWithNoOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuarterWithNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuartersNoOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarterNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuartersNoOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuarterNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addWeeks(int|float $value = 1) Add weeks (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addWeek() Add one week to the instance (using date interval). * @method CarbonInterface subWeeks(int|float $value = 1) Sub weeks (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subWeek() Sub one week to the instance (using date interval). * @method CarbonInterface addWeekdays(int|float $value = 1) Add weekdays (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addWeekday() Add one weekday to the instance (using date interval). * @method CarbonInterface subWeekdays(int|float $value = 1) Sub weekdays (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subWeekday() Sub one weekday to the instance (using date interval). * @method CarbonInterface addUTCMicros(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMicro() Add one microsecond to the instance (using timestamp). * @method CarbonInterface subUTCMicros(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMicro() Sub one microsecond to the instance (using timestamp). * @method CarbonPeriod microsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. * @method float diffInUTCMicros(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of microseconds. * @method CarbonInterface addUTCMicroseconds(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMicrosecond() Add one microsecond to the instance (using timestamp). * @method CarbonInterface subUTCMicroseconds(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMicrosecond() Sub one microsecond to the instance (using timestamp). * @method CarbonPeriod microsecondsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. * @method float diffInUTCMicroseconds(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of microseconds. * @method CarbonInterface addUTCMillis(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMilli() Add one millisecond to the instance (using timestamp). * @method CarbonInterface subUTCMillis(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMilli() Sub one millisecond to the instance (using timestamp). * @method CarbonPeriod millisUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. * @method float diffInUTCMillis(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of milliseconds. * @method CarbonInterface addUTCMilliseconds(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMillisecond() Add one millisecond to the instance (using timestamp). * @method CarbonInterface subUTCMilliseconds(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMillisecond() Sub one millisecond to the instance (using timestamp). * @method CarbonPeriod millisecondsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. * @method float diffInUTCMilliseconds(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of milliseconds. * @method CarbonInterface addUTCSeconds(int|float $value = 1) Add seconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCSecond() Add one second to the instance (using timestamp). * @method CarbonInterface subUTCSeconds(int|float $value = 1) Sub seconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCSecond() Sub one second to the instance (using timestamp). * @method CarbonPeriod secondsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each second or every X seconds if a factor is given. * @method float diffInUTCSeconds(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of seconds. * @method CarbonInterface addUTCMinutes(int|float $value = 1) Add minutes (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMinute() Add one minute to the instance (using timestamp). * @method CarbonInterface subUTCMinutes(int|float $value = 1) Sub minutes (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMinute() Sub one minute to the instance (using timestamp). * @method CarbonPeriod minutesUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each minute or every X minutes if a factor is given. * @method float diffInUTCMinutes(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of minutes. * @method CarbonInterface addUTCHours(int|float $value = 1) Add hours (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCHour() Add one hour to the instance (using timestamp). * @method CarbonInterface subUTCHours(int|float $value = 1) Sub hours (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCHour() Sub one hour to the instance (using timestamp). * @method CarbonPeriod hoursUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each hour or every X hours if a factor is given. * @method float diffInUTCHours(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of hours. * @method CarbonInterface addUTCDays(int|float $value = 1) Add days (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCDay() Add one day to the instance (using timestamp). * @method CarbonInterface subUTCDays(int|float $value = 1) Sub days (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCDay() Sub one day to the instance (using timestamp). * @method CarbonPeriod daysUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each day or every X days if a factor is given. * @method float diffInUTCDays(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of days. * @method CarbonInterface addUTCWeeks(int|float $value = 1) Add weeks (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCWeek() Add one week to the instance (using timestamp). * @method CarbonInterface subUTCWeeks(int|float $value = 1) Sub weeks (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCWeek() Sub one week to the instance (using timestamp). * @method CarbonPeriod weeksUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each week or every X weeks if a factor is given. * @method float diffInUTCWeeks(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of weeks. * @method CarbonInterface addUTCMonths(int|float $value = 1) Add months (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMonth() Add one month to the instance (using timestamp). * @method CarbonInterface subUTCMonths(int|float $value = 1) Sub months (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMonth() Sub one month to the instance (using timestamp). * @method CarbonPeriod monthsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each month or every X months if a factor is given. * @method float diffInUTCMonths(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of months. * @method CarbonInterface addUTCQuarters(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCQuarter() Add one quarter to the instance (using timestamp). * @method CarbonInterface subUTCQuarters(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCQuarter() Sub one quarter to the instance (using timestamp). * @method CarbonPeriod quartersUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each quarter or every X quarters if a factor is given. * @method float diffInUTCQuarters(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of quarters. * @method CarbonInterface addUTCYears(int|float $value = 1) Add years (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCYear() Add one year to the instance (using timestamp). * @method CarbonInterface subUTCYears(int|float $value = 1) Sub years (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCYear() Sub one year to the instance (using timestamp). * @method CarbonPeriod yearsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each year or every X years if a factor is given. * @method float diffInUTCYears(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of years. * @method CarbonInterface addUTCDecades(int|float $value = 1) Add decades (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCDecade() Add one decade to the instance (using timestamp). * @method CarbonInterface subUTCDecades(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCDecade() Sub one decade to the instance (using timestamp). * @method CarbonPeriod decadesUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each decade or every X decades if a factor is given. * @method float diffInUTCDecades(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of decades. * @method CarbonInterface addUTCCenturies(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCCentury() Add one century to the instance (using timestamp). * @method CarbonInterface subUTCCenturies(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCCentury() Sub one century to the instance (using timestamp). * @method CarbonPeriod centuriesUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each century or every X centuries if a factor is given. * @method float diffInUTCCenturies(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of centuries. * @method CarbonInterface addUTCMillennia(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMillennium() Add one millennium to the instance (using timestamp). * @method CarbonInterface subUTCMillennia(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMillennium() Sub one millennium to the instance (using timestamp). * @method CarbonPeriod millenniaUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millennium or every X millennia if a factor is given. * @method float diffInUTCMillennia(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of millennia. * @method CarbonInterface roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method CarbonInterface roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method CarbonInterface floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method CarbonInterface floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method CarbonInterface ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method CarbonInterface ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method CarbonInterface roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method CarbonInterface roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method CarbonInterface floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method CarbonInterface floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method CarbonInterface ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method CarbonInterface ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method CarbonInterface roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method CarbonInterface roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method CarbonInterface floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method CarbonInterface floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method CarbonInterface ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method CarbonInterface ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method CarbonInterface roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method CarbonInterface roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method CarbonInterface floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method CarbonInterface floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method CarbonInterface ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method CarbonInterface ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method CarbonInterface roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method CarbonInterface roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method CarbonInterface floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method CarbonInterface floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method CarbonInterface ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method CarbonInterface ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method CarbonInterface roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method CarbonInterface roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method CarbonInterface floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method CarbonInterface floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method CarbonInterface ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method CarbonInterface ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method CarbonInterface roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method CarbonInterface roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method CarbonInterface floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method CarbonInterface floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method CarbonInterface ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method CarbonInterface ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method CarbonInterface roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method CarbonInterface roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method CarbonInterface floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method CarbonInterface floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method CarbonInterface ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method CarbonInterface ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method CarbonInterface roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method CarbonInterface roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method CarbonInterface floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method CarbonInterface floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method CarbonInterface ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method CarbonInterface ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method CarbonInterface roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method CarbonInterface roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method CarbonInterface floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method CarbonInterface floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method CarbonInterface ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method CarbonInterface ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method CarbonInterface roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method CarbonInterface roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method CarbonInterface floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method CarbonInterface floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method CarbonInterface ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method CarbonInterface ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method CarbonInterface roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method CarbonInterface roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method CarbonInterface floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method CarbonInterface floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method CarbonInterface ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method CarbonInterface ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * @method string shortAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string shortRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string shortRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string shortRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method int centuriesInMillennium() Return the number of centuries contained in the current millennium * @method int|static centuryOfMillennium(?int $century = null) Return the value of the century starting from the beginning of the current millennium when called with no parameters, change the current century when called with an integer value * @method int|static dayOfCentury(?int $day = null) Return the value of the day starting from the beginning of the current century when called with no parameters, change the current day when called with an integer value * @method int|static dayOfDecade(?int $day = null) Return the value of the day starting from the beginning of the current decade when called with no parameters, change the current day when called with an integer value * @method int|static dayOfMillennium(?int $day = null) Return the value of the day starting from the beginning of the current millennium when called with no parameters, change the current day when called with an integer value * @method int|static dayOfMonth(?int $day = null) Return the value of the day starting from the beginning of the current month when called with no parameters, change the current day when called with an integer value * @method int|static dayOfQuarter(?int $day = null) Return the value of the day starting from the beginning of the current quarter when called with no parameters, change the current day when called with an integer value * @method int|static dayOfWeek(?int $day = null) Return the value of the day starting from the beginning of the current week when called with no parameters, change the current day when called with an integer value * @method int daysInCentury() Return the number of days contained in the current century * @method int daysInDecade() Return the number of days contained in the current decade * @method int daysInMillennium() Return the number of days contained in the current millennium * @method int daysInMonth() Return the number of days contained in the current month * @method int daysInQuarter() Return the number of days contained in the current quarter * @method int daysInWeek() Return the number of days contained in the current week * @method int daysInYear() Return the number of days contained in the current year * @method int|static decadeOfCentury(?int $decade = null) Return the value of the decade starting from the beginning of the current century when called with no parameters, change the current decade when called with an integer value * @method int|static decadeOfMillennium(?int $decade = null) Return the value of the decade starting from the beginning of the current millennium when called with no parameters, change the current decade when called with an integer value * @method int decadesInCentury() Return the number of decades contained in the current century * @method int decadesInMillennium() Return the number of decades contained in the current millennium * @method int|static hourOfCentury(?int $hour = null) Return the value of the hour starting from the beginning of the current century when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfDay(?int $hour = null) Return the value of the hour starting from the beginning of the current day when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfDecade(?int $hour = null) Return the value of the hour starting from the beginning of the current decade when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfMillennium(?int $hour = null) Return the value of the hour starting from the beginning of the current millennium when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfMonth(?int $hour = null) Return the value of the hour starting from the beginning of the current month when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfQuarter(?int $hour = null) Return the value of the hour starting from the beginning of the current quarter when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfWeek(?int $hour = null) Return the value of the hour starting from the beginning of the current week when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfYear(?int $hour = null) Return the value of the hour starting from the beginning of the current year when called with no parameters, change the current hour when called with an integer value * @method int hoursInCentury() Return the number of hours contained in the current century * @method int hoursInDay() Return the number of hours contained in the current day * @method int hoursInDecade() Return the number of hours contained in the current decade * @method int hoursInMillennium() Return the number of hours contained in the current millennium * @method int hoursInMonth() Return the number of hours contained in the current month * @method int hoursInQuarter() Return the number of hours contained in the current quarter * @method int hoursInWeek() Return the number of hours contained in the current week * @method int hoursInYear() Return the number of hours contained in the current year * @method int|static microsecondOfCentury(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current century when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfDay(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current day when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfDecade(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current decade when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfHour(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current hour when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMillennium(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current millennium when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMillisecond(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current millisecond when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMinute(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current minute when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMonth(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current month when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfQuarter(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current quarter when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfSecond(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current second when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfWeek(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current week when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfYear(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current year when called with no parameters, change the current microsecond when called with an integer value * @method int microsecondsInCentury() Return the number of microseconds contained in the current century * @method int microsecondsInDay() Return the number of microseconds contained in the current day * @method int microsecondsInDecade() Return the number of microseconds contained in the current decade * @method int microsecondsInHour() Return the number of microseconds contained in the current hour * @method int microsecondsInMillennium() Return the number of microseconds contained in the current millennium * @method int microsecondsInMillisecond() Return the number of microseconds contained in the current millisecond * @method int microsecondsInMinute() Return the number of microseconds contained in the current minute * @method int microsecondsInMonth() Return the number of microseconds contained in the current month * @method int microsecondsInQuarter() Return the number of microseconds contained in the current quarter * @method int microsecondsInSecond() Return the number of microseconds contained in the current second * @method int microsecondsInWeek() Return the number of microseconds contained in the current week * @method int microsecondsInYear() Return the number of microseconds contained in the current year * @method int|static millisecondOfCentury(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current century when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfDay(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current day when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfDecade(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current decade when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfHour(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current hour when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfMillennium(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current millennium when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfMinute(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current minute when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfMonth(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current month when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfQuarter(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current quarter when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfSecond(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current second when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfWeek(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current week when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfYear(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current year when called with no parameters, change the current millisecond when called with an integer value * @method int millisecondsInCentury() Return the number of milliseconds contained in the current century * @method int millisecondsInDay() Return the number of milliseconds contained in the current day * @method int millisecondsInDecade() Return the number of milliseconds contained in the current decade * @method int millisecondsInHour() Return the number of milliseconds contained in the current hour * @method int millisecondsInMillennium() Return the number of milliseconds contained in the current millennium * @method int millisecondsInMinute() Return the number of milliseconds contained in the current minute * @method int millisecondsInMonth() Return the number of milliseconds contained in the current month * @method int millisecondsInQuarter() Return the number of milliseconds contained in the current quarter * @method int millisecondsInSecond() Return the number of milliseconds contained in the current second * @method int millisecondsInWeek() Return the number of milliseconds contained in the current week * @method int millisecondsInYear() Return the number of milliseconds contained in the current year * @method int|static minuteOfCentury(?int $minute = null) Return the value of the minute starting from the beginning of the current century when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfDay(?int $minute = null) Return the value of the minute starting from the beginning of the current day when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfDecade(?int $minute = null) Return the value of the minute starting from the beginning of the current decade when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfHour(?int $minute = null) Return the value of the minute starting from the beginning of the current hour when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfMillennium(?int $minute = null) Return the value of the minute starting from the beginning of the current millennium when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfMonth(?int $minute = null) Return the value of the minute starting from the beginning of the current month when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfQuarter(?int $minute = null) Return the value of the minute starting from the beginning of the current quarter when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfWeek(?int $minute = null) Return the value of the minute starting from the beginning of the current week when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfYear(?int $minute = null) Return the value of the minute starting from the beginning of the current year when called with no parameters, change the current minute when called with an integer value * @method int minutesInCentury() Return the number of minutes contained in the current century * @method int minutesInDay() Return the number of minutes contained in the current day * @method int minutesInDecade() Return the number of minutes contained in the current decade * @method int minutesInHour() Return the number of minutes contained in the current hour * @method int minutesInMillennium() Return the number of minutes contained in the current millennium * @method int minutesInMonth() Return the number of minutes contained in the current month * @method int minutesInQuarter() Return the number of minutes contained in the current quarter * @method int minutesInWeek() Return the number of minutes contained in the current week * @method int minutesInYear() Return the number of minutes contained in the current year * @method int|static monthOfCentury(?int $month = null) Return the value of the month starting from the beginning of the current century when called with no parameters, change the current month when called with an integer value * @method int|static monthOfDecade(?int $month = null) Return the value of the month starting from the beginning of the current decade when called with no parameters, change the current month when called with an integer value * @method int|static monthOfMillennium(?int $month = null) Return the value of the month starting from the beginning of the current millennium when called with no parameters, change the current month when called with an integer value * @method int|static monthOfQuarter(?int $month = null) Return the value of the month starting from the beginning of the current quarter when called with no parameters, change the current month when called with an integer value * @method int|static monthOfYear(?int $month = null) Return the value of the month starting from the beginning of the current year when called with no parameters, change the current month when called with an integer value * @method int monthsInCentury() Return the number of months contained in the current century * @method int monthsInDecade() Return the number of months contained in the current decade * @method int monthsInMillennium() Return the number of months contained in the current millennium * @method int monthsInQuarter() Return the number of months contained in the current quarter * @method int monthsInYear() Return the number of months contained in the current year * @method int|static quarterOfCentury(?int $quarter = null) Return the value of the quarter starting from the beginning of the current century when called with no parameters, change the current quarter when called with an integer value * @method int|static quarterOfDecade(?int $quarter = null) Return the value of the quarter starting from the beginning of the current decade when called with no parameters, change the current quarter when called with an integer value * @method int|static quarterOfMillennium(?int $quarter = null) Return the value of the quarter starting from the beginning of the current millennium when called with no parameters, change the current quarter when called with an integer value * @method int|static quarterOfYear(?int $quarter = null) Return the value of the quarter starting from the beginning of the current year when called with no parameters, change the current quarter when called with an integer value * @method int quartersInCentury() Return the number of quarters contained in the current century * @method int quartersInDecade() Return the number of quarters contained in the current decade * @method int quartersInMillennium() Return the number of quarters contained in the current millennium * @method int quartersInYear() Return the number of quarters contained in the current year * @method int|static secondOfCentury(?int $second = null) Return the value of the second starting from the beginning of the current century when called with no parameters, change the current second when called with an integer value * @method int|static secondOfDay(?int $second = null) Return the value of the second starting from the beginning of the current day when called with no parameters, change the current second when called with an integer value * @method int|static secondOfDecade(?int $second = null) Return the value of the second starting from the beginning of the current decade when called with no parameters, change the current second when called with an integer value * @method int|static secondOfHour(?int $second = null) Return the value of the second starting from the beginning of the current hour when called with no parameters, change the current second when called with an integer value * @method int|static secondOfMillennium(?int $second = null) Return the value of the second starting from the beginning of the current millennium when called with no parameters, change the current second when called with an integer value * @method int|static secondOfMinute(?int $second = null) Return the value of the second starting from the beginning of the current minute when called with no parameters, change the current second when called with an integer value * @method int|static secondOfMonth(?int $second = null) Return the value of the second starting from the beginning of the current month when called with no parameters, change the current second when called with an integer value * @method int|static secondOfQuarter(?int $second = null) Return the value of the second starting from the beginning of the current quarter when called with no parameters, change the current second when called with an integer value * @method int|static secondOfWeek(?int $second = null) Return the value of the second starting from the beginning of the current week when called with no parameters, change the current second when called with an integer value * @method int|static secondOfYear(?int $second = null) Return the value of the second starting from the beginning of the current year when called with no parameters, change the current second when called with an integer value * @method int secondsInCentury() Return the number of seconds contained in the current century * @method int secondsInDay() Return the number of seconds contained in the current day * @method int secondsInDecade() Return the number of seconds contained in the current decade * @method int secondsInHour() Return the number of seconds contained in the current hour * @method int secondsInMillennium() Return the number of seconds contained in the current millennium * @method int secondsInMinute() Return the number of seconds contained in the current minute * @method int secondsInMonth() Return the number of seconds contained in the current month * @method int secondsInQuarter() Return the number of seconds contained in the current quarter * @method int secondsInWeek() Return the number of seconds contained in the current week * @method int secondsInYear() Return the number of seconds contained in the current year * @method int|static weekOfCentury(?int $week = null) Return the value of the week starting from the beginning of the current century when called with no parameters, change the current week when called with an integer value * @method int|static weekOfDecade(?int $week = null) Return the value of the week starting from the beginning of the current decade when called with no parameters, change the current week when called with an integer value * @method int|static weekOfMillennium(?int $week = null) Return the value of the week starting from the beginning of the current millennium when called with no parameters, change the current week when called with an integer value * @method int|static weekOfMonth(?int $week = null) Return the value of the week starting from the beginning of the current month when called with no parameters, change the current week when called with an integer value * @method int|static weekOfQuarter(?int $week = null) Return the value of the week starting from the beginning of the current quarter when called with no parameters, change the current week when called with an integer value * @method int|static weekOfYear(?int $week = null) Return the value of the week starting from the beginning of the current year when called with no parameters, change the current week when called with an integer value * @method int weeksInCentury() Return the number of weeks contained in the current century * @method int weeksInDecade() Return the number of weeks contained in the current decade * @method int weeksInMillennium() Return the number of weeks contained in the current millennium * @method int weeksInMonth() Return the number of weeks contained in the current month * @method int weeksInQuarter() Return the number of weeks contained in the current quarter * @method int|static yearOfCentury(?int $year = null) Return the value of the year starting from the beginning of the current century when called with no parameters, change the current year when called with an integer value * @method int|static yearOfDecade(?int $year = null) Return the value of the year starting from the beginning of the current decade when called with no parameters, change the current year when called with an integer value * @method int|static yearOfMillennium(?int $year = null) Return the value of the year starting from the beginning of the current millennium when called with no parameters, change the current year when called with an integer value * @method int yearsInCentury() Return the number of years contained in the current century * @method int yearsInDecade() Return the number of years contained in the current decade * @method int yearsInMillennium() Return the number of years contained in the current millennium * * </autodoc> */ trait Date { use Boundaries; use Comparison; use Converter; use Creator; use Difference; use Macro; use MagicParameter; use Modifiers; use Mutability; use ObjectInitialisation; use Options; use Rounding; use Serialization; use Test; use Timestamp; use Units; use Week; /** * Names of days of the week. * * @var array */ protected static $days = [ // @call isDayOfWeek CarbonInterface::SUNDAY => 'Sunday', // @call isDayOfWeek CarbonInterface::MONDAY => 'Monday', // @call isDayOfWeek CarbonInterface::TUESDAY => 'Tuesday', // @call isDayOfWeek CarbonInterface::WEDNESDAY => 'Wednesday', // @call isDayOfWeek CarbonInterface::THURSDAY => 'Thursday', // @call isDayOfWeek CarbonInterface::FRIDAY => 'Friday', // @call isDayOfWeek CarbonInterface::SATURDAY => 'Saturday', ]; /** * List of unit and magic methods associated as doc-comments. * * @var array */ protected static $units = [ // @call setUnit // @call addUnit 'year', // @call setUnit // @call addUnit 'month', // @call setUnit // @call addUnit 'day', // @call setUnit // @call addUnit 'hour', // @call setUnit // @call addUnit 'minute', // @call setUnit // @call addUnit 'second', // @call setUnit // @call addUnit 'milli', // @call setUnit // @call addUnit 'millisecond', // @call setUnit // @call addUnit 'micro', // @call setUnit // @call addUnit 'microsecond', ]; /** * Creates a DateTimeZone from a string, DateTimeZone or integer offset. * * @param DateTimeZone|string|int|false|null $object original value to get CarbonTimeZone from it. * @param DateTimeZone|string|int|false|null $objectDump dump of the object for error messages. * * @throws InvalidTimeZoneException * * @return CarbonTimeZone|null */ protected static function safeCreateDateTimeZone( DateTimeZone|string|int|false|null $object, DateTimeZone|string|int|false|null $objectDump = null, ): ?CarbonTimeZone { return CarbonTimeZone::instance($object, $objectDump); } /** * Get the TimeZone associated with the Carbon instance (as CarbonTimeZone). * * @link https://php.net/manual/en/datetime.gettimezone.php */ public function getTimezone(): CarbonTimeZone { return $this->transmitFactory(fn () => CarbonTimeZone::instance(parent::getTimezone())); } /** * List of minimum and maximums for each unit. */ protected static function getRangesByUnit(int $daysInMonth = 31): array { return [ // @call roundUnit 'year' => [1, 9999], // @call roundUnit 'month' => [1, static::MONTHS_PER_YEAR], // @call roundUnit 'day' => [1, $daysInMonth], // @call roundUnit 'hour' => [0, static::HOURS_PER_DAY - 1], // @call roundUnit 'minute' => [0, static::MINUTES_PER_HOUR - 1], // @call roundUnit 'second' => [0, static::SECONDS_PER_MINUTE - 1], ]; } /** * Get a copy of the instance. * * @return static */ public function copy() { return clone $this; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Clone the current instance if it's mutable. * * This method is convenient to ensure you don't mutate the initial object * but avoid to make a useless copy of it if it's already immutable. * * @return static */ public function avoidMutation(): static { if ($this instanceof DateTimeImmutable) { return $this; } return clone $this; } /** * Returns a present instance in the same timezone. * * @return static */ public function nowWithSameTz(): static { $timezone = $this->getTimezone(); return $this->getClock()?->nowAs(static::class, $timezone) ?? static::now($timezone); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|DateTimeInterface|string|null $date * * @return static */ public function carbonize($date = null) { if ($date instanceof DateInterval) { return $this->avoidMutation()->add($date); } if ($date instanceof DatePeriod || $date instanceof CarbonPeriod) { $date = $date->getStartDate(); } return $this->resolveCarbon($date); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the Carbon object. * * @throws UnknownGetterException * * @return string|int|bool|DateTimeZone|null */ public function __get(string $name): mixed { return $this->get($name); } /** * Get a part of the Carbon object. * * @throws UnknownGetterException * * @return string|int|bool|DateTimeZone */ public function get(Unit|string $name): mixed { static $localizedFormats = [ // @property string the day of week in current locale 'localeDayOfWeek' => 'dddd', // @property string the abbreviated day of week in current locale 'shortLocaleDayOfWeek' => 'ddd', // @property string the month in current locale 'localeMonth' => 'MMMM', // @property string the abbreviated month in current locale 'shortLocaleMonth' => 'MMM', ]; $name = Unit::toName($name); if (isset($localizedFormats[$name])) { return $this->isoFormat($localizedFormats[$name]); } static $formats = [ // @property int 'year' => 'Y', // @property int 'yearIso' => 'o', // @--property-read int // @--property-write Month|int // @property int 'month' => 'n', // @property int 'day' => 'j', // @property int 'hour' => 'G', // @property int 'minute' => 'i', // @property int 'second' => 's', // @property int 'micro' => 'u', // @property int 'microsecond' => 'u', // @property int 0 (for Sunday) through 6 (for Saturday) 'dayOfWeek' => 'w', // @property int 1 (for Monday) through 7 (for Sunday) 'dayOfWeekIso' => 'N', // @property int ISO-8601 week number of year, weeks starting on Monday 'weekOfYear' => 'W', // @property-read int number of days in the given month 'daysInMonth' => 't', // @property int|float|string seconds since the Unix Epoch 'timestamp' => 'U', // @property-read string "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) 'latinMeridiem' => 'a', // @property-read string "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) 'latinUpperMeridiem' => 'A', // @property string the day of week in English 'englishDayOfWeek' => 'l', // @property string the abbreviated day of week in English 'shortEnglishDayOfWeek' => 'D', // @property string the month in English 'englishMonth' => 'F', // @property string the abbreviated month in English 'shortEnglishMonth' => 'M', // @property-read string $timezoneAbbreviatedName the current timezone abbreviated name 'timezoneAbbreviatedName' => 'T', // @property-read string $tzAbbrName alias of $timezoneAbbreviatedName 'tzAbbrName' => 'T', ]; switch (true) { case isset($formats[$name]): $value = $this->rawFormat($formats[$name]); return is_numeric($value) ? (int) $value : $value; // @property-read string long name of weekday translated according to Carbon locale, in english if no translation available for current language case $name === 'dayName': return $this->getTranslatedDayName(); // @property-read string short name of weekday translated according to Carbon locale, in english if no translation available for current language case $name === 'shortDayName': return $this->getTranslatedShortDayName(); // @property-read string very short name of weekday translated according to Carbon locale, in english if no translation available for current language case $name === 'minDayName': return $this->getTranslatedMinDayName(); // @property-read string long name of month translated according to Carbon locale, in english if no translation available for current language case $name === 'monthName': return $this->getTranslatedMonthName(); // @property-read string short name of month translated according to Carbon locale, in english if no translation available for current language case $name === 'shortMonthName': return $this->getTranslatedShortMonthName(); // @property-read string lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language case $name === 'meridiem': return $this->meridiem(true); // @property-read string uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language case $name === 'upperMeridiem': return $this->meridiem(); // @property-read int current hour from 1 to 24 case $name === 'noZeroHour': return $this->hour ?: 24; // @property int case $name === 'milliseconds': // @property int case $name === 'millisecond': // @property int case $name === 'milli': return (int) floor(((int) $this->rawFormat('u')) / 1000); // @property int 1 through 53 case $name === 'week': return (int) $this->week(); // @property int 1 through 53 case $name === 'isoWeek': return (int) $this->isoWeek(); // @property int year according to week format case $name === 'weekYear': return (int) $this->weekYear(); // @property int year according to ISO week format case $name === 'isoWeekYear': return (int) $this->isoWeekYear(); // @property-read int 51 through 53 case $name === 'weeksInYear': return $this->weeksInYear(); // @property-read int 51 through 53 case $name === 'isoWeeksInYear': return $this->isoWeeksInYear(); // @property int 1 through 5 case $name === 'weekOfMonth': return (int) ceil($this->day / static::DAYS_PER_WEEK); // @property-read int 1 through 5 case $name === 'weekNumberInMonth': return (int) ceil(($this->day + $this->avoidMutation()->startOfMonth()->dayOfWeekIso - 1) / static::DAYS_PER_WEEK); // @property-read int 0 through 6 case $name === 'firstWeekDay': return (int) $this->getTranslationMessage('first_day_of_week'); // @property-read int 0 through 6 case $name === 'lastWeekDay': return $this->transmitFactory(fn () => static::weekRotate((int) $this->getTranslationMessage('first_day_of_week'), -1)); // @property int 1 through 366 case $name === 'dayOfYear': return 1 + (int) ($this->rawFormat('z')); // @property-read int 365 or 366 case $name === 'daysInYear': return static::DAYS_PER_YEAR + ($this->isLeapYear() ? 1 : 0); // @property int does a diffInYears() with default parameters case $name === 'age': return (int) $this->diffInYears(); // @property-read int the quarter of this instance, 1 - 4 case $name === 'quarter': return (int) ceil($this->month / static::MONTHS_PER_QUARTER); // @property-read int the decade of this instance // @call isSameUnit case $name === 'decade': return (int) ceil($this->year / static::YEARS_PER_DECADE); // @property-read int the century of this instance // @call isSameUnit case $name === 'century': $factor = 1; $year = $this->year; if ($year < 0) { $year = -$year; $factor = -1; } return (int) ($factor * ceil($year / static::YEARS_PER_CENTURY)); // @property-read int the millennium of this instance // @call isSameUnit case $name === 'millennium': $factor = 1; $year = $this->year; if ($year < 0) { $year = -$year; $factor = -1; } return (int) ($factor * ceil($year / static::YEARS_PER_MILLENNIUM)); // @property int the timezone offset in seconds from UTC case $name === 'offset': return $this->getOffset(); // @property int the timezone offset in minutes from UTC case $name === 'offsetMinutes': return $this->getOffset() / static::SECONDS_PER_MINUTE; // @property int the timezone offset in hours from UTC case $name === 'offsetHours': return $this->getOffset() / static::SECONDS_PER_MINUTE / static::MINUTES_PER_HOUR; // @property-read bool daylight savings time indicator, true if DST, false otherwise case $name === 'dst': return $this->rawFormat('I') === '1'; // @property-read bool checks if the timezone is local, true if local, false otherwise case $name === 'local': return $this->getOffset() === $this->avoidMutation()->setTimezone(date_default_timezone_get())->getOffset(); // @property-read bool checks if the timezone is UTC, true if UTC, false otherwise case $name === 'utc': return $this->getOffset() === 0; // @--property-write DateTimeZone|string|int $timezone the current timezone // @--property-write DateTimeZone|string|int $tz alias of $timezone // @--property-read CarbonTimeZone $timezone the current timezone // @--property-read CarbonTimeZone $tz alias of $timezone // @property CarbonTimeZone $timezone the current timezone // @property CarbonTimeZone $tz alias of $timezone case $name === 'timezone' || $name === 'tz': return $this->getTimezone(); // @property-read string $timezoneName the current timezone name // @property-read string $tzName alias of $timezoneName case $name === 'timezoneName' || $name === 'tzName': return $this->getTimezone()->getName(); // @property-read string locale of the current instance case $name === 'locale': return $this->getTranslatorLocale(); case preg_match('/^([a-z]{2,})(In|Of)([A-Z][a-z]+)$/', $name, $match): [, $firstUnit, $operator, $secondUnit] = $match; try { $start = $this->avoidMutation()->startOf($secondUnit); $value = $operator === 'Of' ? (\in_array($firstUnit, [ // Unit with indexes starting at 1 (other units start at 0) 'day', 'week', 'month', 'quarter', ], true) ? 1 : 0) + floor($start->diffInUnit($firstUnit, $this)) : round($start->diffInUnit($firstUnit, $start->avoidMutation()->add($secondUnit, 1))); return (int) $value; } catch (UnknownUnitException) { // default to macro } default: $macro = $this->getLocalMacro('get'.ucfirst($name)); if ($macro) { return $this->executeCallableWithContext($macro); } throw new UnknownGetterException($name); } } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset($name) { try { $this->__get($name); } catch (UnknownGetterException | ReflectionException) { return false; } return true; } /** * Set a part of the Carbon object * * @param string $name * @param string|int|DateTimeZone $value * * @throws UnknownSetterException|ReflectionException * * @return void */ public function __set($name, $value) { if ($this->constructedObjectId === spl_object_hash($this)) { $this->set($name, $value); return; } $this->$name = $value; } /** * Set a part of the Carbon object. * * @throws ImmutableException|UnknownSetterException * * @return $this */ public function set(Unit|array|string $name, DateTimeZone|Month|string|int|float|null $value = null): static { if ($this->isImmutable()) { throw new ImmutableException(\sprintf('%s class', static::class)); } if (\is_array($name)) { foreach ($name as $key => $value) { $this->set($key, $value); } return $this; } $name = Unit::toName($name); switch ($name) { case 'milliseconds': case 'millisecond': case 'milli': case 'microseconds': case 'microsecond': case 'micro': if (str_starts_with($name, 'milli')) { $value *= 1000; } while ($value < 0) { $this->subSecond(); $value += static::MICROSECONDS_PER_SECOND; } while ($value >= static::MICROSECONDS_PER_SECOND) { $this->addSecond(); $value -= static::MICROSECONDS_PER_SECOND; } $this->modify($this->rawFormat('H:i:s.').str_pad((string) round($value), 6, '0', STR_PAD_LEFT)); break; case 'year': case 'month': case 'day': case 'hour': case 'minute': case 'second': [$year, $month, $day, $hour, $minute, $second] = array_map('intval', explode('-', $this->rawFormat('Y-n-j-G-i-s'))); $$name = self::monthToInt($value, $name); $this->setDateTime($year, $month, $day, $hour, $minute, $second); break; case 'week': $this->week($value); break; case 'isoWeek': $this->isoWeek($value); break; case 'weekYear': $this->weekYear($value); break; case 'isoWeekYear': $this->isoWeekYear($value); break; case 'dayOfYear': $this->addDays($value - $this->dayOfYear); break; case 'dayOfWeek': $this->addDays($value - $this->dayOfWeek); break; case 'dayOfWeekIso': $this->addDays($value - $this->dayOfWeekIso); break; case 'timestamp': $this->setTimestamp($value); break; case 'offset': $this->setTimezone(static::safeCreateDateTimeZone($value / static::SECONDS_PER_MINUTE / static::MINUTES_PER_HOUR)); break; case 'offsetMinutes': $this->setTimezone(static::safeCreateDateTimeZone($value / static::MINUTES_PER_HOUR)); break; case 'offsetHours': $this->setTimezone(static::safeCreateDateTimeZone($value)); break; case 'timezone': case 'tz': $this->setTimezone($value); break; default: if (preg_match('/^([a-z]{2,})Of([A-Z][a-z]+)$/', $name, $match)) { [, $firstUnit, $secondUnit] = $match; try { $start = $this->avoidMutation()->startOf($secondUnit); $currentValue = (\in_array($firstUnit, [ // Unit with indexes starting at 1 (other units start at 0) 'day', 'week', 'month', 'quarter', ], true) ? 1 : 0) + (int) floor($start->diffInUnit($firstUnit, $this)); // We check $value a posteriori to give precedence to UnknownUnitException if (!\is_int($value)) { throw new UnitException("->$name expects integer value"); } $this->addUnit($firstUnit, $value - $currentValue); break; } catch (UnknownUnitException) { // default to macro } } $macro = $this->getLocalMacro('set'.ucfirst($name)); if ($macro) { $this->executeCallableWithContext($macro, $value); break; } if ($this->isLocalStrictModeEnabled()) { throw new UnknownSetterException($name); } $this->$name = $value; } return $this; } /** * Get the translation of the current week day name (with context for languages with multiple forms). * * @param string|null $context whole format string * @param string $keySuffix "", "_short" or "_min" * @param string|null $defaultValue default value if translation missing */ public function getTranslatedDayName( ?string $context = null, string $keySuffix = '', ?string $defaultValue = null, ): string { return $this->getTranslatedFormByRegExp('weekdays', $keySuffix, $context, $this->dayOfWeek, $defaultValue ?: $this->englishDayOfWeek); } /** * Get the translation of the current short week day name (with context for languages with multiple forms). * * @param string|null $context whole format string */ public function getTranslatedShortDayName(?string $context = null): string { return $this->getTranslatedDayName($context, '_short', $this->shortEnglishDayOfWeek); } /** * Get the translation of the current abbreviated week day name (with context for languages with multiple forms). * * @param string|null $context whole format string */ public function getTranslatedMinDayName(?string $context = null): string { return $this->getTranslatedDayName($context, '_min', $this->shortEnglishDayOfWeek); } /** * Get the translation of the current month day name (with context for languages with multiple forms). * * @param string|null $context whole format string * @param string $keySuffix "" or "_short" * @param string|null $defaultValue default value if translation missing */ public function getTranslatedMonthName( ?string $context = null, string $keySuffix = '', ?string $defaultValue = null, ): string { return $this->getTranslatedFormByRegExp('months', $keySuffix, $context, $this->month - 1, $defaultValue ?: $this->englishMonth); } /** * Get the translation of the current short month day name (with context for languages with multiple forms). * * @param string|null $context whole format string */ public function getTranslatedShortMonthName(?string $context = null): string { return $this->getTranslatedMonthName($context, '_short', $this->shortEnglishMonth); } /** * Get/set the day of year. * * @template T of int|null * * @param int|null $value new value for day of year if using as setter. * * @psalm-param T $value * * @return static|int * * @psalm-return (T is int ? static : int) */ public function dayOfYear(?int $value = null): static|int { $dayOfYear = $this->dayOfYear; return $value === null ? $dayOfYear : $this->addDays($value - $dayOfYear); } /** * Get/set the weekday from 0 (Sunday) to 6 (Saturday). * * @param WeekDay|int|null $value new value for weekday if using as setter. */ public function weekday(WeekDay|int|null $value = null): static|int { if ($value === null) { return $this->dayOfWeek; } $firstDay = (int) ($this->getTranslationMessage('first_day_of_week') ?? 0); $dayOfWeek = ($this->dayOfWeek + 7 - $firstDay) % 7; return $this->addDays(((WeekDay::int($value) + 7 - $firstDay) % 7) - $dayOfWeek); } /** * Get/set the ISO weekday from 1 (Monday) to 7 (Sunday). * * @param WeekDay|int|null $value new value for weekday if using as setter. */ public function isoWeekday(WeekDay|int|null $value = null): static|int { $dayOfWeekIso = $this->dayOfWeekIso; return $value === null ? $dayOfWeekIso : $this->addDays(WeekDay::int($value) - $dayOfWeekIso); } /** * Return the number of days since the start of the week (using the current locale or the first parameter * if explicitly given). * * @param WeekDay|int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week, * if not provided, start of week is inferred from the locale * (Sunday for en_US, Monday for de_DE, etc.) */ public function getDaysFromStartOfWeek(WeekDay|int|null $weekStartsAt = null): int { $firstDay = (int) (WeekDay::int($weekStartsAt) ?? $this->getTranslationMessage('first_day_of_week') ?? 0); return ($this->dayOfWeek + 7 - $firstDay) % 7; } /** * Set the day (keeping the current time) to the start of the week + the number of days passed as the first * parameter. First day of week is driven by the locale unless explicitly set with the second parameter. * * @param int $numberOfDays number of days to add after the start of the current week * @param WeekDay|int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week, * if not provided, start of week is inferred from the locale * (Sunday for en_US, Monday for de_DE, etc.) */ public function setDaysFromStartOfWeek(int $numberOfDays, WeekDay|int|null $weekStartsAt = null): static { return $this->addDays($numberOfDays - $this->getDaysFromStartOfWeek(WeekDay::int($weekStartsAt))); } /** * Set any unit to a new value without overflowing current other unit given. * * @param string $valueUnit unit name to modify * @param int $value new value for the input unit * @param string $overflowUnit unit name to not overflow */ public function setUnitNoOverflow(string $valueUnit, int $value, string $overflowUnit): static { try { $start = $this->avoidMutation()->startOf($overflowUnit); $end = $this->avoidMutation()->endOf($overflowUnit); /** @var static $date */ $date = $this->$valueUnit($value); if ($date < $start) { return $date->mutateIfMutable($start); } if ($date > $end) { return $date->mutateIfMutable($end); } return $date; } catch (BadMethodCallException | ReflectionException $exception) { throw new UnknownUnitException($valueUnit, 0, $exception); } } /** * Add any unit to a new value without overflowing current other unit given. * * @param string $valueUnit unit name to modify * @param int $value amount to add to the input unit * @param string $overflowUnit unit name to not overflow */ public function addUnitNoOverflow(string $valueUnit, int $value, string $overflowUnit): static { return $this->setUnitNoOverflow($valueUnit, $this->$valueUnit + $value, $overflowUnit); } /** * Subtract any unit to a new value without overflowing current other unit given. * * @param string $valueUnit unit name to modify * @param int $value amount to subtract to the input unit * @param string $overflowUnit unit name to not overflow */ public function subUnitNoOverflow(string $valueUnit, int $value, string $overflowUnit): static { return $this->setUnitNoOverflow($valueUnit, $this->$valueUnit - $value, $overflowUnit); } /** * Returns the minutes offset to UTC if no arguments passed, else set the timezone with given minutes shift passed. */ public function utcOffset(?int $minuteOffset = null): static|int { if ($minuteOffset === null) { return $this->offsetMinutes; } return $this->setTimezone(CarbonTimeZone::createFromMinuteOffset($minuteOffset)); } /** * Set the date with gregorian year, month and day numbers. * * @see https://php.net/manual/en/datetime.setdate.php */ public function setDate(int $year, int $month, int $day): static { return parent::setDate($year, $month, $day); } /** * Set a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates. * * @see https://php.net/manual/en/datetime.setisodate.php */ public function setISODate(int $year, int $week, int $day = 1): static { return parent::setISODate($year, $week, $day); } /** * Set the date and time all together. */ public function setDateTime( int $year, int $month, int $day, int $hour, int $minute, int $second = 0, int $microseconds = 0, ): static { return $this->setDate($year, $month, $day)->setTime($hour, $minute, $second, $microseconds); } /** * Resets the current time of the DateTime object to a different time. * * @see https://php.net/manual/en/datetime.settime.php */ public function setTime(int $hour, int $minute, int $second = 0, int $microseconds = 0): static { return parent::setTime($hour, $minute, $second, $microseconds); } /** * Set the instance's timestamp. * * Timestamp input can be given as int, float or a string containing one or more numbers. */ public function setTimestamp(float|int|string $timestamp): static { [$seconds, $microseconds] = self::getIntegerAndDecimalParts($timestamp); return parent::setTimestamp((int) $seconds)->setMicroseconds((int) $microseconds); } /** * Set the time by time string. */ public function setTimeFromTimeString(string $time): static { if (!str_contains($time, ':')) { $time .= ':0'; } return $this->modify($time); } /** * @alias setTimezone */ public function timezone(DateTimeZone|string|int $value): static { return $this->setTimezone($value); } /** * Set the timezone or returns the timezone name if no arguments passed. * * @return ($value is null ? string : static) */ public function tz(DateTimeZone|string|int|null $value = null): static|string { if ($value === null) { return $this->tzName; } return $this->setTimezone($value); } /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timeZone): static { return parent::setTimezone(static::safeCreateDateTimeZone($timeZone)); } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string $value): static { $dateTimeString = $this->format('Y-m-d H:i:s.u'); return $this ->setTimezone($value) ->modify($dateTimeString); } /** * Set the instance's timezone to UTC. */ public function utc(): static { return $this->setTimezone('UTC'); } /** * Set the year, month, and date for this instance to that of the passed instance. */ public function setDateFrom(DateTimeInterface|string $date): static { $date = $this->resolveCarbon($date); return $this->setDate($date->year, $date->month, $date->day); } /** * Set the hour, minute, second and microseconds for this instance to that of the passed instance. */ public function setTimeFrom(DateTimeInterface|string $date): static { $date = $this->resolveCarbon($date); return $this->setTime($date->hour, $date->minute, $date->second, $date->microsecond); } /** * Set the date and time for this instance to that of the passed instance. */ public function setDateTimeFrom(DateTimeInterface|string $date): static { $date = $this->resolveCarbon($date); return $this->modify($date->rawFormat('Y-m-d H:i:s.u')); } /** * Get the days of the week. */ public static function getDays(): array { return static::$days; } /////////////////////////////////////////////////////////////////// /////////////////////// WEEK SPECIAL DAYS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Get the first day of week. * * @return int */ public static function getWeekStartsAt(?string $locale = null): int { return (int) static::getTranslationMessageWith( $locale ? Translator::get($locale) : static::getTranslator(), 'first_day_of_week', ); } /** * Get the last day of week. * * @param string $locale local to consider the last day of week. * * @return int */ public static function getWeekEndsAt(?string $locale = null): int { return static::weekRotate(static::getWeekStartsAt($locale), -1); } /** * Get weekend days */ public static function getWeekendDays(): array { return FactoryImmutable::getInstance()->getWeekendDays(); } /** * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. * You should rather consider week-end is always saturday and sunday, and if you have some custom * week-end days to handle, give to those days an other name and create a macro for them: * * ``` * Carbon::macro('isDayOff', function ($date) { * return $date->isSunday() || $date->isMonday(); * }); * Carbon::macro('isNotDayOff', function ($date) { * return !$date->isDayOff(); * }); * if ($someDate->isDayOff()) ... * if ($someDate->isNotDayOff()) ... * // Add 5 not-off days * $count = 5; * while ($someDate->isDayOff() || ($count-- > 0)) { * $someDate->addDay(); * } * ``` * * Set weekend days */ public static function setWeekendDays(array $days): void { FactoryImmutable::getDefaultInstance()->setWeekendDays($days); } /** * Determine if a time string will produce a relative date. * * @return bool true if time match a relative date, false if absolute or invalid time string */ public static function hasRelativeKeywords(?string $time): bool { if (!$time || strtotime($time) === false) { return false; } $date1 = new DateTime('2000-01-01T00:00:00Z'); $date1->modify($time); $date2 = new DateTime('2001-12-25T00:00:00Z'); $date2->modify($time); return $date1 != $date2; } /////////////////////////////////////////////////////////////////// /////////////////////// STRING FORMATTING ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Returns list of locale formats for ISO formatting. * * @param string|null $locale current locale used if null */ public function getIsoFormats(?string $locale = null): array { return [ 'LT' => $this->getTranslationMessage('formats.LT', $locale), 'LTS' => $this->getTranslationMessage('formats.LTS', $locale), 'L' => $this->getTranslationMessage('formats.L', $locale), 'LL' => $this->getTranslationMessage('formats.LL', $locale), 'LLL' => $this->getTranslationMessage('formats.LLL', $locale), 'LLLL' => $this->getTranslationMessage('formats.LLLL', $locale), 'l' => $this->getTranslationMessage('formats.l', $locale), 'll' => $this->getTranslationMessage('formats.ll', $locale), 'lll' => $this->getTranslationMessage('formats.lll', $locale), 'llll' => $this->getTranslationMessage('formats.llll', $locale), ]; } /** * Returns list of calendar formats for ISO formatting. * * @param string|null $locale current locale used if null */ public function getCalendarFormats(?string $locale = null): array { return [ 'sameDay' => $this->getTranslationMessage('calendar.sameDay', $locale, '[Today at] LT'), 'nextDay' => $this->getTranslationMessage('calendar.nextDay', $locale, '[Tomorrow at] LT'), 'nextWeek' => $this->getTranslationMessage('calendar.nextWeek', $locale, 'dddd [at] LT'), 'lastDay' => $this->getTranslationMessage('calendar.lastDay', $locale, '[Yesterday at] LT'), 'lastWeek' => $this->getTranslationMessage('calendar.lastWeek', $locale, '[Last] dddd [at] LT'), 'sameElse' => $this->getTranslationMessage('calendar.sameElse', $locale, 'L'), ]; } /** * Returns list of locale units for ISO formatting. */ public static function getIsoUnits(): array { static $units = null; $units ??= [ 'OD' => ['getAltNumber', ['day']], 'OM' => ['getAltNumber', ['month']], 'OY' => ['getAltNumber', ['year']], 'OH' => ['getAltNumber', ['hour']], 'Oh' => ['getAltNumber', ['h']], 'Om' => ['getAltNumber', ['minute']], 'Os' => ['getAltNumber', ['second']], 'D' => 'day', 'DD' => ['rawFormat', ['d']], 'Do' => ['ordinal', ['day', 'D']], 'd' => 'dayOfWeek', 'dd' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedMinDayName( $originalFormat, ), 'ddd' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedShortDayName( $originalFormat, ), 'dddd' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedDayName( $originalFormat, ), 'DDD' => 'dayOfYear', 'DDDD' => ['getPaddedUnit', ['dayOfYear', 3]], 'DDDo' => ['ordinal', ['dayOfYear', 'DDD']], 'e' => ['weekday', []], 'E' => 'dayOfWeekIso', 'H' => ['rawFormat', ['G']], 'HH' => ['rawFormat', ['H']], 'h' => ['rawFormat', ['g']], 'hh' => ['rawFormat', ['h']], 'k' => 'noZeroHour', 'kk' => ['getPaddedUnit', ['noZeroHour']], 'hmm' => ['rawFormat', ['gi']], 'hmmss' => ['rawFormat', ['gis']], 'Hmm' => ['rawFormat', ['Gi']], 'Hmmss' => ['rawFormat', ['Gis']], 'm' => 'minute', 'mm' => ['rawFormat', ['i']], 'a' => 'meridiem', 'A' => 'upperMeridiem', 's' => 'second', 'ss' => ['getPaddedUnit', ['second']], 'S' => static fn (CarbonInterface $date) => (string) floor($date->micro / 100000), 'SS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 10000, 2), 'SSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 1000, 3), 'SSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 100, 4), 'SSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 10, 5), 'SSSSSS' => ['getPaddedUnit', ['micro', 6]], 'SSSSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro * 10, 7), 'SSSSSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro * 100, 8), 'SSSSSSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro * 1000, 9), 'M' => 'month', 'MM' => ['rawFormat', ['m']], 'MMM' => static function (CarbonInterface $date, $originalFormat = null) { $month = $date->getTranslatedShortMonthName($originalFormat); $suffix = $date->getTranslationMessage('mmm_suffix'); if ($suffix && $month !== $date->monthName) { $month .= $suffix; } return $month; }, 'MMMM' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedMonthName( $originalFormat, ), 'Mo' => ['ordinal', ['month', 'M']], 'Q' => 'quarter', 'Qo' => ['ordinal', ['quarter', 'M']], 'G' => 'isoWeekYear', 'GG' => ['getPaddedUnit', ['isoWeekYear']], 'GGG' => ['getPaddedUnit', ['isoWeekYear', 3]], 'GGGG' => ['getPaddedUnit', ['isoWeekYear', 4]], 'GGGGG' => ['getPaddedUnit', ['isoWeekYear', 5]], 'g' => 'weekYear', 'gg' => ['getPaddedUnit', ['weekYear']], 'ggg' => ['getPaddedUnit', ['weekYear', 3]], 'gggg' => ['getPaddedUnit', ['weekYear', 4]], 'ggggg' => ['getPaddedUnit', ['weekYear', 5]], 'W' => 'isoWeek', 'WW' => ['getPaddedUnit', ['isoWeek']], 'Wo' => ['ordinal', ['isoWeek', 'W']], 'w' => 'week', 'ww' => ['getPaddedUnit', ['week']], 'wo' => ['ordinal', ['week', 'w']], 'x' => ['valueOf', []], 'X' => 'timestamp', 'Y' => 'year', 'YY' => ['rawFormat', ['y']], 'YYYY' => ['getPaddedUnit', ['year', 4]], 'YYYYY' => ['getPaddedUnit', ['year', 5]], 'YYYYYY' => static fn (CarbonInterface $date) => ($date->year < 0 ? '' : '+'). $date->getPaddedUnit('year', 6), 'z' => ['rawFormat', ['T']], 'zz' => 'tzName', 'Z' => ['getOffsetString', []], 'ZZ' => ['getOffsetString', ['']], ]; return $units; } /** * Returns a unit of the instance padded with 0 by default or any other string if specified. * * @param string $unit Carbon unit name * @param int $length Length of the output (2 by default) * @param string $padString String to use for padding ("0" by default) * @param int $padType Side(s) to pad (STR_PAD_LEFT by default) */ public function getPaddedUnit($unit, $length = 2, $padString = '0', $padType = STR_PAD_LEFT): string { return ($this->$unit < 0 ? '-' : '').str_pad((string) abs($this->$unit), $length, $padString, $padType); } /** * Return a property with its ordinal. */ public function ordinal(string $key, ?string $period = null): string { $number = $this->$key; $result = $this->translate('ordinal', [ ':number' => $number, ':period' => (string) $period, ]); return (string) ($result === 'ordinal' ? $number : $result); } /** * Return the meridiem of the current time in the current locale. * * @param bool $isLower if true, returns lowercase variant if available in the current locale. */ public function meridiem(bool $isLower = false): string { $hour = $this->hour; $index = $hour < static::HOURS_PER_DAY / 2 ? 0 : 1; if ($isLower) { $key = 'meridiem.'.($index + 2); $result = $this->translate($key); if ($result !== $key) { return $result; } } $key = "meridiem.$index"; $result = $this->translate($key); if ($result === $key) { $result = $this->translate('meridiem', [ ':hour' => $this->hour, ':minute' => $this->minute, ':isLower' => $isLower, ]); if ($result === 'meridiem') { return $isLower ? $this->latinMeridiem : $this->latinUpperMeridiem; } } elseif ($isLower) { $result = mb_strtolower($result); } return $result; } /** * Returns the alternative number for a given date property if available in the current locale. * * @param string $key date property */ public function getAltNumber(string $key): string { return $this->translateNumber((int) (\strlen($key) > 1 ? $this->$key : $this->rawFormat($key))); } /** * Format in the current language using ISO replacement patterns. * * @param string|null $originalFormat provide context if a chunk has been passed alone */ public function isoFormat(string $format, ?string $originalFormat = null): string { $result = ''; $length = mb_strlen($format); $originalFormat ??= $format; $inEscaped = false; $formats = null; $units = null; for ($i = 0; $i < $length; $i++) { $char = mb_substr($format, $i, 1); if ($char === '\\') { $result .= mb_substr($format, ++$i, 1); continue; } if ($char === '[' && !$inEscaped) { $inEscaped = true; continue; } if ($char === ']' && $inEscaped) { $inEscaped = false; continue; } if ($inEscaped) { $result .= $char; continue; } $input = mb_substr($format, $i); if (preg_match('/^(LTS|LT|l{1,4}|L{1,4})/', $input, $match)) { if ($formats === null) { $formats = $this->getIsoFormats(); } $code = $match[0]; $sequence = $formats[$code] ?? preg_replace_callback( '/MMMM|MM|DD|dddd/', static fn ($code) => mb_substr($code[0], 1), $formats[strtoupper($code)] ?? '', ); $rest = mb_substr($format, $i + mb_strlen($code)); $format = mb_substr($format, 0, $i).$sequence.$rest; $length = mb_strlen($format); $input = $sequence.$rest; } if (preg_match('/^'.CarbonInterface::ISO_FORMAT_REGEXP.'/', $input, $match)) { $code = $match[0]; if ($units === null) { $units = static::getIsoUnits(); } $sequence = $units[$code] ?? ''; if ($sequence instanceof Closure) { $sequence = $sequence($this, $originalFormat); } elseif (\is_array($sequence)) { try { $sequence = $this->{$sequence[0]}(...$sequence[1]); } catch (ReflectionException | InvalidArgumentException | BadMethodCallException) { $sequence = ''; } } elseif (\is_string($sequence)) { $sequence = $this->$sequence ?? $code; } $format = mb_substr($format, 0, $i).$sequence.mb_substr($format, $i + mb_strlen($code)); $i += mb_strlen((string) $sequence) - 1; $length = mb_strlen($format); $char = $sequence; } $result .= $char; } return $result; } /** * List of replacements from date() format to isoFormat(). */ public static function getFormatsToIsoReplacements(): array { static $replacements = null; $replacements ??= [ 'd' => true, 'D' => 'ddd', 'j' => true, 'l' => 'dddd', 'N' => true, 'S' => static fn ($date) => str_replace((string) $date->rawFormat('j'), '', $date->isoFormat('Do')), 'w' => true, 'z' => true, 'W' => true, 'F' => 'MMMM', 'm' => true, 'M' => 'MMM', 'n' => true, 't' => true, 'L' => true, 'o' => true, 'Y' => true, 'y' => true, 'a' => 'a', 'A' => 'A', 'B' => true, 'g' => true, 'G' => true, 'h' => true, 'H' => true, 'i' => true, 's' => true, 'u' => true, 'v' => true, 'E' => true, 'I' => true, 'O' => true, 'P' => true, 'Z' => true, 'c' => true, 'r' => true, 'U' => true, 'T' => true, ]; return $replacements; } /** * Format as ->format() do (using date replacements patterns from https://php.net/manual/en/function.date.php) * but translate words whenever possible (months, day names, etc.) using the current locale. */ public function translatedFormat(string $format): string { $replacements = static::getFormatsToIsoReplacements(); $context = ''; $isoFormat = ''; $length = mb_strlen($format); for ($i = 0; $i < $length; $i++) { $char = mb_substr($format, $i, 1); if ($char === '\\') { $replacement = mb_substr($format, $i, 2); $isoFormat .= $replacement; $i++; continue; } if (!isset($replacements[$char])) { $replacement = preg_match('/^[A-Za-z]$/', $char) ? "\\$char" : $char; $isoFormat .= $replacement; $context .= $replacement; continue; } $replacement = $replacements[$char]; if ($replacement === true) { static $contextReplacements = null; if ($contextReplacements === null) { $contextReplacements = [ 'm' => 'MM', 'd' => 'DD', 't' => 'D', 'j' => 'D', 'N' => 'e', 'w' => 'e', 'n' => 'M', 'o' => 'YYYY', 'Y' => 'YYYY', 'y' => 'YY', 'g' => 'h', 'G' => 'H', 'h' => 'hh', 'H' => 'HH', 'i' => 'mm', 's' => 'ss', ]; } $isoFormat .= '['.$this->rawFormat($char).']'; $context .= $contextReplacements[$char] ?? ' '; continue; } if ($replacement instanceof Closure) { $replacement = '['.$replacement($this).']'; $isoFormat .= $replacement; $context .= $replacement; continue; } $isoFormat .= $replacement; $context .= $replacement; } return $this->isoFormat($isoFormat, $context); } /** * Returns the offset hour and minute formatted with +/- and a given separator (":" by default). * For example, if the time zone is 9 hours 30 minutes, you'll get "+09:30", with "@@" as first * argument, "+09@@30", with "" as first argument, "+0930". Negative offset will return something * like "-12:00". * * @param string $separator string to place between hours and minutes (":" by default) */ public function getOffsetString(string $separator = ':'): string { $second = $this->getOffset(); $symbol = $second < 0 ? '-' : '+'; $minute = abs($second) / static::SECONDS_PER_MINUTE; $hour = self::floorZeroPad($minute / static::MINUTES_PER_HOUR, 2); $minute = self::floorZeroPad(((int) $minute) % static::MINUTES_PER_HOUR, 2); return "$symbol$hour$separator$minute"; } /** * Dynamically handle calls to the class. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadMethodCallException */ public static function __callStatic(string $method, array $parameters): mixed { if (!static::hasMacro($method)) { foreach (static::getGenericMacros() as $callback) { try { return static::executeStaticCallable($callback, $method, ...$parameters); } catch (BadMethodCallException) { continue; } } if (static::isStrictModeEnabled()) { throw new UnknownMethodException(\sprintf('%s::%s', static::class, $method)); } return null; } return static::executeStaticCallable(static::getMacro($method), ...$parameters); } /** * Set specified unit to new given value. * * @param string $unit year, month, day, hour, minute, second or microsecond * @param Month|int $value new value for given unit */ public function setUnit(string $unit, Month|int|float|null $value = null): static { if (\is_float($value)) { $int = (int) $value; if ((float) $int !== $value) { throw new InvalidArgumentException( "$unit cannot be changed to float value $value, integer expected", ); } $value = $int; } $unit = static::singularUnit($unit); $value = self::monthToInt($value, $unit); $dateUnits = ['year', 'month', 'day']; if (\in_array($unit, $dateUnits)) { return $this->setDate(...array_map( fn ($name) => (int) ($name === $unit ? $value : $this->$name), $dateUnits, )); } $units = ['hour', 'minute', 'second', 'micro']; if ($unit === 'millisecond' || $unit === 'milli') { $value *= 1000; $unit = 'micro'; } elseif ($unit === 'microsecond') { $unit = 'micro'; } return $this->setTime(...array_map( fn ($name) => (int) ($name === $unit ? $value : $this->$name), $units, )); } /** * Returns standardized singular of a given singular/plural unit name (in English). */ public static function singularUnit(string $unit): string { $unit = rtrim(mb_strtolower($unit), 's'); return match ($unit) { 'centurie' => 'century', 'millennia' => 'millennium', default => $unit, }; } /** * Returns standardized plural of a given singular/plural unit name (in English). */ public static function pluralUnit(string $unit): string { $unit = rtrim(strtolower($unit), 's'); return match ($unit) { 'century' => 'centuries', 'millennium', 'millennia' => 'millennia', default => "{$unit}s", }; } public static function sleep(int|float $seconds): void { if (static::hasTestNow()) { static::setTestNow(static::getTestNow()->avoidMutation()->addSeconds($seconds)); return; } (new NativeClock('UTC'))->sleep($seconds); } /** * Dynamically handle calls to the class. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws UnknownMethodException|BadMethodCallException|ReflectionException|Throwable */ public function __call(string $method, array $parameters): mixed { $unit = rtrim($method, 's'); return $this->callDiffAlias($unit, $parameters) ?? $this->callHumanDiffAlias($unit, $parameters) ?? $this->callRoundMethod($unit, $parameters) ?? $this->callIsMethod($unit, $parameters) ?? $this->callModifierMethod($unit, $parameters) ?? $this->callPeriodMethod($method, $parameters) ?? $this->callGetOrSetMethod($method, $parameters) ?? $this->callMacroMethod($method, $parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. */ protected function resolveCarbon(DateTimeInterface|string|null $date): self { if (!$date) { return $this->nowWithSameTz(); } if (\is_string($date)) { return $this->transmitFactory(fn () => static::parse($date, $this->getTimezone())); } return $date instanceof self ? $date : $this->transmitFactory(static fn () => static::instance($date)); } protected static function weekRotate(int $day, int $rotation): int { return (static::DAYS_PER_WEEK + $rotation % static::DAYS_PER_WEEK + $day) % static::DAYS_PER_WEEK; } protected function executeCallable(callable $macro, ...$parameters) { if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return \call_user_func_array($boundMacro ?: $macro, $parameters); } return \call_user_func_array($macro, $parameters); } protected function executeCallableWithContext(callable $macro, ...$parameters) { return static::bindMacroContext($this, function () use (&$macro, &$parameters) { return $this->executeCallable($macro, ...$parameters); }); } protected function getAllGenericMacros(): Generator { yield from $this->localGenericMacros ?? []; yield from $this->transmitFactory(static fn () => static::getGenericMacros()); } protected static function getGenericMacros(): Generator { foreach ((FactoryImmutable::getInstance()->getSettings()['genericMacros'] ?? []) as $list) { foreach ($list as $macro) { yield $macro; } } } protected static function executeStaticCallable(callable $macro, ...$parameters) { return static::bindMacroContext(null, function () use (&$macro, &$parameters) { if ($macro instanceof Closure) { $boundMacro = @Closure::bind($macro, null, static::class); return \call_user_func_array($boundMacro ?: $macro, $parameters); } return \call_user_func_array($macro, $parameters); }); } protected function getTranslatedFormByRegExp($baseKey, $keySuffix, $context, $subKey, $defaultValue) { $key = $baseKey.$keySuffix; $standaloneKey = $key.'_standalone'; $baseTranslation = $this->getTranslationMessage($key); if ($baseTranslation instanceof Closure) { return $baseTranslation($this, $context, $subKey) ?: $defaultValue; } if ( $this->getTranslationMessage("$standaloneKey.$subKey") && (!$context || (($regExp = $this->getTranslationMessage($baseKey.'_regexp')) && !preg_match($regExp, $context))) ) { $key = $standaloneKey; } return $this->getTranslationMessage("$key.$subKey", null, $defaultValue); } private function callGetOrSetMethod(string $method, array $parameters): mixed { if (preg_match('/^([a-z]{2,})(In|Of)([A-Z][a-z]+)$/', $method)) { $localStrictModeEnabled = $this->localStrictModeEnabled; $this->localStrictModeEnabled = true; try { return $this->callGetOrSet($method, $parameters[0] ?? null); } catch (UnknownGetterException|UnknownSetterException|ImmutableException) { // continue to macro } finally { $this->localStrictModeEnabled = $localStrictModeEnabled; } } return null; } private function callGetOrSet(string $name, mixed $value): mixed { if ($value !== null) { if (\is_string($value) || \is_int($value) || \is_float($value) || $value instanceof DateTimeZone || $value instanceof Month) { return $this->set($name, $value); } return null; } return $this->get($name); } private function getUTCUnit(string $unit): ?string { if (str_starts_with($unit, 'Real')) { return substr($unit, 4); } if (str_starts_with($unit, 'UTC')) { return substr($unit, 3); } return null; } private function callDiffAlias(string $method, array $parameters): mixed { if (preg_match('/^(diff|floatDiff)In(Real|UTC|Utc)?(.+)$/', $method, $match)) { $mode = strtoupper($match[2] ?? ''); $betterMethod = $match[1] === 'floatDiff' ? str_replace('floatDiff', 'diff', $method) : null; if ($mode === 'REAL') { $mode = 'UTC'; $betterMethod = str_replace($match[2], 'UTC', $betterMethod ?? $method); } if ($betterMethod) { @trigger_error( "Use the method $betterMethod instead to make it more explicit about what it does.\n". 'On next major version, "float" prefix will be removed (as all diff are now returning floating numbers)'. ' and "Real" methods will be removed in favor of "UTC" because what it actually does is to convert both'. ' dates to UTC timezone before comparison, while by default it does it only if both dates don\'t have'. ' exactly the same timezone (Note: 2 timezones with the same offset but different names are considered'. " different as it's not safe to assume they will always have the same offset).", \E_USER_DEPRECATED, ); } $unit = self::pluralUnit($match[3]); $diffMethod = 'diffIn'.ucfirst($unit); if (\in_array($unit, ['days', 'weeks', 'months', 'quarters', 'years'])) { $parameters['utc'] = ($mode === 'UTC'); } if (method_exists($this, $diffMethod)) { return $this->$diffMethod(...$parameters); } } return null; } private function callHumanDiffAlias(string $method, array $parameters): ?string { $diffSizes = [ // @mode diffForHumans 'short' => true, // @mode diffForHumans 'long' => false, ]; $diffSyntaxModes = [ // @call diffForHumans 'Absolute' => CarbonInterface::DIFF_ABSOLUTE, // @call diffForHumans 'Relative' => CarbonInterface::DIFF_RELATIVE_AUTO, // @call diffForHumans 'RelativeToNow' => CarbonInterface::DIFF_RELATIVE_TO_NOW, // @call diffForHumans 'RelativeToOther' => CarbonInterface::DIFF_RELATIVE_TO_OTHER, ]; $sizePattern = implode('|', array_keys($diffSizes)); $syntaxPattern = implode('|', array_keys($diffSyntaxModes)); if (preg_match("/^(?<size>$sizePattern)(?<syntax>$syntaxPattern)DiffForHuman$/", $method, $match)) { $dates = array_filter($parameters, function ($parameter) { return $parameter instanceof DateTimeInterface; }); $other = null; if (\count($dates)) { $key = key($dates); $other = current($dates); array_splice($parameters, $key, 1); } return $this->diffForHumans($other, $diffSyntaxModes[$match['syntax']], $diffSizes[$match['size']], ...$parameters); } return null; } private function callIsMethod(string $unit, array $parameters): ?bool { if (!str_starts_with($unit, 'is')) { return null; } $word = substr($unit, 2); if (\in_array($word, static::$days, true)) { return $this->isDayOfWeek($word); } return match ($word) { // @call is Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) 'Utc', 'UTC' => $this->utc, // @call is Check if the current instance has non-UTC timezone. 'Local' => $this->local, // @call is Check if the current instance is a valid date. 'Valid' => $this->year !== 0, // @call is Check if the current instance is in a daylight saving time. 'DST' => $this->dst, default => $this->callComparatorMethod($word, $parameters), }; } private function callComparatorMethod(string $unit, array $parameters): ?bool { $start = substr($unit, 0, 4); $factor = -1; if ($start === 'Last') { $start = 'Next'; $factor = 1; } if ($start === 'Next') { $lowerUnit = strtolower(substr($unit, 4)); if (static::isModifiableUnit($lowerUnit)) { return $this->avoidMutation()->addUnit($lowerUnit, $factor, false)->isSameUnit($lowerUnit, ...($parameters ?: ['now'])); } } if ($start === 'Same') { try { return $this->isSameUnit(strtolower(substr($unit, 4)), ...$parameters); } catch (BadComparisonUnitException) { // Try next } } if (str_starts_with($unit, 'Current')) { try { return $this->isCurrentUnit(strtolower(substr($unit, 7))); } catch (BadComparisonUnitException | BadMethodCallException) { // Try next } } return null; } private function callModifierMethod(string $unit, array $parameters): ?static { $action = substr($unit, 0, 3); $overflow = null; if ($action === 'set') { $unit = strtolower(substr($unit, 3)); } if (\in_array($unit, static::$units, true)) { return $this->setUnit($unit, ...$parameters); } if ($action === 'add' || $action === 'sub') { $unit = substr($unit, 3); $utcUnit = $this->getUTCUnit($unit); if ($utcUnit) { $unit = static::singularUnit($utcUnit); return $this->{"{$action}UTCUnit"}($unit, ...$parameters); } if (preg_match('/^(Month|Quarter|Year|Decade|Century|Centurie|Millennium|Millennia)s?(No|With|Without|WithNo)Overflow$/', $unit, $match)) { $unit = $match[1]; $overflow = $match[2] === 'With'; } $unit = static::singularUnit($unit); } if (static::isModifiableUnit($unit)) { return $this->{"{$action}Unit"}($unit, $this->getMagicParameter($parameters, 0, 'value', 1), $overflow); } return null; } private function callPeriodMethod(string $method, array $parameters): ?CarbonPeriod { if (str_ends_with($method, 'Until')) { try { $unit = static::singularUnit(substr($method, 0, -5)); return $this->range( $this->getMagicParameter($parameters, 0, 'endDate', $this), $this->getMagicParameter($parameters, 1, 'factor', 1), $unit ); } catch (InvalidArgumentException) { // Try macros } } return null; } private function callMacroMethod(string $method, array $parameters): mixed { return static::bindMacroContext($this, function () use (&$method, &$parameters) { $macro = $this->getLocalMacro($method); if (!$macro) { foreach ($this->getAllGenericMacros() as $callback) { try { return $this->executeCallable($callback, $method, ...$parameters); } catch (BadMethodCallException) { continue; } } if ($this->isLocalStrictModeEnabled()) { throw new UnknownMethodException($method); } return null; } return $this->executeCallable($macro, ...$parameters); }); } private static function floorZeroPad(int|float $value, int $length): string { return str_pad((string) floor($value), $length, '0', STR_PAD_LEFT); } /** * @template T of CarbonInterface * * @param T $date * * @return T */ private function mutateIfMutable(CarbonInterface $date): CarbonInterface { return $this instanceof DateTimeImmutable ? $date : $this->modify('@'.$date->rawFormat('U.u'))->setTimezone($date->getTimezone()); } }
PHP
{ "end_line": 1999, "name": "hasRelativeKeywords", "signature": "public static function hasRelativeKeywords(?string $time): bool", "start_line": 1987 }
{ "class_name": "Date", "class_signature": "trait Date", "namespace": "Carbon\\Traits" }
meridiem
Carbon/src/Carbon/Traits/Date.php
public function meridiem(bool $isLower = false): string { $hour = $this->hour; $index = $hour < static::HOURS_PER_DAY / 2 ? 0 : 1; if ($isLower) { $key = 'meridiem.'.($index + 2); $result = $this->translate($key); if ($result !== $key) { return $result; } } $key = "meridiem.$index"; $result = $this->translate($key); if ($result === $key) { $result = $this->translate('meridiem', [ ':hour' => $this->hour, ':minute' => $this->minute, ':isLower' => $isLower, ]); if ($result === 'meridiem') { return $isLower ? $this->latinMeridiem : $this->latinUpperMeridiem; } } elseif ($isLower) { $result = mb_strtolower($result); } return $result; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use BadMethodCallException; use Carbon\Carbon; use Carbon\CarbonInterface; use Carbon\CarbonPeriod; use Carbon\CarbonTimeZone; use Carbon\Exceptions\BadComparisonUnitException; use Carbon\Exceptions\ImmutableException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Exceptions\UnitException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\FactoryImmutable; use Carbon\Month; use Carbon\Translator; use Carbon\Unit; use Carbon\WeekDay; use Closure; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use ReflectionException; use Symfony\Component\Clock\NativeClock; use Throwable; /** * A simple API extension for DateTime. * * <autodoc generated by `composer phpdoc`> * * @property string $localeDayOfWeek the day of week in current locale * @property string $shortLocaleDayOfWeek the abbreviated day of week in current locale * @property string $localeMonth the month in current locale * @property string $shortLocaleMonth the abbreviated month in current locale * @property int $year * @property int $yearIso * @property int $month * @property int $day * @property int $hour * @property int $minute * @property int $second * @property int $micro * @property int $microsecond * @property int $dayOfWeekIso 1 (for Monday) through 7 (for Sunday) * @property int|float|string $timestamp seconds since the Unix Epoch * @property string $englishDayOfWeek the day of week in English * @property string $shortEnglishDayOfWeek the abbreviated day of week in English * @property string $englishMonth the month in English * @property string $shortEnglishMonth the abbreviated month in English * @property int $milliseconds * @property int $millisecond * @property int $milli * @property int $week 1 through 53 * @property int $isoWeek 1 through 53 * @property int $weekYear year according to week format * @property int $isoWeekYear year according to ISO week format * @property int $age does a diffInYears() with default parameters * @property int $offset the timezone offset in seconds from UTC * @property int $offsetMinutes the timezone offset in minutes from UTC * @property int $offsetHours the timezone offset in hours from UTC * @property CarbonTimeZone $timezone the current timezone * @property CarbonTimeZone $tz alias of $timezone * @property int $centuryOfMillennium The value of the century starting from the beginning of the current millennium * @property int $dayOfCentury The value of the day starting from the beginning of the current century * @property int $dayOfDecade The value of the day starting from the beginning of the current decade * @property int $dayOfMillennium The value of the day starting from the beginning of the current millennium * @property int $dayOfMonth The value of the day starting from the beginning of the current month * @property int $dayOfQuarter The value of the day starting from the beginning of the current quarter * @property int $dayOfWeek 0 (for Sunday) through 6 (for Saturday) * @property int $dayOfYear 1 through 366 * @property int $decadeOfCentury The value of the decade starting from the beginning of the current century * @property int $decadeOfMillennium The value of the decade starting from the beginning of the current millennium * @property int $hourOfCentury The value of the hour starting from the beginning of the current century * @property int $hourOfDay The value of the hour starting from the beginning of the current day * @property int $hourOfDecade The value of the hour starting from the beginning of the current decade * @property int $hourOfMillennium The value of the hour starting from the beginning of the current millennium * @property int $hourOfMonth The value of the hour starting from the beginning of the current month * @property int $hourOfQuarter The value of the hour starting from the beginning of the current quarter * @property int $hourOfWeek The value of the hour starting from the beginning of the current week * @property int $hourOfYear The value of the hour starting from the beginning of the current year * @property int $microsecondOfCentury The value of the microsecond starting from the beginning of the current century * @property int $microsecondOfDay The value of the microsecond starting from the beginning of the current day * @property int $microsecondOfDecade The value of the microsecond starting from the beginning of the current decade * @property int $microsecondOfHour The value of the microsecond starting from the beginning of the current hour * @property int $microsecondOfMillennium The value of the microsecond starting from the beginning of the current millennium * @property int $microsecondOfMillisecond The value of the microsecond starting from the beginning of the current millisecond * @property int $microsecondOfMinute The value of the microsecond starting from the beginning of the current minute * @property int $microsecondOfMonth The value of the microsecond starting from the beginning of the current month * @property int $microsecondOfQuarter The value of the microsecond starting from the beginning of the current quarter * @property int $microsecondOfSecond The value of the microsecond starting from the beginning of the current second * @property int $microsecondOfWeek The value of the microsecond starting from the beginning of the current week * @property int $microsecondOfYear The value of the microsecond starting from the beginning of the current year * @property int $millisecondOfCentury The value of the millisecond starting from the beginning of the current century * @property int $millisecondOfDay The value of the millisecond starting from the beginning of the current day * @property int $millisecondOfDecade The value of the millisecond starting from the beginning of the current decade * @property int $millisecondOfHour The value of the millisecond starting from the beginning of the current hour * @property int $millisecondOfMillennium The value of the millisecond starting from the beginning of the current millennium * @property int $millisecondOfMinute The value of the millisecond starting from the beginning of the current minute * @property int $millisecondOfMonth The value of the millisecond starting from the beginning of the current month * @property int $millisecondOfQuarter The value of the millisecond starting from the beginning of the current quarter * @property int $millisecondOfSecond The value of the millisecond starting from the beginning of the current second * @property int $millisecondOfWeek The value of the millisecond starting from the beginning of the current week * @property int $millisecondOfYear The value of the millisecond starting from the beginning of the current year * @property int $minuteOfCentury The value of the minute starting from the beginning of the current century * @property int $minuteOfDay The value of the minute starting from the beginning of the current day * @property int $minuteOfDecade The value of the minute starting from the beginning of the current decade * @property int $minuteOfHour The value of the minute starting from the beginning of the current hour * @property int $minuteOfMillennium The value of the minute starting from the beginning of the current millennium * @property int $minuteOfMonth The value of the minute starting from the beginning of the current month * @property int $minuteOfQuarter The value of the minute starting from the beginning of the current quarter * @property int $minuteOfWeek The value of the minute starting from the beginning of the current week * @property int $minuteOfYear The value of the minute starting from the beginning of the current year * @property int $monthOfCentury The value of the month starting from the beginning of the current century * @property int $monthOfDecade The value of the month starting from the beginning of the current decade * @property int $monthOfMillennium The value of the month starting from the beginning of the current millennium * @property int $monthOfQuarter The value of the month starting from the beginning of the current quarter * @property int $monthOfYear The value of the month starting from the beginning of the current year * @property int $quarterOfCentury The value of the quarter starting from the beginning of the current century * @property int $quarterOfDecade The value of the quarter starting from the beginning of the current decade * @property int $quarterOfMillennium The value of the quarter starting from the beginning of the current millennium * @property int $quarterOfYear The value of the quarter starting from the beginning of the current year * @property int $secondOfCentury The value of the second starting from the beginning of the current century * @property int $secondOfDay The value of the second starting from the beginning of the current day * @property int $secondOfDecade The value of the second starting from the beginning of the current decade * @property int $secondOfHour The value of the second starting from the beginning of the current hour * @property int $secondOfMillennium The value of the second starting from the beginning of the current millennium * @property int $secondOfMinute The value of the second starting from the beginning of the current minute * @property int $secondOfMonth The value of the second starting from the beginning of the current month * @property int $secondOfQuarter The value of the second starting from the beginning of the current quarter * @property int $secondOfWeek The value of the second starting from the beginning of the current week * @property int $secondOfYear The value of the second starting from the beginning of the current year * @property int $weekOfCentury The value of the week starting from the beginning of the current century * @property int $weekOfDecade The value of the week starting from the beginning of the current decade * @property int $weekOfMillennium The value of the week starting from the beginning of the current millennium * @property int $weekOfMonth 1 through 5 * @property int $weekOfQuarter The value of the week starting from the beginning of the current quarter * @property int $weekOfYear ISO-8601 week number of year, weeks starting on Monday * @property int $yearOfCentury The value of the year starting from the beginning of the current century * @property int $yearOfDecade The value of the year starting from the beginning of the current decade * @property int $yearOfMillennium The value of the year starting from the beginning of the current millennium * @property-read string $latinMeridiem "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) * @property-read string $latinUpperMeridiem "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) * @property-read string $timezoneAbbreviatedName the current timezone abbreviated name * @property-read string $tzAbbrName alias of $timezoneAbbreviatedName * @property-read string $dayName long name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $shortDayName short name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $minDayName very short name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $monthName long name of month translated according to Carbon locale, in english if no translation available for current language * @property-read string $shortMonthName short name of month translated according to Carbon locale, in english if no translation available for current language * @property-read string $meridiem lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language * @property-read string $upperMeridiem uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language * @property-read int $noZeroHour current hour from 1 to 24 * @property-read int $isoWeeksInYear 51 through 53 * @property-read int $weekNumberInMonth 1 through 5 * @property-read int $firstWeekDay 0 through 6 * @property-read int $lastWeekDay 0 through 6 * @property-read int $quarter the quarter of this instance, 1 - 4 * @property-read int $decade the decade of this instance * @property-read int $century the century of this instance * @property-read int $millennium the millennium of this instance * @property-read bool $dst daylight savings time indicator, true if DST, false otherwise * @property-read bool $local checks if the timezone is local, true if local, false otherwise * @property-read bool $utc checks if the timezone is UTC, true if UTC, false otherwise * @property-read string $timezoneName the current timezone name * @property-read string $tzName alias of $timezoneName * @property-read string $locale locale of the current instance * @property-read int $centuriesInMillennium The number of centuries contained in the current millennium * @property-read int $daysInCentury The number of days contained in the current century * @property-read int $daysInDecade The number of days contained in the current decade * @property-read int $daysInMillennium The number of days contained in the current millennium * @property-read int $daysInMonth number of days in the given month * @property-read int $daysInQuarter The number of days contained in the current quarter * @property-read int $daysInWeek The number of days contained in the current week * @property-read int $daysInYear 365 or 366 * @property-read int $decadesInCentury The number of decades contained in the current century * @property-read int $decadesInMillennium The number of decades contained in the current millennium * @property-read int $hoursInCentury The number of hours contained in the current century * @property-read int $hoursInDay The number of hours contained in the current day * @property-read int $hoursInDecade The number of hours contained in the current decade * @property-read int $hoursInMillennium The number of hours contained in the current millennium * @property-read int $hoursInMonth The number of hours contained in the current month * @property-read int $hoursInQuarter The number of hours contained in the current quarter * @property-read int $hoursInWeek The number of hours contained in the current week * @property-read int $hoursInYear The number of hours contained in the current year * @property-read int $microsecondsInCentury The number of microseconds contained in the current century * @property-read int $microsecondsInDay The number of microseconds contained in the current day * @property-read int $microsecondsInDecade The number of microseconds contained in the current decade * @property-read int $microsecondsInHour The number of microseconds contained in the current hour * @property-read int $microsecondsInMillennium The number of microseconds contained in the current millennium * @property-read int $microsecondsInMillisecond The number of microseconds contained in the current millisecond * @property-read int $microsecondsInMinute The number of microseconds contained in the current minute * @property-read int $microsecondsInMonth The number of microseconds contained in the current month * @property-read int $microsecondsInQuarter The number of microseconds contained in the current quarter * @property-read int $microsecondsInSecond The number of microseconds contained in the current second * @property-read int $microsecondsInWeek The number of microseconds contained in the current week * @property-read int $microsecondsInYear The number of microseconds contained in the current year * @property-read int $millisecondsInCentury The number of milliseconds contained in the current century * @property-read int $millisecondsInDay The number of milliseconds contained in the current day * @property-read int $millisecondsInDecade The number of milliseconds contained in the current decade * @property-read int $millisecondsInHour The number of milliseconds contained in the current hour * @property-read int $millisecondsInMillennium The number of milliseconds contained in the current millennium * @property-read int $millisecondsInMinute The number of milliseconds contained in the current minute * @property-read int $millisecondsInMonth The number of milliseconds contained in the current month * @property-read int $millisecondsInQuarter The number of milliseconds contained in the current quarter * @property-read int $millisecondsInSecond The number of milliseconds contained in the current second * @property-read int $millisecondsInWeek The number of milliseconds contained in the current week * @property-read int $millisecondsInYear The number of milliseconds contained in the current year * @property-read int $minutesInCentury The number of minutes contained in the current century * @property-read int $minutesInDay The number of minutes contained in the current day * @property-read int $minutesInDecade The number of minutes contained in the current decade * @property-read int $minutesInHour The number of minutes contained in the current hour * @property-read int $minutesInMillennium The number of minutes contained in the current millennium * @property-read int $minutesInMonth The number of minutes contained in the current month * @property-read int $minutesInQuarter The number of minutes contained in the current quarter * @property-read int $minutesInWeek The number of minutes contained in the current week * @property-read int $minutesInYear The number of minutes contained in the current year * @property-read int $monthsInCentury The number of months contained in the current century * @property-read int $monthsInDecade The number of months contained in the current decade * @property-read int $monthsInMillennium The number of months contained in the current millennium * @property-read int $monthsInQuarter The number of months contained in the current quarter * @property-read int $monthsInYear The number of months contained in the current year * @property-read int $quartersInCentury The number of quarters contained in the current century * @property-read int $quartersInDecade The number of quarters contained in the current decade * @property-read int $quartersInMillennium The number of quarters contained in the current millennium * @property-read int $quartersInYear The number of quarters contained in the current year * @property-read int $secondsInCentury The number of seconds contained in the current century * @property-read int $secondsInDay The number of seconds contained in the current day * @property-read int $secondsInDecade The number of seconds contained in the current decade * @property-read int $secondsInHour The number of seconds contained in the current hour * @property-read int $secondsInMillennium The number of seconds contained in the current millennium * @property-read int $secondsInMinute The number of seconds contained in the current minute * @property-read int $secondsInMonth The number of seconds contained in the current month * @property-read int $secondsInQuarter The number of seconds contained in the current quarter * @property-read int $secondsInWeek The number of seconds contained in the current week * @property-read int $secondsInYear The number of seconds contained in the current year * @property-read int $weeksInCentury The number of weeks contained in the current century * @property-read int $weeksInDecade The number of weeks contained in the current decade * @property-read int $weeksInMillennium The number of weeks contained in the current millennium * @property-read int $weeksInMonth The number of weeks contained in the current month * @property-read int $weeksInQuarter The number of weeks contained in the current quarter * @property-read int $weeksInYear 51 through 53 * @property-read int $yearsInCentury The number of years contained in the current century * @property-read int $yearsInDecade The number of years contained in the current decade * @property-read int $yearsInMillennium The number of years contained in the current millennium * * @method bool isUtc() Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) * @method bool isLocal() Check if the current instance has non-UTC timezone. * @method bool isValid() Check if the current instance is a valid date. * @method bool isDST() Check if the current instance is in a daylight saving time. * @method bool isSunday() Checks if the instance day is sunday. * @method bool isMonday() Checks if the instance day is monday. * @method bool isTuesday() Checks if the instance day is tuesday. * @method bool isWednesday() Checks if the instance day is wednesday. * @method bool isThursday() Checks if the instance day is thursday. * @method bool isFriday() Checks if the instance day is friday. * @method bool isSaturday() Checks if the instance day is saturday. * @method bool isSameYear(DateTimeInterface|string $date) Checks if the given date is in the same year as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentYear() Checks if the instance is in the same year as the current moment. * @method bool isNextYear() Checks if the instance is in the same year as the current moment next year. * @method bool isLastYear() Checks if the instance is in the same year as the current moment last year. * @method bool isCurrentMonth() Checks if the instance is in the same month as the current moment. * @method bool isNextMonth() Checks if the instance is in the same month as the current moment next month. * @method bool isLastMonth() Checks if the instance is in the same month as the current moment last month. * @method bool isSameWeek(DateTimeInterface|string $date) Checks if the given date is in the same week as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentWeek() Checks if the instance is in the same week as the current moment. * @method bool isNextWeek() Checks if the instance is in the same week as the current moment next week. * @method bool isLastWeek() Checks if the instance is in the same week as the current moment last week. * @method bool isSameDay(DateTimeInterface|string $date) Checks if the given date is in the same day as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentDay() Checks if the instance is in the same day as the current moment. * @method bool isNextDay() Checks if the instance is in the same day as the current moment next day. * @method bool isLastDay() Checks if the instance is in the same day as the current moment last day. * @method bool isSameHour(DateTimeInterface|string $date) Checks if the given date is in the same hour as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentHour() Checks if the instance is in the same hour as the current moment. * @method bool isNextHour() Checks if the instance is in the same hour as the current moment next hour. * @method bool isLastHour() Checks if the instance is in the same hour as the current moment last hour. * @method bool isSameMinute(DateTimeInterface|string $date) Checks if the given date is in the same minute as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMinute() Checks if the instance is in the same minute as the current moment. * @method bool isNextMinute() Checks if the instance is in the same minute as the current moment next minute. * @method bool isLastMinute() Checks if the instance is in the same minute as the current moment last minute. * @method bool isSameSecond(DateTimeInterface|string $date) Checks if the given date is in the same second as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentSecond() Checks if the instance is in the same second as the current moment. * @method bool isNextSecond() Checks if the instance is in the same second as the current moment next second. * @method bool isLastSecond() Checks if the instance is in the same second as the current moment last second. * @method bool isSameMilli(DateTimeInterface|string $date) Checks if the given date is in the same millisecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMilli() Checks if the instance is in the same millisecond as the current moment. * @method bool isNextMilli() Checks if the instance is in the same millisecond as the current moment next millisecond. * @method bool isLastMilli() Checks if the instance is in the same millisecond as the current moment last millisecond. * @method bool isSameMillisecond(DateTimeInterface|string $date) Checks if the given date is in the same millisecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMillisecond() Checks if the instance is in the same millisecond as the current moment. * @method bool isNextMillisecond() Checks if the instance is in the same millisecond as the current moment next millisecond. * @method bool isLastMillisecond() Checks if the instance is in the same millisecond as the current moment last millisecond. * @method bool isSameMicro(DateTimeInterface|string $date) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMicro() Checks if the instance is in the same microsecond as the current moment. * @method bool isNextMicro() Checks if the instance is in the same microsecond as the current moment next microsecond. * @method bool isLastMicro() Checks if the instance is in the same microsecond as the current moment last microsecond. * @method bool isSameMicrosecond(DateTimeInterface|string $date) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMicrosecond() Checks if the instance is in the same microsecond as the current moment. * @method bool isNextMicrosecond() Checks if the instance is in the same microsecond as the current moment next microsecond. * @method bool isLastMicrosecond() Checks if the instance is in the same microsecond as the current moment last microsecond. * @method bool isSameDecade(DateTimeInterface|string $date) Checks if the given date is in the same decade as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentDecade() Checks if the instance is in the same decade as the current moment. * @method bool isNextDecade() Checks if the instance is in the same decade as the current moment next decade. * @method bool isLastDecade() Checks if the instance is in the same decade as the current moment last decade. * @method bool isSameCentury(DateTimeInterface|string $date) Checks if the given date is in the same century as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentCentury() Checks if the instance is in the same century as the current moment. * @method bool isNextCentury() Checks if the instance is in the same century as the current moment next century. * @method bool isLastCentury() Checks if the instance is in the same century as the current moment last century. * @method bool isSameMillennium(DateTimeInterface|string $date) Checks if the given date is in the same millennium as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMillennium() Checks if the instance is in the same millennium as the current moment. * @method bool isNextMillennium() Checks if the instance is in the same millennium as the current moment next millennium. * @method bool isLastMillennium() Checks if the instance is in the same millennium as the current moment last millennium. * @method bool isCurrentQuarter() Checks if the instance is in the same quarter as the current moment. * @method bool isNextQuarter() Checks if the instance is in the same quarter as the current moment next quarter. * @method bool isLastQuarter() Checks if the instance is in the same quarter as the current moment last quarter. * @method CarbonInterface years(int $value) Set current instance year to the given value. * @method CarbonInterface year(int $value) Set current instance year to the given value. * @method CarbonInterface setYears(int $value) Set current instance year to the given value. * @method CarbonInterface setYear(int $value) Set current instance year to the given value. * @method CarbonInterface months(Month|int $value) Set current instance month to the given value. * @method CarbonInterface month(Month|int $value) Set current instance month to the given value. * @method CarbonInterface setMonths(Month|int $value) Set current instance month to the given value. * @method CarbonInterface setMonth(Month|int $value) Set current instance month to the given value. * @method CarbonInterface days(int $value) Set current instance day to the given value. * @method CarbonInterface day(int $value) Set current instance day to the given value. * @method CarbonInterface setDays(int $value) Set current instance day to the given value. * @method CarbonInterface setDay(int $value) Set current instance day to the given value. * @method CarbonInterface hours(int $value) Set current instance hour to the given value. * @method CarbonInterface hour(int $value) Set current instance hour to the given value. * @method CarbonInterface setHours(int $value) Set current instance hour to the given value. * @method CarbonInterface setHour(int $value) Set current instance hour to the given value. * @method CarbonInterface minutes(int $value) Set current instance minute to the given value. * @method CarbonInterface minute(int $value) Set current instance minute to the given value. * @method CarbonInterface setMinutes(int $value) Set current instance minute to the given value. * @method CarbonInterface setMinute(int $value) Set current instance minute to the given value. * @method CarbonInterface seconds(int $value) Set current instance second to the given value. * @method CarbonInterface second(int $value) Set current instance second to the given value. * @method CarbonInterface setSeconds(int $value) Set current instance second to the given value. * @method CarbonInterface setSecond(int $value) Set current instance second to the given value. * @method CarbonInterface millis(int $value) Set current instance millisecond to the given value. * @method CarbonInterface milli(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMillis(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMilli(int $value) Set current instance millisecond to the given value. * @method CarbonInterface milliseconds(int $value) Set current instance millisecond to the given value. * @method CarbonInterface millisecond(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMilliseconds(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMillisecond(int $value) Set current instance millisecond to the given value. * @method CarbonInterface micros(int $value) Set current instance microsecond to the given value. * @method CarbonInterface micro(int $value) Set current instance microsecond to the given value. * @method CarbonInterface setMicros(int $value) Set current instance microsecond to the given value. * @method CarbonInterface setMicro(int $value) Set current instance microsecond to the given value. * @method CarbonInterface microseconds(int $value) Set current instance microsecond to the given value. * @method CarbonInterface microsecond(int $value) Set current instance microsecond to the given value. * @method CarbonInterface setMicroseconds(int $value) Set current instance microsecond to the given value. * @method self setMicrosecond(int $value) Set current instance microsecond to the given value. * @method CarbonInterface addYears(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addYear() Add one year to the instance (using date interval). * @method CarbonInterface subYears(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subYear() Sub one year to the instance (using date interval). * @method CarbonInterface addYearsWithOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addYearWithOverflow() Add one year to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subYearsWithOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subYearWithOverflow() Sub one year to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addYearsWithoutOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearWithoutOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearsWithoutOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearWithoutOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearsWithNoOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearWithNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearsWithNoOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearWithNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearsNoOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearsNoOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonths(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMonth() Add one month to the instance (using date interval). * @method CarbonInterface subMonths(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMonth() Sub one month to the instance (using date interval). * @method CarbonInterface addMonthsWithOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMonthWithOverflow() Add one month to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMonthsWithOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMonthWithOverflow() Sub one month to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMonthsWithoutOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthWithoutOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthsWithoutOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthWithoutOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthsWithNoOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthWithNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthsWithNoOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthWithNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthsNoOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthsNoOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDays(int|float $value = 1) Add days (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addDay() Add one day to the instance (using date interval). * @method CarbonInterface subDays(int|float $value = 1) Sub days (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subDay() Sub one day to the instance (using date interval). * @method CarbonInterface addHours(int|float $value = 1) Add hours (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addHour() Add one hour to the instance (using date interval). * @method CarbonInterface subHours(int|float $value = 1) Sub hours (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subHour() Sub one hour to the instance (using date interval). * @method CarbonInterface addMinutes(int|float $value = 1) Add minutes (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMinute() Add one minute to the instance (using date interval). * @method CarbonInterface subMinutes(int|float $value = 1) Sub minutes (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMinute() Sub one minute to the instance (using date interval). * @method CarbonInterface addSeconds(int|float $value = 1) Add seconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addSecond() Add one second to the instance (using date interval). * @method CarbonInterface subSeconds(int|float $value = 1) Sub seconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subSecond() Sub one second to the instance (using date interval). * @method CarbonInterface addMillis(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMilli() Add one millisecond to the instance (using date interval). * @method CarbonInterface subMillis(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMilli() Sub one millisecond to the instance (using date interval). * @method CarbonInterface addMilliseconds(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMillisecond() Add one millisecond to the instance (using date interval). * @method CarbonInterface subMilliseconds(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMillisecond() Sub one millisecond to the instance (using date interval). * @method CarbonInterface addMicros(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMicro() Add one microsecond to the instance (using date interval). * @method CarbonInterface subMicros(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMicro() Sub one microsecond to the instance (using date interval). * @method CarbonInterface addMicroseconds(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMicrosecond() Add one microsecond to the instance (using date interval). * @method CarbonInterface subMicroseconds(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMicrosecond() Sub one microsecond to the instance (using date interval). * @method CarbonInterface addMillennia(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMillennium() Add one millennium to the instance (using date interval). * @method CarbonInterface subMillennia(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMillennium() Sub one millennium to the instance (using date interval). * @method CarbonInterface addMillenniaWithOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMillenniumWithOverflow() Add one millennium to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMillenniaWithOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMillenniumWithOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMillenniaWithoutOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniumWithoutOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniaWithoutOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniumWithoutOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniaWithNoOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniumWithNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniaWithNoOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniumWithNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniaNoOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniumNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniaNoOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniumNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturies(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addCentury() Add one century to the instance (using date interval). * @method CarbonInterface subCenturies(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subCentury() Sub one century to the instance (using date interval). * @method CarbonInterface addCenturiesWithOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addCenturyWithOverflow() Add one century to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subCenturiesWithOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subCenturyWithOverflow() Sub one century to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addCenturiesWithoutOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturyWithoutOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturiesWithoutOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturyWithoutOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturiesWithNoOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturyWithNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturiesWithNoOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturyWithNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturiesNoOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturyNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturiesNoOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturyNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecades(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addDecade() Add one decade to the instance (using date interval). * @method CarbonInterface subDecades(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subDecade() Sub one decade to the instance (using date interval). * @method CarbonInterface addDecadesWithOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addDecadeWithOverflow() Add one decade to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subDecadesWithOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subDecadeWithOverflow() Sub one decade to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addDecadesWithoutOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadeWithoutOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadesWithoutOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadeWithoutOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadesWithNoOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadeWithNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadesWithNoOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadeWithNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadesNoOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadeNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadesNoOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadeNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarters(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addQuarter() Add one quarter to the instance (using date interval). * @method CarbonInterface subQuarters(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subQuarter() Sub one quarter to the instance (using date interval). * @method CarbonInterface addQuartersWithOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addQuarterWithOverflow() Add one quarter to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subQuartersWithOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subQuarterWithOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addQuartersWithoutOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarterWithoutOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuartersWithoutOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuarterWithoutOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuartersWithNoOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarterWithNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuartersWithNoOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuarterWithNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuartersNoOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarterNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuartersNoOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuarterNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addWeeks(int|float $value = 1) Add weeks (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addWeek() Add one week to the instance (using date interval). * @method CarbonInterface subWeeks(int|float $value = 1) Sub weeks (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subWeek() Sub one week to the instance (using date interval). * @method CarbonInterface addWeekdays(int|float $value = 1) Add weekdays (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addWeekday() Add one weekday to the instance (using date interval). * @method CarbonInterface subWeekdays(int|float $value = 1) Sub weekdays (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subWeekday() Sub one weekday to the instance (using date interval). * @method CarbonInterface addUTCMicros(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMicro() Add one microsecond to the instance (using timestamp). * @method CarbonInterface subUTCMicros(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMicro() Sub one microsecond to the instance (using timestamp). * @method CarbonPeriod microsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. * @method float diffInUTCMicros(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of microseconds. * @method CarbonInterface addUTCMicroseconds(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMicrosecond() Add one microsecond to the instance (using timestamp). * @method CarbonInterface subUTCMicroseconds(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMicrosecond() Sub one microsecond to the instance (using timestamp). * @method CarbonPeriod microsecondsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. * @method float diffInUTCMicroseconds(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of microseconds. * @method CarbonInterface addUTCMillis(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMilli() Add one millisecond to the instance (using timestamp). * @method CarbonInterface subUTCMillis(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMilli() Sub one millisecond to the instance (using timestamp). * @method CarbonPeriod millisUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. * @method float diffInUTCMillis(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of milliseconds. * @method CarbonInterface addUTCMilliseconds(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMillisecond() Add one millisecond to the instance (using timestamp). * @method CarbonInterface subUTCMilliseconds(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMillisecond() Sub one millisecond to the instance (using timestamp). * @method CarbonPeriod millisecondsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. * @method float diffInUTCMilliseconds(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of milliseconds. * @method CarbonInterface addUTCSeconds(int|float $value = 1) Add seconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCSecond() Add one second to the instance (using timestamp). * @method CarbonInterface subUTCSeconds(int|float $value = 1) Sub seconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCSecond() Sub one second to the instance (using timestamp). * @method CarbonPeriod secondsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each second or every X seconds if a factor is given. * @method float diffInUTCSeconds(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of seconds. * @method CarbonInterface addUTCMinutes(int|float $value = 1) Add minutes (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMinute() Add one minute to the instance (using timestamp). * @method CarbonInterface subUTCMinutes(int|float $value = 1) Sub minutes (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMinute() Sub one minute to the instance (using timestamp). * @method CarbonPeriod minutesUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each minute or every X minutes if a factor is given. * @method float diffInUTCMinutes(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of minutes. * @method CarbonInterface addUTCHours(int|float $value = 1) Add hours (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCHour() Add one hour to the instance (using timestamp). * @method CarbonInterface subUTCHours(int|float $value = 1) Sub hours (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCHour() Sub one hour to the instance (using timestamp). * @method CarbonPeriod hoursUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each hour or every X hours if a factor is given. * @method float diffInUTCHours(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of hours. * @method CarbonInterface addUTCDays(int|float $value = 1) Add days (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCDay() Add one day to the instance (using timestamp). * @method CarbonInterface subUTCDays(int|float $value = 1) Sub days (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCDay() Sub one day to the instance (using timestamp). * @method CarbonPeriod daysUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each day or every X days if a factor is given. * @method float diffInUTCDays(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of days. * @method CarbonInterface addUTCWeeks(int|float $value = 1) Add weeks (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCWeek() Add one week to the instance (using timestamp). * @method CarbonInterface subUTCWeeks(int|float $value = 1) Sub weeks (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCWeek() Sub one week to the instance (using timestamp). * @method CarbonPeriod weeksUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each week or every X weeks if a factor is given. * @method float diffInUTCWeeks(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of weeks. * @method CarbonInterface addUTCMonths(int|float $value = 1) Add months (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMonth() Add one month to the instance (using timestamp). * @method CarbonInterface subUTCMonths(int|float $value = 1) Sub months (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMonth() Sub one month to the instance (using timestamp). * @method CarbonPeriod monthsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each month or every X months if a factor is given. * @method float diffInUTCMonths(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of months. * @method CarbonInterface addUTCQuarters(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCQuarter() Add one quarter to the instance (using timestamp). * @method CarbonInterface subUTCQuarters(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCQuarter() Sub one quarter to the instance (using timestamp). * @method CarbonPeriod quartersUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each quarter or every X quarters if a factor is given. * @method float diffInUTCQuarters(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of quarters. * @method CarbonInterface addUTCYears(int|float $value = 1) Add years (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCYear() Add one year to the instance (using timestamp). * @method CarbonInterface subUTCYears(int|float $value = 1) Sub years (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCYear() Sub one year to the instance (using timestamp). * @method CarbonPeriod yearsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each year or every X years if a factor is given. * @method float diffInUTCYears(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of years. * @method CarbonInterface addUTCDecades(int|float $value = 1) Add decades (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCDecade() Add one decade to the instance (using timestamp). * @method CarbonInterface subUTCDecades(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCDecade() Sub one decade to the instance (using timestamp). * @method CarbonPeriod decadesUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each decade or every X decades if a factor is given. * @method float diffInUTCDecades(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of decades. * @method CarbonInterface addUTCCenturies(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCCentury() Add one century to the instance (using timestamp). * @method CarbonInterface subUTCCenturies(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCCentury() Sub one century to the instance (using timestamp). * @method CarbonPeriod centuriesUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each century or every X centuries if a factor is given. * @method float diffInUTCCenturies(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of centuries. * @method CarbonInterface addUTCMillennia(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMillennium() Add one millennium to the instance (using timestamp). * @method CarbonInterface subUTCMillennia(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMillennium() Sub one millennium to the instance (using timestamp). * @method CarbonPeriod millenniaUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millennium or every X millennia if a factor is given. * @method float diffInUTCMillennia(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of millennia. * @method CarbonInterface roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method CarbonInterface roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method CarbonInterface floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method CarbonInterface floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method CarbonInterface ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method CarbonInterface ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method CarbonInterface roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method CarbonInterface roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method CarbonInterface floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method CarbonInterface floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method CarbonInterface ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method CarbonInterface ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method CarbonInterface roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method CarbonInterface roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method CarbonInterface floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method CarbonInterface floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method CarbonInterface ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method CarbonInterface ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method CarbonInterface roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method CarbonInterface roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method CarbonInterface floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method CarbonInterface floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method CarbonInterface ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method CarbonInterface ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method CarbonInterface roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method CarbonInterface roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method CarbonInterface floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method CarbonInterface floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method CarbonInterface ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method CarbonInterface ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method CarbonInterface roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method CarbonInterface roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method CarbonInterface floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method CarbonInterface floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method CarbonInterface ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method CarbonInterface ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method CarbonInterface roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method CarbonInterface roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method CarbonInterface floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method CarbonInterface floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method CarbonInterface ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method CarbonInterface ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method CarbonInterface roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method CarbonInterface roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method CarbonInterface floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method CarbonInterface floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method CarbonInterface ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method CarbonInterface ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method CarbonInterface roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method CarbonInterface roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method CarbonInterface floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method CarbonInterface floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method CarbonInterface ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method CarbonInterface ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method CarbonInterface roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method CarbonInterface roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method CarbonInterface floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method CarbonInterface floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method CarbonInterface ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method CarbonInterface ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method CarbonInterface roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method CarbonInterface roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method CarbonInterface floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method CarbonInterface floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method CarbonInterface ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method CarbonInterface ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method CarbonInterface roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method CarbonInterface roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method CarbonInterface floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method CarbonInterface floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method CarbonInterface ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method CarbonInterface ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * @method string shortAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string shortRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string shortRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string shortRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method int centuriesInMillennium() Return the number of centuries contained in the current millennium * @method int|static centuryOfMillennium(?int $century = null) Return the value of the century starting from the beginning of the current millennium when called with no parameters, change the current century when called with an integer value * @method int|static dayOfCentury(?int $day = null) Return the value of the day starting from the beginning of the current century when called with no parameters, change the current day when called with an integer value * @method int|static dayOfDecade(?int $day = null) Return the value of the day starting from the beginning of the current decade when called with no parameters, change the current day when called with an integer value * @method int|static dayOfMillennium(?int $day = null) Return the value of the day starting from the beginning of the current millennium when called with no parameters, change the current day when called with an integer value * @method int|static dayOfMonth(?int $day = null) Return the value of the day starting from the beginning of the current month when called with no parameters, change the current day when called with an integer value * @method int|static dayOfQuarter(?int $day = null) Return the value of the day starting from the beginning of the current quarter when called with no parameters, change the current day when called with an integer value * @method int|static dayOfWeek(?int $day = null) Return the value of the day starting from the beginning of the current week when called with no parameters, change the current day when called with an integer value * @method int daysInCentury() Return the number of days contained in the current century * @method int daysInDecade() Return the number of days contained in the current decade * @method int daysInMillennium() Return the number of days contained in the current millennium * @method int daysInMonth() Return the number of days contained in the current month * @method int daysInQuarter() Return the number of days contained in the current quarter * @method int daysInWeek() Return the number of days contained in the current week * @method int daysInYear() Return the number of days contained in the current year * @method int|static decadeOfCentury(?int $decade = null) Return the value of the decade starting from the beginning of the current century when called with no parameters, change the current decade when called with an integer value * @method int|static decadeOfMillennium(?int $decade = null) Return the value of the decade starting from the beginning of the current millennium when called with no parameters, change the current decade when called with an integer value * @method int decadesInCentury() Return the number of decades contained in the current century * @method int decadesInMillennium() Return the number of decades contained in the current millennium * @method int|static hourOfCentury(?int $hour = null) Return the value of the hour starting from the beginning of the current century when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfDay(?int $hour = null) Return the value of the hour starting from the beginning of the current day when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfDecade(?int $hour = null) Return the value of the hour starting from the beginning of the current decade when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfMillennium(?int $hour = null) Return the value of the hour starting from the beginning of the current millennium when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfMonth(?int $hour = null) Return the value of the hour starting from the beginning of the current month when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfQuarter(?int $hour = null) Return the value of the hour starting from the beginning of the current quarter when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfWeek(?int $hour = null) Return the value of the hour starting from the beginning of the current week when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfYear(?int $hour = null) Return the value of the hour starting from the beginning of the current year when called with no parameters, change the current hour when called with an integer value * @method int hoursInCentury() Return the number of hours contained in the current century * @method int hoursInDay() Return the number of hours contained in the current day * @method int hoursInDecade() Return the number of hours contained in the current decade * @method int hoursInMillennium() Return the number of hours contained in the current millennium * @method int hoursInMonth() Return the number of hours contained in the current month * @method int hoursInQuarter() Return the number of hours contained in the current quarter * @method int hoursInWeek() Return the number of hours contained in the current week * @method int hoursInYear() Return the number of hours contained in the current year * @method int|static microsecondOfCentury(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current century when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfDay(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current day when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfDecade(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current decade when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfHour(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current hour when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMillennium(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current millennium when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMillisecond(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current millisecond when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMinute(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current minute when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMonth(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current month when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfQuarter(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current quarter when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfSecond(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current second when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfWeek(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current week when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfYear(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current year when called with no parameters, change the current microsecond when called with an integer value * @method int microsecondsInCentury() Return the number of microseconds contained in the current century * @method int microsecondsInDay() Return the number of microseconds contained in the current day * @method int microsecondsInDecade() Return the number of microseconds contained in the current decade * @method int microsecondsInHour() Return the number of microseconds contained in the current hour * @method int microsecondsInMillennium() Return the number of microseconds contained in the current millennium * @method int microsecondsInMillisecond() Return the number of microseconds contained in the current millisecond * @method int microsecondsInMinute() Return the number of microseconds contained in the current minute * @method int microsecondsInMonth() Return the number of microseconds contained in the current month * @method int microsecondsInQuarter() Return the number of microseconds contained in the current quarter * @method int microsecondsInSecond() Return the number of microseconds contained in the current second * @method int microsecondsInWeek() Return the number of microseconds contained in the current week * @method int microsecondsInYear() Return the number of microseconds contained in the current year * @method int|static millisecondOfCentury(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current century when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfDay(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current day when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfDecade(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current decade when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfHour(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current hour when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfMillennium(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current millennium when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfMinute(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current minute when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfMonth(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current month when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfQuarter(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current quarter when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfSecond(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current second when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfWeek(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current week when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfYear(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current year when called with no parameters, change the current millisecond when called with an integer value * @method int millisecondsInCentury() Return the number of milliseconds contained in the current century * @method int millisecondsInDay() Return the number of milliseconds contained in the current day * @method int millisecondsInDecade() Return the number of milliseconds contained in the current decade * @method int millisecondsInHour() Return the number of milliseconds contained in the current hour * @method int millisecondsInMillennium() Return the number of milliseconds contained in the current millennium * @method int millisecondsInMinute() Return the number of milliseconds contained in the current minute * @method int millisecondsInMonth() Return the number of milliseconds contained in the current month * @method int millisecondsInQuarter() Return the number of milliseconds contained in the current quarter * @method int millisecondsInSecond() Return the number of milliseconds contained in the current second * @method int millisecondsInWeek() Return the number of milliseconds contained in the current week * @method int millisecondsInYear() Return the number of milliseconds contained in the current year * @method int|static minuteOfCentury(?int $minute = null) Return the value of the minute starting from the beginning of the current century when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfDay(?int $minute = null) Return the value of the minute starting from the beginning of the current day when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfDecade(?int $minute = null) Return the value of the minute starting from the beginning of the current decade when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfHour(?int $minute = null) Return the value of the minute starting from the beginning of the current hour when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfMillennium(?int $minute = null) Return the value of the minute starting from the beginning of the current millennium when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfMonth(?int $minute = null) Return the value of the minute starting from the beginning of the current month when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfQuarter(?int $minute = null) Return the value of the minute starting from the beginning of the current quarter when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfWeek(?int $minute = null) Return the value of the minute starting from the beginning of the current week when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfYear(?int $minute = null) Return the value of the minute starting from the beginning of the current year when called with no parameters, change the current minute when called with an integer value * @method int minutesInCentury() Return the number of minutes contained in the current century * @method int minutesInDay() Return the number of minutes contained in the current day * @method int minutesInDecade() Return the number of minutes contained in the current decade * @method int minutesInHour() Return the number of minutes contained in the current hour * @method int minutesInMillennium() Return the number of minutes contained in the current millennium * @method int minutesInMonth() Return the number of minutes contained in the current month * @method int minutesInQuarter() Return the number of minutes contained in the current quarter * @method int minutesInWeek() Return the number of minutes contained in the current week * @method int minutesInYear() Return the number of minutes contained in the current year * @method int|static monthOfCentury(?int $month = null) Return the value of the month starting from the beginning of the current century when called with no parameters, change the current month when called with an integer value * @method int|static monthOfDecade(?int $month = null) Return the value of the month starting from the beginning of the current decade when called with no parameters, change the current month when called with an integer value * @method int|static monthOfMillennium(?int $month = null) Return the value of the month starting from the beginning of the current millennium when called with no parameters, change the current month when called with an integer value * @method int|static monthOfQuarter(?int $month = null) Return the value of the month starting from the beginning of the current quarter when called with no parameters, change the current month when called with an integer value * @method int|static monthOfYear(?int $month = null) Return the value of the month starting from the beginning of the current year when called with no parameters, change the current month when called with an integer value * @method int monthsInCentury() Return the number of months contained in the current century * @method int monthsInDecade() Return the number of months contained in the current decade * @method int monthsInMillennium() Return the number of months contained in the current millennium * @method int monthsInQuarter() Return the number of months contained in the current quarter * @method int monthsInYear() Return the number of months contained in the current year * @method int|static quarterOfCentury(?int $quarter = null) Return the value of the quarter starting from the beginning of the current century when called with no parameters, change the current quarter when called with an integer value * @method int|static quarterOfDecade(?int $quarter = null) Return the value of the quarter starting from the beginning of the current decade when called with no parameters, change the current quarter when called with an integer value * @method int|static quarterOfMillennium(?int $quarter = null) Return the value of the quarter starting from the beginning of the current millennium when called with no parameters, change the current quarter when called with an integer value * @method int|static quarterOfYear(?int $quarter = null) Return the value of the quarter starting from the beginning of the current year when called with no parameters, change the current quarter when called with an integer value * @method int quartersInCentury() Return the number of quarters contained in the current century * @method int quartersInDecade() Return the number of quarters contained in the current decade * @method int quartersInMillennium() Return the number of quarters contained in the current millennium * @method int quartersInYear() Return the number of quarters contained in the current year * @method int|static secondOfCentury(?int $second = null) Return the value of the second starting from the beginning of the current century when called with no parameters, change the current second when called with an integer value * @method int|static secondOfDay(?int $second = null) Return the value of the second starting from the beginning of the current day when called with no parameters, change the current second when called with an integer value * @method int|static secondOfDecade(?int $second = null) Return the value of the second starting from the beginning of the current decade when called with no parameters, change the current second when called with an integer value * @method int|static secondOfHour(?int $second = null) Return the value of the second starting from the beginning of the current hour when called with no parameters, change the current second when called with an integer value * @method int|static secondOfMillennium(?int $second = null) Return the value of the second starting from the beginning of the current millennium when called with no parameters, change the current second when called with an integer value * @method int|static secondOfMinute(?int $second = null) Return the value of the second starting from the beginning of the current minute when called with no parameters, change the current second when called with an integer value * @method int|static secondOfMonth(?int $second = null) Return the value of the second starting from the beginning of the current month when called with no parameters, change the current second when called with an integer value * @method int|static secondOfQuarter(?int $second = null) Return the value of the second starting from the beginning of the current quarter when called with no parameters, change the current second when called with an integer value * @method int|static secondOfWeek(?int $second = null) Return the value of the second starting from the beginning of the current week when called with no parameters, change the current second when called with an integer value * @method int|static secondOfYear(?int $second = null) Return the value of the second starting from the beginning of the current year when called with no parameters, change the current second when called with an integer value * @method int secondsInCentury() Return the number of seconds contained in the current century * @method int secondsInDay() Return the number of seconds contained in the current day * @method int secondsInDecade() Return the number of seconds contained in the current decade * @method int secondsInHour() Return the number of seconds contained in the current hour * @method int secondsInMillennium() Return the number of seconds contained in the current millennium * @method int secondsInMinute() Return the number of seconds contained in the current minute * @method int secondsInMonth() Return the number of seconds contained in the current month * @method int secondsInQuarter() Return the number of seconds contained in the current quarter * @method int secondsInWeek() Return the number of seconds contained in the current week * @method int secondsInYear() Return the number of seconds contained in the current year * @method int|static weekOfCentury(?int $week = null) Return the value of the week starting from the beginning of the current century when called with no parameters, change the current week when called with an integer value * @method int|static weekOfDecade(?int $week = null) Return the value of the week starting from the beginning of the current decade when called with no parameters, change the current week when called with an integer value * @method int|static weekOfMillennium(?int $week = null) Return the value of the week starting from the beginning of the current millennium when called with no parameters, change the current week when called with an integer value * @method int|static weekOfMonth(?int $week = null) Return the value of the week starting from the beginning of the current month when called with no parameters, change the current week when called with an integer value * @method int|static weekOfQuarter(?int $week = null) Return the value of the week starting from the beginning of the current quarter when called with no parameters, change the current week when called with an integer value * @method int|static weekOfYear(?int $week = null) Return the value of the week starting from the beginning of the current year when called with no parameters, change the current week when called with an integer value * @method int weeksInCentury() Return the number of weeks contained in the current century * @method int weeksInDecade() Return the number of weeks contained in the current decade * @method int weeksInMillennium() Return the number of weeks contained in the current millennium * @method int weeksInMonth() Return the number of weeks contained in the current month * @method int weeksInQuarter() Return the number of weeks contained in the current quarter * @method int|static yearOfCentury(?int $year = null) Return the value of the year starting from the beginning of the current century when called with no parameters, change the current year when called with an integer value * @method int|static yearOfDecade(?int $year = null) Return the value of the year starting from the beginning of the current decade when called with no parameters, change the current year when called with an integer value * @method int|static yearOfMillennium(?int $year = null) Return the value of the year starting from the beginning of the current millennium when called with no parameters, change the current year when called with an integer value * @method int yearsInCentury() Return the number of years contained in the current century * @method int yearsInDecade() Return the number of years contained in the current decade * @method int yearsInMillennium() Return the number of years contained in the current millennium * * </autodoc> */ trait Date { use Boundaries; use Comparison; use Converter; use Creator; use Difference; use Macro; use MagicParameter; use Modifiers; use Mutability; use ObjectInitialisation; use Options; use Rounding; use Serialization; use Test; use Timestamp; use Units; use Week; /** * Names of days of the week. * * @var array */ protected static $days = [ // @call isDayOfWeek CarbonInterface::SUNDAY => 'Sunday', // @call isDayOfWeek CarbonInterface::MONDAY => 'Monday', // @call isDayOfWeek CarbonInterface::TUESDAY => 'Tuesday', // @call isDayOfWeek CarbonInterface::WEDNESDAY => 'Wednesday', // @call isDayOfWeek CarbonInterface::THURSDAY => 'Thursday', // @call isDayOfWeek CarbonInterface::FRIDAY => 'Friday', // @call isDayOfWeek CarbonInterface::SATURDAY => 'Saturday', ]; /** * List of unit and magic methods associated as doc-comments. * * @var array */ protected static $units = [ // @call setUnit // @call addUnit 'year', // @call setUnit // @call addUnit 'month', // @call setUnit // @call addUnit 'day', // @call setUnit // @call addUnit 'hour', // @call setUnit // @call addUnit 'minute', // @call setUnit // @call addUnit 'second', // @call setUnit // @call addUnit 'milli', // @call setUnit // @call addUnit 'millisecond', // @call setUnit // @call addUnit 'micro', // @call setUnit // @call addUnit 'microsecond', ]; /** * Creates a DateTimeZone from a string, DateTimeZone or integer offset. * * @param DateTimeZone|string|int|false|null $object original value to get CarbonTimeZone from it. * @param DateTimeZone|string|int|false|null $objectDump dump of the object for error messages. * * @throws InvalidTimeZoneException * * @return CarbonTimeZone|null */ protected static function safeCreateDateTimeZone( DateTimeZone|string|int|false|null $object, DateTimeZone|string|int|false|null $objectDump = null, ): ?CarbonTimeZone { return CarbonTimeZone::instance($object, $objectDump); } /** * Get the TimeZone associated with the Carbon instance (as CarbonTimeZone). * * @link https://php.net/manual/en/datetime.gettimezone.php */ public function getTimezone(): CarbonTimeZone { return $this->transmitFactory(fn () => CarbonTimeZone::instance(parent::getTimezone())); } /** * List of minimum and maximums for each unit. */ protected static function getRangesByUnit(int $daysInMonth = 31): array { return [ // @call roundUnit 'year' => [1, 9999], // @call roundUnit 'month' => [1, static::MONTHS_PER_YEAR], // @call roundUnit 'day' => [1, $daysInMonth], // @call roundUnit 'hour' => [0, static::HOURS_PER_DAY - 1], // @call roundUnit 'minute' => [0, static::MINUTES_PER_HOUR - 1], // @call roundUnit 'second' => [0, static::SECONDS_PER_MINUTE - 1], ]; } /** * Get a copy of the instance. * * @return static */ public function copy() { return clone $this; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Clone the current instance if it's mutable. * * This method is convenient to ensure you don't mutate the initial object * but avoid to make a useless copy of it if it's already immutable. * * @return static */ public function avoidMutation(): static { if ($this instanceof DateTimeImmutable) { return $this; } return clone $this; } /** * Returns a present instance in the same timezone. * * @return static */ public function nowWithSameTz(): static { $timezone = $this->getTimezone(); return $this->getClock()?->nowAs(static::class, $timezone) ?? static::now($timezone); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|DateTimeInterface|string|null $date * * @return static */ public function carbonize($date = null) { if ($date instanceof DateInterval) { return $this->avoidMutation()->add($date); } if ($date instanceof DatePeriod || $date instanceof CarbonPeriod) { $date = $date->getStartDate(); } return $this->resolveCarbon($date); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the Carbon object. * * @throws UnknownGetterException * * @return string|int|bool|DateTimeZone|null */ public function __get(string $name): mixed { return $this->get($name); } /** * Get a part of the Carbon object. * * @throws UnknownGetterException * * @return string|int|bool|DateTimeZone */ public function get(Unit|string $name): mixed { static $localizedFormats = [ // @property string the day of week in current locale 'localeDayOfWeek' => 'dddd', // @property string the abbreviated day of week in current locale 'shortLocaleDayOfWeek' => 'ddd', // @property string the month in current locale 'localeMonth' => 'MMMM', // @property string the abbreviated month in current locale 'shortLocaleMonth' => 'MMM', ]; $name = Unit::toName($name); if (isset($localizedFormats[$name])) { return $this->isoFormat($localizedFormats[$name]); } static $formats = [ // @property int 'year' => 'Y', // @property int 'yearIso' => 'o', // @--property-read int // @--property-write Month|int // @property int 'month' => 'n', // @property int 'day' => 'j', // @property int 'hour' => 'G', // @property int 'minute' => 'i', // @property int 'second' => 's', // @property int 'micro' => 'u', // @property int 'microsecond' => 'u', // @property int 0 (for Sunday) through 6 (for Saturday) 'dayOfWeek' => 'w', // @property int 1 (for Monday) through 7 (for Sunday) 'dayOfWeekIso' => 'N', // @property int ISO-8601 week number of year, weeks starting on Monday 'weekOfYear' => 'W', // @property-read int number of days in the given month 'daysInMonth' => 't', // @property int|float|string seconds since the Unix Epoch 'timestamp' => 'U', // @property-read string "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) 'latinMeridiem' => 'a', // @property-read string "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) 'latinUpperMeridiem' => 'A', // @property string the day of week in English 'englishDayOfWeek' => 'l', // @property string the abbreviated day of week in English 'shortEnglishDayOfWeek' => 'D', // @property string the month in English 'englishMonth' => 'F', // @property string the abbreviated month in English 'shortEnglishMonth' => 'M', // @property-read string $timezoneAbbreviatedName the current timezone abbreviated name 'timezoneAbbreviatedName' => 'T', // @property-read string $tzAbbrName alias of $timezoneAbbreviatedName 'tzAbbrName' => 'T', ]; switch (true) { case isset($formats[$name]): $value = $this->rawFormat($formats[$name]); return is_numeric($value) ? (int) $value : $value; // @property-read string long name of weekday translated according to Carbon locale, in english if no translation available for current language case $name === 'dayName': return $this->getTranslatedDayName(); // @property-read string short name of weekday translated according to Carbon locale, in english if no translation available for current language case $name === 'shortDayName': return $this->getTranslatedShortDayName(); // @property-read string very short name of weekday translated according to Carbon locale, in english if no translation available for current language case $name === 'minDayName': return $this->getTranslatedMinDayName(); // @property-read string long name of month translated according to Carbon locale, in english if no translation available for current language case $name === 'monthName': return $this->getTranslatedMonthName(); // @property-read string short name of month translated according to Carbon locale, in english if no translation available for current language case $name === 'shortMonthName': return $this->getTranslatedShortMonthName(); // @property-read string lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language case $name === 'meridiem': return $this->meridiem(true); // @property-read string uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language case $name === 'upperMeridiem': return $this->meridiem(); // @property-read int current hour from 1 to 24 case $name === 'noZeroHour': return $this->hour ?: 24; // @property int case $name === 'milliseconds': // @property int case $name === 'millisecond': // @property int case $name === 'milli': return (int) floor(((int) $this->rawFormat('u')) / 1000); // @property int 1 through 53 case $name === 'week': return (int) $this->week(); // @property int 1 through 53 case $name === 'isoWeek': return (int) $this->isoWeek(); // @property int year according to week format case $name === 'weekYear': return (int) $this->weekYear(); // @property int year according to ISO week format case $name === 'isoWeekYear': return (int) $this->isoWeekYear(); // @property-read int 51 through 53 case $name === 'weeksInYear': return $this->weeksInYear(); // @property-read int 51 through 53 case $name === 'isoWeeksInYear': return $this->isoWeeksInYear(); // @property int 1 through 5 case $name === 'weekOfMonth': return (int) ceil($this->day / static::DAYS_PER_WEEK); // @property-read int 1 through 5 case $name === 'weekNumberInMonth': return (int) ceil(($this->day + $this->avoidMutation()->startOfMonth()->dayOfWeekIso - 1) / static::DAYS_PER_WEEK); // @property-read int 0 through 6 case $name === 'firstWeekDay': return (int) $this->getTranslationMessage('first_day_of_week'); // @property-read int 0 through 6 case $name === 'lastWeekDay': return $this->transmitFactory(fn () => static::weekRotate((int) $this->getTranslationMessage('first_day_of_week'), -1)); // @property int 1 through 366 case $name === 'dayOfYear': return 1 + (int) ($this->rawFormat('z')); // @property-read int 365 or 366 case $name === 'daysInYear': return static::DAYS_PER_YEAR + ($this->isLeapYear() ? 1 : 0); // @property int does a diffInYears() with default parameters case $name === 'age': return (int) $this->diffInYears(); // @property-read int the quarter of this instance, 1 - 4 case $name === 'quarter': return (int) ceil($this->month / static::MONTHS_PER_QUARTER); // @property-read int the decade of this instance // @call isSameUnit case $name === 'decade': return (int) ceil($this->year / static::YEARS_PER_DECADE); // @property-read int the century of this instance // @call isSameUnit case $name === 'century': $factor = 1; $year = $this->year; if ($year < 0) { $year = -$year; $factor = -1; } return (int) ($factor * ceil($year / static::YEARS_PER_CENTURY)); // @property-read int the millennium of this instance // @call isSameUnit case $name === 'millennium': $factor = 1; $year = $this->year; if ($year < 0) { $year = -$year; $factor = -1; } return (int) ($factor * ceil($year / static::YEARS_PER_MILLENNIUM)); // @property int the timezone offset in seconds from UTC case $name === 'offset': return $this->getOffset(); // @property int the timezone offset in minutes from UTC case $name === 'offsetMinutes': return $this->getOffset() / static::SECONDS_PER_MINUTE; // @property int the timezone offset in hours from UTC case $name === 'offsetHours': return $this->getOffset() / static::SECONDS_PER_MINUTE / static::MINUTES_PER_HOUR; // @property-read bool daylight savings time indicator, true if DST, false otherwise case $name === 'dst': return $this->rawFormat('I') === '1'; // @property-read bool checks if the timezone is local, true if local, false otherwise case $name === 'local': return $this->getOffset() === $this->avoidMutation()->setTimezone(date_default_timezone_get())->getOffset(); // @property-read bool checks if the timezone is UTC, true if UTC, false otherwise case $name === 'utc': return $this->getOffset() === 0; // @--property-write DateTimeZone|string|int $timezone the current timezone // @--property-write DateTimeZone|string|int $tz alias of $timezone // @--property-read CarbonTimeZone $timezone the current timezone // @--property-read CarbonTimeZone $tz alias of $timezone // @property CarbonTimeZone $timezone the current timezone // @property CarbonTimeZone $tz alias of $timezone case $name === 'timezone' || $name === 'tz': return $this->getTimezone(); // @property-read string $timezoneName the current timezone name // @property-read string $tzName alias of $timezoneName case $name === 'timezoneName' || $name === 'tzName': return $this->getTimezone()->getName(); // @property-read string locale of the current instance case $name === 'locale': return $this->getTranslatorLocale(); case preg_match('/^([a-z]{2,})(In|Of)([A-Z][a-z]+)$/', $name, $match): [, $firstUnit, $operator, $secondUnit] = $match; try { $start = $this->avoidMutation()->startOf($secondUnit); $value = $operator === 'Of' ? (\in_array($firstUnit, [ // Unit with indexes starting at 1 (other units start at 0) 'day', 'week', 'month', 'quarter', ], true) ? 1 : 0) + floor($start->diffInUnit($firstUnit, $this)) : round($start->diffInUnit($firstUnit, $start->avoidMutation()->add($secondUnit, 1))); return (int) $value; } catch (UnknownUnitException) { // default to macro } default: $macro = $this->getLocalMacro('get'.ucfirst($name)); if ($macro) { return $this->executeCallableWithContext($macro); } throw new UnknownGetterException($name); } } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset($name) { try { $this->__get($name); } catch (UnknownGetterException | ReflectionException) { return false; } return true; } /** * Set a part of the Carbon object * * @param string $name * @param string|int|DateTimeZone $value * * @throws UnknownSetterException|ReflectionException * * @return void */ public function __set($name, $value) { if ($this->constructedObjectId === spl_object_hash($this)) { $this->set($name, $value); return; } $this->$name = $value; } /** * Set a part of the Carbon object. * * @throws ImmutableException|UnknownSetterException * * @return $this */ public function set(Unit|array|string $name, DateTimeZone|Month|string|int|float|null $value = null): static { if ($this->isImmutable()) { throw new ImmutableException(\sprintf('%s class', static::class)); } if (\is_array($name)) { foreach ($name as $key => $value) { $this->set($key, $value); } return $this; } $name = Unit::toName($name); switch ($name) { case 'milliseconds': case 'millisecond': case 'milli': case 'microseconds': case 'microsecond': case 'micro': if (str_starts_with($name, 'milli')) { $value *= 1000; } while ($value < 0) { $this->subSecond(); $value += static::MICROSECONDS_PER_SECOND; } while ($value >= static::MICROSECONDS_PER_SECOND) { $this->addSecond(); $value -= static::MICROSECONDS_PER_SECOND; } $this->modify($this->rawFormat('H:i:s.').str_pad((string) round($value), 6, '0', STR_PAD_LEFT)); break; case 'year': case 'month': case 'day': case 'hour': case 'minute': case 'second': [$year, $month, $day, $hour, $minute, $second] = array_map('intval', explode('-', $this->rawFormat('Y-n-j-G-i-s'))); $$name = self::monthToInt($value, $name); $this->setDateTime($year, $month, $day, $hour, $minute, $second); break; case 'week': $this->week($value); break; case 'isoWeek': $this->isoWeek($value); break; case 'weekYear': $this->weekYear($value); break; case 'isoWeekYear': $this->isoWeekYear($value); break; case 'dayOfYear': $this->addDays($value - $this->dayOfYear); break; case 'dayOfWeek': $this->addDays($value - $this->dayOfWeek); break; case 'dayOfWeekIso': $this->addDays($value - $this->dayOfWeekIso); break; case 'timestamp': $this->setTimestamp($value); break; case 'offset': $this->setTimezone(static::safeCreateDateTimeZone($value / static::SECONDS_PER_MINUTE / static::MINUTES_PER_HOUR)); break; case 'offsetMinutes': $this->setTimezone(static::safeCreateDateTimeZone($value / static::MINUTES_PER_HOUR)); break; case 'offsetHours': $this->setTimezone(static::safeCreateDateTimeZone($value)); break; case 'timezone': case 'tz': $this->setTimezone($value); break; default: if (preg_match('/^([a-z]{2,})Of([A-Z][a-z]+)$/', $name, $match)) { [, $firstUnit, $secondUnit] = $match; try { $start = $this->avoidMutation()->startOf($secondUnit); $currentValue = (\in_array($firstUnit, [ // Unit with indexes starting at 1 (other units start at 0) 'day', 'week', 'month', 'quarter', ], true) ? 1 : 0) + (int) floor($start->diffInUnit($firstUnit, $this)); // We check $value a posteriori to give precedence to UnknownUnitException if (!\is_int($value)) { throw new UnitException("->$name expects integer value"); } $this->addUnit($firstUnit, $value - $currentValue); break; } catch (UnknownUnitException) { // default to macro } } $macro = $this->getLocalMacro('set'.ucfirst($name)); if ($macro) { $this->executeCallableWithContext($macro, $value); break; } if ($this->isLocalStrictModeEnabled()) { throw new UnknownSetterException($name); } $this->$name = $value; } return $this; } /** * Get the translation of the current week day name (with context for languages with multiple forms). * * @param string|null $context whole format string * @param string $keySuffix "", "_short" or "_min" * @param string|null $defaultValue default value if translation missing */ public function getTranslatedDayName( ?string $context = null, string $keySuffix = '', ?string $defaultValue = null, ): string { return $this->getTranslatedFormByRegExp('weekdays', $keySuffix, $context, $this->dayOfWeek, $defaultValue ?: $this->englishDayOfWeek); } /** * Get the translation of the current short week day name (with context for languages with multiple forms). * * @param string|null $context whole format string */ public function getTranslatedShortDayName(?string $context = null): string { return $this->getTranslatedDayName($context, '_short', $this->shortEnglishDayOfWeek); } /** * Get the translation of the current abbreviated week day name (with context for languages with multiple forms). * * @param string|null $context whole format string */ public function getTranslatedMinDayName(?string $context = null): string { return $this->getTranslatedDayName($context, '_min', $this->shortEnglishDayOfWeek); } /** * Get the translation of the current month day name (with context for languages with multiple forms). * * @param string|null $context whole format string * @param string $keySuffix "" or "_short" * @param string|null $defaultValue default value if translation missing */ public function getTranslatedMonthName( ?string $context = null, string $keySuffix = '', ?string $defaultValue = null, ): string { return $this->getTranslatedFormByRegExp('months', $keySuffix, $context, $this->month - 1, $defaultValue ?: $this->englishMonth); } /** * Get the translation of the current short month day name (with context for languages with multiple forms). * * @param string|null $context whole format string */ public function getTranslatedShortMonthName(?string $context = null): string { return $this->getTranslatedMonthName($context, '_short', $this->shortEnglishMonth); } /** * Get/set the day of year. * * @template T of int|null * * @param int|null $value new value for day of year if using as setter. * * @psalm-param T $value * * @return static|int * * @psalm-return (T is int ? static : int) */ public function dayOfYear(?int $value = null): static|int { $dayOfYear = $this->dayOfYear; return $value === null ? $dayOfYear : $this->addDays($value - $dayOfYear); } /** * Get/set the weekday from 0 (Sunday) to 6 (Saturday). * * @param WeekDay|int|null $value new value for weekday if using as setter. */ public function weekday(WeekDay|int|null $value = null): static|int { if ($value === null) { return $this->dayOfWeek; } $firstDay = (int) ($this->getTranslationMessage('first_day_of_week') ?? 0); $dayOfWeek = ($this->dayOfWeek + 7 - $firstDay) % 7; return $this->addDays(((WeekDay::int($value) + 7 - $firstDay) % 7) - $dayOfWeek); } /** * Get/set the ISO weekday from 1 (Monday) to 7 (Sunday). * * @param WeekDay|int|null $value new value for weekday if using as setter. */ public function isoWeekday(WeekDay|int|null $value = null): static|int { $dayOfWeekIso = $this->dayOfWeekIso; return $value === null ? $dayOfWeekIso : $this->addDays(WeekDay::int($value) - $dayOfWeekIso); } /** * Return the number of days since the start of the week (using the current locale or the first parameter * if explicitly given). * * @param WeekDay|int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week, * if not provided, start of week is inferred from the locale * (Sunday for en_US, Monday for de_DE, etc.) */ public function getDaysFromStartOfWeek(WeekDay|int|null $weekStartsAt = null): int { $firstDay = (int) (WeekDay::int($weekStartsAt) ?? $this->getTranslationMessage('first_day_of_week') ?? 0); return ($this->dayOfWeek + 7 - $firstDay) % 7; } /** * Set the day (keeping the current time) to the start of the week + the number of days passed as the first * parameter. First day of week is driven by the locale unless explicitly set with the second parameter. * * @param int $numberOfDays number of days to add after the start of the current week * @param WeekDay|int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week, * if not provided, start of week is inferred from the locale * (Sunday for en_US, Monday for de_DE, etc.) */ public function setDaysFromStartOfWeek(int $numberOfDays, WeekDay|int|null $weekStartsAt = null): static { return $this->addDays($numberOfDays - $this->getDaysFromStartOfWeek(WeekDay::int($weekStartsAt))); } /** * Set any unit to a new value without overflowing current other unit given. * * @param string $valueUnit unit name to modify * @param int $value new value for the input unit * @param string $overflowUnit unit name to not overflow */ public function setUnitNoOverflow(string $valueUnit, int $value, string $overflowUnit): static { try { $start = $this->avoidMutation()->startOf($overflowUnit); $end = $this->avoidMutation()->endOf($overflowUnit); /** @var static $date */ $date = $this->$valueUnit($value); if ($date < $start) { return $date->mutateIfMutable($start); } if ($date > $end) { return $date->mutateIfMutable($end); } return $date; } catch (BadMethodCallException | ReflectionException $exception) { throw new UnknownUnitException($valueUnit, 0, $exception); } } /** * Add any unit to a new value without overflowing current other unit given. * * @param string $valueUnit unit name to modify * @param int $value amount to add to the input unit * @param string $overflowUnit unit name to not overflow */ public function addUnitNoOverflow(string $valueUnit, int $value, string $overflowUnit): static { return $this->setUnitNoOverflow($valueUnit, $this->$valueUnit + $value, $overflowUnit); } /** * Subtract any unit to a new value without overflowing current other unit given. * * @param string $valueUnit unit name to modify * @param int $value amount to subtract to the input unit * @param string $overflowUnit unit name to not overflow */ public function subUnitNoOverflow(string $valueUnit, int $value, string $overflowUnit): static { return $this->setUnitNoOverflow($valueUnit, $this->$valueUnit - $value, $overflowUnit); } /** * Returns the minutes offset to UTC if no arguments passed, else set the timezone with given minutes shift passed. */ public function utcOffset(?int $minuteOffset = null): static|int { if ($minuteOffset === null) { return $this->offsetMinutes; } return $this->setTimezone(CarbonTimeZone::createFromMinuteOffset($minuteOffset)); } /** * Set the date with gregorian year, month and day numbers. * * @see https://php.net/manual/en/datetime.setdate.php */ public function setDate(int $year, int $month, int $day): static { return parent::setDate($year, $month, $day); } /** * Set a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates. * * @see https://php.net/manual/en/datetime.setisodate.php */ public function setISODate(int $year, int $week, int $day = 1): static { return parent::setISODate($year, $week, $day); } /** * Set the date and time all together. */ public function setDateTime( int $year, int $month, int $day, int $hour, int $minute, int $second = 0, int $microseconds = 0, ): static { return $this->setDate($year, $month, $day)->setTime($hour, $minute, $second, $microseconds); } /** * Resets the current time of the DateTime object to a different time. * * @see https://php.net/manual/en/datetime.settime.php */ public function setTime(int $hour, int $minute, int $second = 0, int $microseconds = 0): static { return parent::setTime($hour, $minute, $second, $microseconds); } /** * Set the instance's timestamp. * * Timestamp input can be given as int, float or a string containing one or more numbers. */ public function setTimestamp(float|int|string $timestamp): static { [$seconds, $microseconds] = self::getIntegerAndDecimalParts($timestamp); return parent::setTimestamp((int) $seconds)->setMicroseconds((int) $microseconds); } /** * Set the time by time string. */ public function setTimeFromTimeString(string $time): static { if (!str_contains($time, ':')) { $time .= ':0'; } return $this->modify($time); } /** * @alias setTimezone */ public function timezone(DateTimeZone|string|int $value): static { return $this->setTimezone($value); } /** * Set the timezone or returns the timezone name if no arguments passed. * * @return ($value is null ? string : static) */ public function tz(DateTimeZone|string|int|null $value = null): static|string { if ($value === null) { return $this->tzName; } return $this->setTimezone($value); } /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timeZone): static { return parent::setTimezone(static::safeCreateDateTimeZone($timeZone)); } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string $value): static { $dateTimeString = $this->format('Y-m-d H:i:s.u'); return $this ->setTimezone($value) ->modify($dateTimeString); } /** * Set the instance's timezone to UTC. */ public function utc(): static { return $this->setTimezone('UTC'); } /** * Set the year, month, and date for this instance to that of the passed instance. */ public function setDateFrom(DateTimeInterface|string $date): static { $date = $this->resolveCarbon($date); return $this->setDate($date->year, $date->month, $date->day); } /** * Set the hour, minute, second and microseconds for this instance to that of the passed instance. */ public function setTimeFrom(DateTimeInterface|string $date): static { $date = $this->resolveCarbon($date); return $this->setTime($date->hour, $date->minute, $date->second, $date->microsecond); } /** * Set the date and time for this instance to that of the passed instance. */ public function setDateTimeFrom(DateTimeInterface|string $date): static { $date = $this->resolveCarbon($date); return $this->modify($date->rawFormat('Y-m-d H:i:s.u')); } /** * Get the days of the week. */ public static function getDays(): array { return static::$days; } /////////////////////////////////////////////////////////////////// /////////////////////// WEEK SPECIAL DAYS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Get the first day of week. * * @return int */ public static function getWeekStartsAt(?string $locale = null): int { return (int) static::getTranslationMessageWith( $locale ? Translator::get($locale) : static::getTranslator(), 'first_day_of_week', ); } /** * Get the last day of week. * * @param string $locale local to consider the last day of week. * * @return int */ public static function getWeekEndsAt(?string $locale = null): int { return static::weekRotate(static::getWeekStartsAt($locale), -1); } /** * Get weekend days */ public static function getWeekendDays(): array { return FactoryImmutable::getInstance()->getWeekendDays(); } /** * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. * You should rather consider week-end is always saturday and sunday, and if you have some custom * week-end days to handle, give to those days an other name and create a macro for them: * * ``` * Carbon::macro('isDayOff', function ($date) { * return $date->isSunday() || $date->isMonday(); * }); * Carbon::macro('isNotDayOff', function ($date) { * return !$date->isDayOff(); * }); * if ($someDate->isDayOff()) ... * if ($someDate->isNotDayOff()) ... * // Add 5 not-off days * $count = 5; * while ($someDate->isDayOff() || ($count-- > 0)) { * $someDate->addDay(); * } * ``` * * Set weekend days */ public static function setWeekendDays(array $days): void { FactoryImmutable::getDefaultInstance()->setWeekendDays($days); } /** * Determine if a time string will produce a relative date. * * @return bool true if time match a relative date, false if absolute or invalid time string */ public static function hasRelativeKeywords(?string $time): bool { if (!$time || strtotime($time) === false) { return false; } $date1 = new DateTime('2000-01-01T00:00:00Z'); $date1->modify($time); $date2 = new DateTime('2001-12-25T00:00:00Z'); $date2->modify($time); return $date1 != $date2; } /////////////////////////////////////////////////////////////////// /////////////////////// STRING FORMATTING ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Returns list of locale formats for ISO formatting. * * @param string|null $locale current locale used if null */ public function getIsoFormats(?string $locale = null): array { return [ 'LT' => $this->getTranslationMessage('formats.LT', $locale), 'LTS' => $this->getTranslationMessage('formats.LTS', $locale), 'L' => $this->getTranslationMessage('formats.L', $locale), 'LL' => $this->getTranslationMessage('formats.LL', $locale), 'LLL' => $this->getTranslationMessage('formats.LLL', $locale), 'LLLL' => $this->getTranslationMessage('formats.LLLL', $locale), 'l' => $this->getTranslationMessage('formats.l', $locale), 'll' => $this->getTranslationMessage('formats.ll', $locale), 'lll' => $this->getTranslationMessage('formats.lll', $locale), 'llll' => $this->getTranslationMessage('formats.llll', $locale), ]; } /** * Returns list of calendar formats for ISO formatting. * * @param string|null $locale current locale used if null */ public function getCalendarFormats(?string $locale = null): array { return [ 'sameDay' => $this->getTranslationMessage('calendar.sameDay', $locale, '[Today at] LT'), 'nextDay' => $this->getTranslationMessage('calendar.nextDay', $locale, '[Tomorrow at] LT'), 'nextWeek' => $this->getTranslationMessage('calendar.nextWeek', $locale, 'dddd [at] LT'), 'lastDay' => $this->getTranslationMessage('calendar.lastDay', $locale, '[Yesterday at] LT'), 'lastWeek' => $this->getTranslationMessage('calendar.lastWeek', $locale, '[Last] dddd [at] LT'), 'sameElse' => $this->getTranslationMessage('calendar.sameElse', $locale, 'L'), ]; } /** * Returns list of locale units for ISO formatting. */ public static function getIsoUnits(): array { static $units = null; $units ??= [ 'OD' => ['getAltNumber', ['day']], 'OM' => ['getAltNumber', ['month']], 'OY' => ['getAltNumber', ['year']], 'OH' => ['getAltNumber', ['hour']], 'Oh' => ['getAltNumber', ['h']], 'Om' => ['getAltNumber', ['minute']], 'Os' => ['getAltNumber', ['second']], 'D' => 'day', 'DD' => ['rawFormat', ['d']], 'Do' => ['ordinal', ['day', 'D']], 'd' => 'dayOfWeek', 'dd' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedMinDayName( $originalFormat, ), 'ddd' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedShortDayName( $originalFormat, ), 'dddd' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedDayName( $originalFormat, ), 'DDD' => 'dayOfYear', 'DDDD' => ['getPaddedUnit', ['dayOfYear', 3]], 'DDDo' => ['ordinal', ['dayOfYear', 'DDD']], 'e' => ['weekday', []], 'E' => 'dayOfWeekIso', 'H' => ['rawFormat', ['G']], 'HH' => ['rawFormat', ['H']], 'h' => ['rawFormat', ['g']], 'hh' => ['rawFormat', ['h']], 'k' => 'noZeroHour', 'kk' => ['getPaddedUnit', ['noZeroHour']], 'hmm' => ['rawFormat', ['gi']], 'hmmss' => ['rawFormat', ['gis']], 'Hmm' => ['rawFormat', ['Gi']], 'Hmmss' => ['rawFormat', ['Gis']], 'm' => 'minute', 'mm' => ['rawFormat', ['i']], 'a' => 'meridiem', 'A' => 'upperMeridiem', 's' => 'second', 'ss' => ['getPaddedUnit', ['second']], 'S' => static fn (CarbonInterface $date) => (string) floor($date->micro / 100000), 'SS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 10000, 2), 'SSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 1000, 3), 'SSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 100, 4), 'SSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 10, 5), 'SSSSSS' => ['getPaddedUnit', ['micro', 6]], 'SSSSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro * 10, 7), 'SSSSSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro * 100, 8), 'SSSSSSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro * 1000, 9), 'M' => 'month', 'MM' => ['rawFormat', ['m']], 'MMM' => static function (CarbonInterface $date, $originalFormat = null) { $month = $date->getTranslatedShortMonthName($originalFormat); $suffix = $date->getTranslationMessage('mmm_suffix'); if ($suffix && $month !== $date->monthName) { $month .= $suffix; } return $month; }, 'MMMM' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedMonthName( $originalFormat, ), 'Mo' => ['ordinal', ['month', 'M']], 'Q' => 'quarter', 'Qo' => ['ordinal', ['quarter', 'M']], 'G' => 'isoWeekYear', 'GG' => ['getPaddedUnit', ['isoWeekYear']], 'GGG' => ['getPaddedUnit', ['isoWeekYear', 3]], 'GGGG' => ['getPaddedUnit', ['isoWeekYear', 4]], 'GGGGG' => ['getPaddedUnit', ['isoWeekYear', 5]], 'g' => 'weekYear', 'gg' => ['getPaddedUnit', ['weekYear']], 'ggg' => ['getPaddedUnit', ['weekYear', 3]], 'gggg' => ['getPaddedUnit', ['weekYear', 4]], 'ggggg' => ['getPaddedUnit', ['weekYear', 5]], 'W' => 'isoWeek', 'WW' => ['getPaddedUnit', ['isoWeek']], 'Wo' => ['ordinal', ['isoWeek', 'W']], 'w' => 'week', 'ww' => ['getPaddedUnit', ['week']], 'wo' => ['ordinal', ['week', 'w']], 'x' => ['valueOf', []], 'X' => 'timestamp', 'Y' => 'year', 'YY' => ['rawFormat', ['y']], 'YYYY' => ['getPaddedUnit', ['year', 4]], 'YYYYY' => ['getPaddedUnit', ['year', 5]], 'YYYYYY' => static fn (CarbonInterface $date) => ($date->year < 0 ? '' : '+'). $date->getPaddedUnit('year', 6), 'z' => ['rawFormat', ['T']], 'zz' => 'tzName', 'Z' => ['getOffsetString', []], 'ZZ' => ['getOffsetString', ['']], ]; return $units; } /** * Returns a unit of the instance padded with 0 by default or any other string if specified. * * @param string $unit Carbon unit name * @param int $length Length of the output (2 by default) * @param string $padString String to use for padding ("0" by default) * @param int $padType Side(s) to pad (STR_PAD_LEFT by default) */ public function getPaddedUnit($unit, $length = 2, $padString = '0', $padType = STR_PAD_LEFT): string { return ($this->$unit < 0 ? '-' : '').str_pad((string) abs($this->$unit), $length, $padString, $padType); } /** * Return a property with its ordinal. */ public function ordinal(string $key, ?string $period = null): string { $number = $this->$key; $result = $this->translate('ordinal', [ ':number' => $number, ':period' => (string) $period, ]); return (string) ($result === 'ordinal' ? $number : $result); } /** * Return the meridiem of the current time in the current locale. * * @param bool $isLower if true, returns lowercase variant if available in the current locale. */ public function meridiem(bool $isLower = false): string { $hour = $this->hour; $index = $hour < static::HOURS_PER_DAY / 2 ? 0 : 1; if ($isLower) { $key = 'meridiem.'.($index + 2); $result = $this->translate($key); if ($result !== $key) { return $result; } } $key = "meridiem.$index"; $result = $this->translate($key); if ($result === $key) { $result = $this->translate('meridiem', [ ':hour' => $this->hour, ':minute' => $this->minute, ':isLower' => $isLower, ]); if ($result === 'meridiem') { return $isLower ? $this->latinMeridiem : $this->latinUpperMeridiem; } } elseif ($isLower) { $result = mb_strtolower($result); } return $result; } /** * Returns the alternative number for a given date property if available in the current locale. * * @param string $key date property */ public function getAltNumber(string $key): string { return $this->translateNumber((int) (\strlen($key) > 1 ? $this->$key : $this->rawFormat($key))); } /** * Format in the current language using ISO replacement patterns. * * @param string|null $originalFormat provide context if a chunk has been passed alone */ public function isoFormat(string $format, ?string $originalFormat = null): string { $result = ''; $length = mb_strlen($format); $originalFormat ??= $format; $inEscaped = false; $formats = null; $units = null; for ($i = 0; $i < $length; $i++) { $char = mb_substr($format, $i, 1); if ($char === '\\') { $result .= mb_substr($format, ++$i, 1); continue; } if ($char === '[' && !$inEscaped) { $inEscaped = true; continue; } if ($char === ']' && $inEscaped) { $inEscaped = false; continue; } if ($inEscaped) { $result .= $char; continue; } $input = mb_substr($format, $i); if (preg_match('/^(LTS|LT|l{1,4}|L{1,4})/', $input, $match)) { if ($formats === null) { $formats = $this->getIsoFormats(); } $code = $match[0]; $sequence = $formats[$code] ?? preg_replace_callback( '/MMMM|MM|DD|dddd/', static fn ($code) => mb_substr($code[0], 1), $formats[strtoupper($code)] ?? '', ); $rest = mb_substr($format, $i + mb_strlen($code)); $format = mb_substr($format, 0, $i).$sequence.$rest; $length = mb_strlen($format); $input = $sequence.$rest; } if (preg_match('/^'.CarbonInterface::ISO_FORMAT_REGEXP.'/', $input, $match)) { $code = $match[0]; if ($units === null) { $units = static::getIsoUnits(); } $sequence = $units[$code] ?? ''; if ($sequence instanceof Closure) { $sequence = $sequence($this, $originalFormat); } elseif (\is_array($sequence)) { try { $sequence = $this->{$sequence[0]}(...$sequence[1]); } catch (ReflectionException | InvalidArgumentException | BadMethodCallException) { $sequence = ''; } } elseif (\is_string($sequence)) { $sequence = $this->$sequence ?? $code; } $format = mb_substr($format, 0, $i).$sequence.mb_substr($format, $i + mb_strlen($code)); $i += mb_strlen((string) $sequence) - 1; $length = mb_strlen($format); $char = $sequence; } $result .= $char; } return $result; } /** * List of replacements from date() format to isoFormat(). */ public static function getFormatsToIsoReplacements(): array { static $replacements = null; $replacements ??= [ 'd' => true, 'D' => 'ddd', 'j' => true, 'l' => 'dddd', 'N' => true, 'S' => static fn ($date) => str_replace((string) $date->rawFormat('j'), '', $date->isoFormat('Do')), 'w' => true, 'z' => true, 'W' => true, 'F' => 'MMMM', 'm' => true, 'M' => 'MMM', 'n' => true, 't' => true, 'L' => true, 'o' => true, 'Y' => true, 'y' => true, 'a' => 'a', 'A' => 'A', 'B' => true, 'g' => true, 'G' => true, 'h' => true, 'H' => true, 'i' => true, 's' => true, 'u' => true, 'v' => true, 'E' => true, 'I' => true, 'O' => true, 'P' => true, 'Z' => true, 'c' => true, 'r' => true, 'U' => true, 'T' => true, ]; return $replacements; } /** * Format as ->format() do (using date replacements patterns from https://php.net/manual/en/function.date.php) * but translate words whenever possible (months, day names, etc.) using the current locale. */ public function translatedFormat(string $format): string { $replacements = static::getFormatsToIsoReplacements(); $context = ''; $isoFormat = ''; $length = mb_strlen($format); for ($i = 0; $i < $length; $i++) { $char = mb_substr($format, $i, 1); if ($char === '\\') { $replacement = mb_substr($format, $i, 2); $isoFormat .= $replacement; $i++; continue; } if (!isset($replacements[$char])) { $replacement = preg_match('/^[A-Za-z]$/', $char) ? "\\$char" : $char; $isoFormat .= $replacement; $context .= $replacement; continue; } $replacement = $replacements[$char]; if ($replacement === true) { static $contextReplacements = null; if ($contextReplacements === null) { $contextReplacements = [ 'm' => 'MM', 'd' => 'DD', 't' => 'D', 'j' => 'D', 'N' => 'e', 'w' => 'e', 'n' => 'M', 'o' => 'YYYY', 'Y' => 'YYYY', 'y' => 'YY', 'g' => 'h', 'G' => 'H', 'h' => 'hh', 'H' => 'HH', 'i' => 'mm', 's' => 'ss', ]; } $isoFormat .= '['.$this->rawFormat($char).']'; $context .= $contextReplacements[$char] ?? ' '; continue; } if ($replacement instanceof Closure) { $replacement = '['.$replacement($this).']'; $isoFormat .= $replacement; $context .= $replacement; continue; } $isoFormat .= $replacement; $context .= $replacement; } return $this->isoFormat($isoFormat, $context); } /** * Returns the offset hour and minute formatted with +/- and a given separator (":" by default). * For example, if the time zone is 9 hours 30 minutes, you'll get "+09:30", with "@@" as first * argument, "+09@@30", with "" as first argument, "+0930". Negative offset will return something * like "-12:00". * * @param string $separator string to place between hours and minutes (":" by default) */ public function getOffsetString(string $separator = ':'): string { $second = $this->getOffset(); $symbol = $second < 0 ? '-' : '+'; $minute = abs($second) / static::SECONDS_PER_MINUTE; $hour = self::floorZeroPad($minute / static::MINUTES_PER_HOUR, 2); $minute = self::floorZeroPad(((int) $minute) % static::MINUTES_PER_HOUR, 2); return "$symbol$hour$separator$minute"; } /** * Dynamically handle calls to the class. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadMethodCallException */ public static function __callStatic(string $method, array $parameters): mixed { if (!static::hasMacro($method)) { foreach (static::getGenericMacros() as $callback) { try { return static::executeStaticCallable($callback, $method, ...$parameters); } catch (BadMethodCallException) { continue; } } if (static::isStrictModeEnabled()) { throw new UnknownMethodException(\sprintf('%s::%s', static::class, $method)); } return null; } return static::executeStaticCallable(static::getMacro($method), ...$parameters); } /** * Set specified unit to new given value. * * @param string $unit year, month, day, hour, minute, second or microsecond * @param Month|int $value new value for given unit */ public function setUnit(string $unit, Month|int|float|null $value = null): static { if (\is_float($value)) { $int = (int) $value; if ((float) $int !== $value) { throw new InvalidArgumentException( "$unit cannot be changed to float value $value, integer expected", ); } $value = $int; } $unit = static::singularUnit($unit); $value = self::monthToInt($value, $unit); $dateUnits = ['year', 'month', 'day']; if (\in_array($unit, $dateUnits)) { return $this->setDate(...array_map( fn ($name) => (int) ($name === $unit ? $value : $this->$name), $dateUnits, )); } $units = ['hour', 'minute', 'second', 'micro']; if ($unit === 'millisecond' || $unit === 'milli') { $value *= 1000; $unit = 'micro'; } elseif ($unit === 'microsecond') { $unit = 'micro'; } return $this->setTime(...array_map( fn ($name) => (int) ($name === $unit ? $value : $this->$name), $units, )); } /** * Returns standardized singular of a given singular/plural unit name (in English). */ public static function singularUnit(string $unit): string { $unit = rtrim(mb_strtolower($unit), 's'); return match ($unit) { 'centurie' => 'century', 'millennia' => 'millennium', default => $unit, }; } /** * Returns standardized plural of a given singular/plural unit name (in English). */ public static function pluralUnit(string $unit): string { $unit = rtrim(strtolower($unit), 's'); return match ($unit) { 'century' => 'centuries', 'millennium', 'millennia' => 'millennia', default => "{$unit}s", }; } public static function sleep(int|float $seconds): void { if (static::hasTestNow()) { static::setTestNow(static::getTestNow()->avoidMutation()->addSeconds($seconds)); return; } (new NativeClock('UTC'))->sleep($seconds); } /** * Dynamically handle calls to the class. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws UnknownMethodException|BadMethodCallException|ReflectionException|Throwable */ public function __call(string $method, array $parameters): mixed { $unit = rtrim($method, 's'); return $this->callDiffAlias($unit, $parameters) ?? $this->callHumanDiffAlias($unit, $parameters) ?? $this->callRoundMethod($unit, $parameters) ?? $this->callIsMethod($unit, $parameters) ?? $this->callModifierMethod($unit, $parameters) ?? $this->callPeriodMethod($method, $parameters) ?? $this->callGetOrSetMethod($method, $parameters) ?? $this->callMacroMethod($method, $parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. */ protected function resolveCarbon(DateTimeInterface|string|null $date): self { if (!$date) { return $this->nowWithSameTz(); } if (\is_string($date)) { return $this->transmitFactory(fn () => static::parse($date, $this->getTimezone())); } return $date instanceof self ? $date : $this->transmitFactory(static fn () => static::instance($date)); } protected static function weekRotate(int $day, int $rotation): int { return (static::DAYS_PER_WEEK + $rotation % static::DAYS_PER_WEEK + $day) % static::DAYS_PER_WEEK; } protected function executeCallable(callable $macro, ...$parameters) { if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return \call_user_func_array($boundMacro ?: $macro, $parameters); } return \call_user_func_array($macro, $parameters); } protected function executeCallableWithContext(callable $macro, ...$parameters) { return static::bindMacroContext($this, function () use (&$macro, &$parameters) { return $this->executeCallable($macro, ...$parameters); }); } protected function getAllGenericMacros(): Generator { yield from $this->localGenericMacros ?? []; yield from $this->transmitFactory(static fn () => static::getGenericMacros()); } protected static function getGenericMacros(): Generator { foreach ((FactoryImmutable::getInstance()->getSettings()['genericMacros'] ?? []) as $list) { foreach ($list as $macro) { yield $macro; } } } protected static function executeStaticCallable(callable $macro, ...$parameters) { return static::bindMacroContext(null, function () use (&$macro, &$parameters) { if ($macro instanceof Closure) { $boundMacro = @Closure::bind($macro, null, static::class); return \call_user_func_array($boundMacro ?: $macro, $parameters); } return \call_user_func_array($macro, $parameters); }); } protected function getTranslatedFormByRegExp($baseKey, $keySuffix, $context, $subKey, $defaultValue) { $key = $baseKey.$keySuffix; $standaloneKey = $key.'_standalone'; $baseTranslation = $this->getTranslationMessage($key); if ($baseTranslation instanceof Closure) { return $baseTranslation($this, $context, $subKey) ?: $defaultValue; } if ( $this->getTranslationMessage("$standaloneKey.$subKey") && (!$context || (($regExp = $this->getTranslationMessage($baseKey.'_regexp')) && !preg_match($regExp, $context))) ) { $key = $standaloneKey; } return $this->getTranslationMessage("$key.$subKey", null, $defaultValue); } private function callGetOrSetMethod(string $method, array $parameters): mixed { if (preg_match('/^([a-z]{2,})(In|Of)([A-Z][a-z]+)$/', $method)) { $localStrictModeEnabled = $this->localStrictModeEnabled; $this->localStrictModeEnabled = true; try { return $this->callGetOrSet($method, $parameters[0] ?? null); } catch (UnknownGetterException|UnknownSetterException|ImmutableException) { // continue to macro } finally { $this->localStrictModeEnabled = $localStrictModeEnabled; } } return null; } private function callGetOrSet(string $name, mixed $value): mixed { if ($value !== null) { if (\is_string($value) || \is_int($value) || \is_float($value) || $value instanceof DateTimeZone || $value instanceof Month) { return $this->set($name, $value); } return null; } return $this->get($name); } private function getUTCUnit(string $unit): ?string { if (str_starts_with($unit, 'Real')) { return substr($unit, 4); } if (str_starts_with($unit, 'UTC')) { return substr($unit, 3); } return null; } private function callDiffAlias(string $method, array $parameters): mixed { if (preg_match('/^(diff|floatDiff)In(Real|UTC|Utc)?(.+)$/', $method, $match)) { $mode = strtoupper($match[2] ?? ''); $betterMethod = $match[1] === 'floatDiff' ? str_replace('floatDiff', 'diff', $method) : null; if ($mode === 'REAL') { $mode = 'UTC'; $betterMethod = str_replace($match[2], 'UTC', $betterMethod ?? $method); } if ($betterMethod) { @trigger_error( "Use the method $betterMethod instead to make it more explicit about what it does.\n". 'On next major version, "float" prefix will be removed (as all diff are now returning floating numbers)'. ' and "Real" methods will be removed in favor of "UTC" because what it actually does is to convert both'. ' dates to UTC timezone before comparison, while by default it does it only if both dates don\'t have'. ' exactly the same timezone (Note: 2 timezones with the same offset but different names are considered'. " different as it's not safe to assume they will always have the same offset).", \E_USER_DEPRECATED, ); } $unit = self::pluralUnit($match[3]); $diffMethod = 'diffIn'.ucfirst($unit); if (\in_array($unit, ['days', 'weeks', 'months', 'quarters', 'years'])) { $parameters['utc'] = ($mode === 'UTC'); } if (method_exists($this, $diffMethod)) { return $this->$diffMethod(...$parameters); } } return null; } private function callHumanDiffAlias(string $method, array $parameters): ?string { $diffSizes = [ // @mode diffForHumans 'short' => true, // @mode diffForHumans 'long' => false, ]; $diffSyntaxModes = [ // @call diffForHumans 'Absolute' => CarbonInterface::DIFF_ABSOLUTE, // @call diffForHumans 'Relative' => CarbonInterface::DIFF_RELATIVE_AUTO, // @call diffForHumans 'RelativeToNow' => CarbonInterface::DIFF_RELATIVE_TO_NOW, // @call diffForHumans 'RelativeToOther' => CarbonInterface::DIFF_RELATIVE_TO_OTHER, ]; $sizePattern = implode('|', array_keys($diffSizes)); $syntaxPattern = implode('|', array_keys($diffSyntaxModes)); if (preg_match("/^(?<size>$sizePattern)(?<syntax>$syntaxPattern)DiffForHuman$/", $method, $match)) { $dates = array_filter($parameters, function ($parameter) { return $parameter instanceof DateTimeInterface; }); $other = null; if (\count($dates)) { $key = key($dates); $other = current($dates); array_splice($parameters, $key, 1); } return $this->diffForHumans($other, $diffSyntaxModes[$match['syntax']], $diffSizes[$match['size']], ...$parameters); } return null; } private function callIsMethod(string $unit, array $parameters): ?bool { if (!str_starts_with($unit, 'is')) { return null; } $word = substr($unit, 2); if (\in_array($word, static::$days, true)) { return $this->isDayOfWeek($word); } return match ($word) { // @call is Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) 'Utc', 'UTC' => $this->utc, // @call is Check if the current instance has non-UTC timezone. 'Local' => $this->local, // @call is Check if the current instance is a valid date. 'Valid' => $this->year !== 0, // @call is Check if the current instance is in a daylight saving time. 'DST' => $this->dst, default => $this->callComparatorMethod($word, $parameters), }; } private function callComparatorMethod(string $unit, array $parameters): ?bool { $start = substr($unit, 0, 4); $factor = -1; if ($start === 'Last') { $start = 'Next'; $factor = 1; } if ($start === 'Next') { $lowerUnit = strtolower(substr($unit, 4)); if (static::isModifiableUnit($lowerUnit)) { return $this->avoidMutation()->addUnit($lowerUnit, $factor, false)->isSameUnit($lowerUnit, ...($parameters ?: ['now'])); } } if ($start === 'Same') { try { return $this->isSameUnit(strtolower(substr($unit, 4)), ...$parameters); } catch (BadComparisonUnitException) { // Try next } } if (str_starts_with($unit, 'Current')) { try { return $this->isCurrentUnit(strtolower(substr($unit, 7))); } catch (BadComparisonUnitException | BadMethodCallException) { // Try next } } return null; } private function callModifierMethod(string $unit, array $parameters): ?static { $action = substr($unit, 0, 3); $overflow = null; if ($action === 'set') { $unit = strtolower(substr($unit, 3)); } if (\in_array($unit, static::$units, true)) { return $this->setUnit($unit, ...$parameters); } if ($action === 'add' || $action === 'sub') { $unit = substr($unit, 3); $utcUnit = $this->getUTCUnit($unit); if ($utcUnit) { $unit = static::singularUnit($utcUnit); return $this->{"{$action}UTCUnit"}($unit, ...$parameters); } if (preg_match('/^(Month|Quarter|Year|Decade|Century|Centurie|Millennium|Millennia)s?(No|With|Without|WithNo)Overflow$/', $unit, $match)) { $unit = $match[1]; $overflow = $match[2] === 'With'; } $unit = static::singularUnit($unit); } if (static::isModifiableUnit($unit)) { return $this->{"{$action}Unit"}($unit, $this->getMagicParameter($parameters, 0, 'value', 1), $overflow); } return null; } private function callPeriodMethod(string $method, array $parameters): ?CarbonPeriod { if (str_ends_with($method, 'Until')) { try { $unit = static::singularUnit(substr($method, 0, -5)); return $this->range( $this->getMagicParameter($parameters, 0, 'endDate', $this), $this->getMagicParameter($parameters, 1, 'factor', 1), $unit ); } catch (InvalidArgumentException) { // Try macros } } return null; } private function callMacroMethod(string $method, array $parameters): mixed { return static::bindMacroContext($this, function () use (&$method, &$parameters) { $macro = $this->getLocalMacro($method); if (!$macro) { foreach ($this->getAllGenericMacros() as $callback) { try { return $this->executeCallable($callback, $method, ...$parameters); } catch (BadMethodCallException) { continue; } } if ($this->isLocalStrictModeEnabled()) { throw new UnknownMethodException($method); } return null; } return $this->executeCallable($macro, ...$parameters); }); } private static function floorZeroPad(int|float $value, int $length): string { return str_pad((string) floor($value), $length, '0', STR_PAD_LEFT); } /** * @template T of CarbonInterface * * @param T $date * * @return T */ private function mutateIfMutable(CarbonInterface $date): CarbonInterface { return $this instanceof DateTimeImmutable ? $date : $this->modify('@'.$date->rawFormat('U.u'))->setTimezone($date->getTimezone()); } }
PHP
{ "end_line": 2214, "name": "meridiem", "signature": "public function meridiem(bool $isLower = false): string", "start_line": 2183 }
{ "class_name": "Date", "class_signature": "trait Date", "namespace": "Carbon\\Traits" }
isoFormat
Carbon/src/Carbon/Traits/Date.php
public function isoFormat(string $format, ?string $originalFormat = null): string { $result = ''; $length = mb_strlen($format); $originalFormat ??= $format; $inEscaped = false; $formats = null; $units = null; for ($i = 0; $i < $length; $i++) { $char = mb_substr($format, $i, 1); if ($char === '\\') { $result .= mb_substr($format, ++$i, 1); continue; } if ($char === '[' && !$inEscaped) { $inEscaped = true; continue; } if ($char === ']' && $inEscaped) { $inEscaped = false; continue; } if ($inEscaped) { $result .= $char; continue; } $input = mb_substr($format, $i); if (preg_match('/^(LTS|LT|l{1,4}|L{1,4})/', $input, $match)) { if ($formats === null) { $formats = $this->getIsoFormats(); } $code = $match[0]; $sequence = $formats[$code] ?? preg_replace_callback( '/MMMM|MM|DD|dddd/', static fn ($code) => mb_substr($code[0], 1), $formats[strtoupper($code)] ?? '', ); $rest = mb_substr($format, $i + mb_strlen($code)); $format = mb_substr($format, 0, $i).$sequence.$rest; $length = mb_strlen($format); $input = $sequence.$rest; } if (preg_match('/^'.CarbonInterface::ISO_FORMAT_REGEXP.'/', $input, $match)) { $code = $match[0]; if ($units === null) { $units = static::getIsoUnits(); } $sequence = $units[$code] ?? ''; if ($sequence instanceof Closure) { $sequence = $sequence($this, $originalFormat); } elseif (\is_array($sequence)) { try { $sequence = $this->{$sequence[0]}(...$sequence[1]); } catch (ReflectionException | InvalidArgumentException | BadMethodCallException) { $sequence = ''; } } elseif (\is_string($sequence)) { $sequence = $this->$sequence ?? $code; } $format = mb_substr($format, 0, $i).$sequence.mb_substr($format, $i + mb_strlen($code)); $i += mb_strlen((string) $sequence) - 1; $length = mb_strlen($format); $char = $sequence; } $result .= $char; } return $result; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use BadMethodCallException; use Carbon\Carbon; use Carbon\CarbonInterface; use Carbon\CarbonPeriod; use Carbon\CarbonTimeZone; use Carbon\Exceptions\BadComparisonUnitException; use Carbon\Exceptions\ImmutableException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Exceptions\UnitException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\FactoryImmutable; use Carbon\Month; use Carbon\Translator; use Carbon\Unit; use Carbon\WeekDay; use Closure; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use ReflectionException; use Symfony\Component\Clock\NativeClock; use Throwable; /** * A simple API extension for DateTime. * * <autodoc generated by `composer phpdoc`> * * @property string $localeDayOfWeek the day of week in current locale * @property string $shortLocaleDayOfWeek the abbreviated day of week in current locale * @property string $localeMonth the month in current locale * @property string $shortLocaleMonth the abbreviated month in current locale * @property int $year * @property int $yearIso * @property int $month * @property int $day * @property int $hour * @property int $minute * @property int $second * @property int $micro * @property int $microsecond * @property int $dayOfWeekIso 1 (for Monday) through 7 (for Sunday) * @property int|float|string $timestamp seconds since the Unix Epoch * @property string $englishDayOfWeek the day of week in English * @property string $shortEnglishDayOfWeek the abbreviated day of week in English * @property string $englishMonth the month in English * @property string $shortEnglishMonth the abbreviated month in English * @property int $milliseconds * @property int $millisecond * @property int $milli * @property int $week 1 through 53 * @property int $isoWeek 1 through 53 * @property int $weekYear year according to week format * @property int $isoWeekYear year according to ISO week format * @property int $age does a diffInYears() with default parameters * @property int $offset the timezone offset in seconds from UTC * @property int $offsetMinutes the timezone offset in minutes from UTC * @property int $offsetHours the timezone offset in hours from UTC * @property CarbonTimeZone $timezone the current timezone * @property CarbonTimeZone $tz alias of $timezone * @property int $centuryOfMillennium The value of the century starting from the beginning of the current millennium * @property int $dayOfCentury The value of the day starting from the beginning of the current century * @property int $dayOfDecade The value of the day starting from the beginning of the current decade * @property int $dayOfMillennium The value of the day starting from the beginning of the current millennium * @property int $dayOfMonth The value of the day starting from the beginning of the current month * @property int $dayOfQuarter The value of the day starting from the beginning of the current quarter * @property int $dayOfWeek 0 (for Sunday) through 6 (for Saturday) * @property int $dayOfYear 1 through 366 * @property int $decadeOfCentury The value of the decade starting from the beginning of the current century * @property int $decadeOfMillennium The value of the decade starting from the beginning of the current millennium * @property int $hourOfCentury The value of the hour starting from the beginning of the current century * @property int $hourOfDay The value of the hour starting from the beginning of the current day * @property int $hourOfDecade The value of the hour starting from the beginning of the current decade * @property int $hourOfMillennium The value of the hour starting from the beginning of the current millennium * @property int $hourOfMonth The value of the hour starting from the beginning of the current month * @property int $hourOfQuarter The value of the hour starting from the beginning of the current quarter * @property int $hourOfWeek The value of the hour starting from the beginning of the current week * @property int $hourOfYear The value of the hour starting from the beginning of the current year * @property int $microsecondOfCentury The value of the microsecond starting from the beginning of the current century * @property int $microsecondOfDay The value of the microsecond starting from the beginning of the current day * @property int $microsecondOfDecade The value of the microsecond starting from the beginning of the current decade * @property int $microsecondOfHour The value of the microsecond starting from the beginning of the current hour * @property int $microsecondOfMillennium The value of the microsecond starting from the beginning of the current millennium * @property int $microsecondOfMillisecond The value of the microsecond starting from the beginning of the current millisecond * @property int $microsecondOfMinute The value of the microsecond starting from the beginning of the current minute * @property int $microsecondOfMonth The value of the microsecond starting from the beginning of the current month * @property int $microsecondOfQuarter The value of the microsecond starting from the beginning of the current quarter * @property int $microsecondOfSecond The value of the microsecond starting from the beginning of the current second * @property int $microsecondOfWeek The value of the microsecond starting from the beginning of the current week * @property int $microsecondOfYear The value of the microsecond starting from the beginning of the current year * @property int $millisecondOfCentury The value of the millisecond starting from the beginning of the current century * @property int $millisecondOfDay The value of the millisecond starting from the beginning of the current day * @property int $millisecondOfDecade The value of the millisecond starting from the beginning of the current decade * @property int $millisecondOfHour The value of the millisecond starting from the beginning of the current hour * @property int $millisecondOfMillennium The value of the millisecond starting from the beginning of the current millennium * @property int $millisecondOfMinute The value of the millisecond starting from the beginning of the current minute * @property int $millisecondOfMonth The value of the millisecond starting from the beginning of the current month * @property int $millisecondOfQuarter The value of the millisecond starting from the beginning of the current quarter * @property int $millisecondOfSecond The value of the millisecond starting from the beginning of the current second * @property int $millisecondOfWeek The value of the millisecond starting from the beginning of the current week * @property int $millisecondOfYear The value of the millisecond starting from the beginning of the current year * @property int $minuteOfCentury The value of the minute starting from the beginning of the current century * @property int $minuteOfDay The value of the minute starting from the beginning of the current day * @property int $minuteOfDecade The value of the minute starting from the beginning of the current decade * @property int $minuteOfHour The value of the minute starting from the beginning of the current hour * @property int $minuteOfMillennium The value of the minute starting from the beginning of the current millennium * @property int $minuteOfMonth The value of the minute starting from the beginning of the current month * @property int $minuteOfQuarter The value of the minute starting from the beginning of the current quarter * @property int $minuteOfWeek The value of the minute starting from the beginning of the current week * @property int $minuteOfYear The value of the minute starting from the beginning of the current year * @property int $monthOfCentury The value of the month starting from the beginning of the current century * @property int $monthOfDecade The value of the month starting from the beginning of the current decade * @property int $monthOfMillennium The value of the month starting from the beginning of the current millennium * @property int $monthOfQuarter The value of the month starting from the beginning of the current quarter * @property int $monthOfYear The value of the month starting from the beginning of the current year * @property int $quarterOfCentury The value of the quarter starting from the beginning of the current century * @property int $quarterOfDecade The value of the quarter starting from the beginning of the current decade * @property int $quarterOfMillennium The value of the quarter starting from the beginning of the current millennium * @property int $quarterOfYear The value of the quarter starting from the beginning of the current year * @property int $secondOfCentury The value of the second starting from the beginning of the current century * @property int $secondOfDay The value of the second starting from the beginning of the current day * @property int $secondOfDecade The value of the second starting from the beginning of the current decade * @property int $secondOfHour The value of the second starting from the beginning of the current hour * @property int $secondOfMillennium The value of the second starting from the beginning of the current millennium * @property int $secondOfMinute The value of the second starting from the beginning of the current minute * @property int $secondOfMonth The value of the second starting from the beginning of the current month * @property int $secondOfQuarter The value of the second starting from the beginning of the current quarter * @property int $secondOfWeek The value of the second starting from the beginning of the current week * @property int $secondOfYear The value of the second starting from the beginning of the current year * @property int $weekOfCentury The value of the week starting from the beginning of the current century * @property int $weekOfDecade The value of the week starting from the beginning of the current decade * @property int $weekOfMillennium The value of the week starting from the beginning of the current millennium * @property int $weekOfMonth 1 through 5 * @property int $weekOfQuarter The value of the week starting from the beginning of the current quarter * @property int $weekOfYear ISO-8601 week number of year, weeks starting on Monday * @property int $yearOfCentury The value of the year starting from the beginning of the current century * @property int $yearOfDecade The value of the year starting from the beginning of the current decade * @property int $yearOfMillennium The value of the year starting from the beginning of the current millennium * @property-read string $latinMeridiem "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) * @property-read string $latinUpperMeridiem "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) * @property-read string $timezoneAbbreviatedName the current timezone abbreviated name * @property-read string $tzAbbrName alias of $timezoneAbbreviatedName * @property-read string $dayName long name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $shortDayName short name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $minDayName very short name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $monthName long name of month translated according to Carbon locale, in english if no translation available for current language * @property-read string $shortMonthName short name of month translated according to Carbon locale, in english if no translation available for current language * @property-read string $meridiem lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language * @property-read string $upperMeridiem uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language * @property-read int $noZeroHour current hour from 1 to 24 * @property-read int $isoWeeksInYear 51 through 53 * @property-read int $weekNumberInMonth 1 through 5 * @property-read int $firstWeekDay 0 through 6 * @property-read int $lastWeekDay 0 through 6 * @property-read int $quarter the quarter of this instance, 1 - 4 * @property-read int $decade the decade of this instance * @property-read int $century the century of this instance * @property-read int $millennium the millennium of this instance * @property-read bool $dst daylight savings time indicator, true if DST, false otherwise * @property-read bool $local checks if the timezone is local, true if local, false otherwise * @property-read bool $utc checks if the timezone is UTC, true if UTC, false otherwise * @property-read string $timezoneName the current timezone name * @property-read string $tzName alias of $timezoneName * @property-read string $locale locale of the current instance * @property-read int $centuriesInMillennium The number of centuries contained in the current millennium * @property-read int $daysInCentury The number of days contained in the current century * @property-read int $daysInDecade The number of days contained in the current decade * @property-read int $daysInMillennium The number of days contained in the current millennium * @property-read int $daysInMonth number of days in the given month * @property-read int $daysInQuarter The number of days contained in the current quarter * @property-read int $daysInWeek The number of days contained in the current week * @property-read int $daysInYear 365 or 366 * @property-read int $decadesInCentury The number of decades contained in the current century * @property-read int $decadesInMillennium The number of decades contained in the current millennium * @property-read int $hoursInCentury The number of hours contained in the current century * @property-read int $hoursInDay The number of hours contained in the current day * @property-read int $hoursInDecade The number of hours contained in the current decade * @property-read int $hoursInMillennium The number of hours contained in the current millennium * @property-read int $hoursInMonth The number of hours contained in the current month * @property-read int $hoursInQuarter The number of hours contained in the current quarter * @property-read int $hoursInWeek The number of hours contained in the current week * @property-read int $hoursInYear The number of hours contained in the current year * @property-read int $microsecondsInCentury The number of microseconds contained in the current century * @property-read int $microsecondsInDay The number of microseconds contained in the current day * @property-read int $microsecondsInDecade The number of microseconds contained in the current decade * @property-read int $microsecondsInHour The number of microseconds contained in the current hour * @property-read int $microsecondsInMillennium The number of microseconds contained in the current millennium * @property-read int $microsecondsInMillisecond The number of microseconds contained in the current millisecond * @property-read int $microsecondsInMinute The number of microseconds contained in the current minute * @property-read int $microsecondsInMonth The number of microseconds contained in the current month * @property-read int $microsecondsInQuarter The number of microseconds contained in the current quarter * @property-read int $microsecondsInSecond The number of microseconds contained in the current second * @property-read int $microsecondsInWeek The number of microseconds contained in the current week * @property-read int $microsecondsInYear The number of microseconds contained in the current year * @property-read int $millisecondsInCentury The number of milliseconds contained in the current century * @property-read int $millisecondsInDay The number of milliseconds contained in the current day * @property-read int $millisecondsInDecade The number of milliseconds contained in the current decade * @property-read int $millisecondsInHour The number of milliseconds contained in the current hour * @property-read int $millisecondsInMillennium The number of milliseconds contained in the current millennium * @property-read int $millisecondsInMinute The number of milliseconds contained in the current minute * @property-read int $millisecondsInMonth The number of milliseconds contained in the current month * @property-read int $millisecondsInQuarter The number of milliseconds contained in the current quarter * @property-read int $millisecondsInSecond The number of milliseconds contained in the current second * @property-read int $millisecondsInWeek The number of milliseconds contained in the current week * @property-read int $millisecondsInYear The number of milliseconds contained in the current year * @property-read int $minutesInCentury The number of minutes contained in the current century * @property-read int $minutesInDay The number of minutes contained in the current day * @property-read int $minutesInDecade The number of minutes contained in the current decade * @property-read int $minutesInHour The number of minutes contained in the current hour * @property-read int $minutesInMillennium The number of minutes contained in the current millennium * @property-read int $minutesInMonth The number of minutes contained in the current month * @property-read int $minutesInQuarter The number of minutes contained in the current quarter * @property-read int $minutesInWeek The number of minutes contained in the current week * @property-read int $minutesInYear The number of minutes contained in the current year * @property-read int $monthsInCentury The number of months contained in the current century * @property-read int $monthsInDecade The number of months contained in the current decade * @property-read int $monthsInMillennium The number of months contained in the current millennium * @property-read int $monthsInQuarter The number of months contained in the current quarter * @property-read int $monthsInYear The number of months contained in the current year * @property-read int $quartersInCentury The number of quarters contained in the current century * @property-read int $quartersInDecade The number of quarters contained in the current decade * @property-read int $quartersInMillennium The number of quarters contained in the current millennium * @property-read int $quartersInYear The number of quarters contained in the current year * @property-read int $secondsInCentury The number of seconds contained in the current century * @property-read int $secondsInDay The number of seconds contained in the current day * @property-read int $secondsInDecade The number of seconds contained in the current decade * @property-read int $secondsInHour The number of seconds contained in the current hour * @property-read int $secondsInMillennium The number of seconds contained in the current millennium * @property-read int $secondsInMinute The number of seconds contained in the current minute * @property-read int $secondsInMonth The number of seconds contained in the current month * @property-read int $secondsInQuarter The number of seconds contained in the current quarter * @property-read int $secondsInWeek The number of seconds contained in the current week * @property-read int $secondsInYear The number of seconds contained in the current year * @property-read int $weeksInCentury The number of weeks contained in the current century * @property-read int $weeksInDecade The number of weeks contained in the current decade * @property-read int $weeksInMillennium The number of weeks contained in the current millennium * @property-read int $weeksInMonth The number of weeks contained in the current month * @property-read int $weeksInQuarter The number of weeks contained in the current quarter * @property-read int $weeksInYear 51 through 53 * @property-read int $yearsInCentury The number of years contained in the current century * @property-read int $yearsInDecade The number of years contained in the current decade * @property-read int $yearsInMillennium The number of years contained in the current millennium * * @method bool isUtc() Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) * @method bool isLocal() Check if the current instance has non-UTC timezone. * @method bool isValid() Check if the current instance is a valid date. * @method bool isDST() Check if the current instance is in a daylight saving time. * @method bool isSunday() Checks if the instance day is sunday. * @method bool isMonday() Checks if the instance day is monday. * @method bool isTuesday() Checks if the instance day is tuesday. * @method bool isWednesday() Checks if the instance day is wednesday. * @method bool isThursday() Checks if the instance day is thursday. * @method bool isFriday() Checks if the instance day is friday. * @method bool isSaturday() Checks if the instance day is saturday. * @method bool isSameYear(DateTimeInterface|string $date) Checks if the given date is in the same year as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentYear() Checks if the instance is in the same year as the current moment. * @method bool isNextYear() Checks if the instance is in the same year as the current moment next year. * @method bool isLastYear() Checks if the instance is in the same year as the current moment last year. * @method bool isCurrentMonth() Checks if the instance is in the same month as the current moment. * @method bool isNextMonth() Checks if the instance is in the same month as the current moment next month. * @method bool isLastMonth() Checks if the instance is in the same month as the current moment last month. * @method bool isSameWeek(DateTimeInterface|string $date) Checks if the given date is in the same week as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentWeek() Checks if the instance is in the same week as the current moment. * @method bool isNextWeek() Checks if the instance is in the same week as the current moment next week. * @method bool isLastWeek() Checks if the instance is in the same week as the current moment last week. * @method bool isSameDay(DateTimeInterface|string $date) Checks if the given date is in the same day as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentDay() Checks if the instance is in the same day as the current moment. * @method bool isNextDay() Checks if the instance is in the same day as the current moment next day. * @method bool isLastDay() Checks if the instance is in the same day as the current moment last day. * @method bool isSameHour(DateTimeInterface|string $date) Checks if the given date is in the same hour as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentHour() Checks if the instance is in the same hour as the current moment. * @method bool isNextHour() Checks if the instance is in the same hour as the current moment next hour. * @method bool isLastHour() Checks if the instance is in the same hour as the current moment last hour. * @method bool isSameMinute(DateTimeInterface|string $date) Checks if the given date is in the same minute as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMinute() Checks if the instance is in the same minute as the current moment. * @method bool isNextMinute() Checks if the instance is in the same minute as the current moment next minute. * @method bool isLastMinute() Checks if the instance is in the same minute as the current moment last minute. * @method bool isSameSecond(DateTimeInterface|string $date) Checks if the given date is in the same second as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentSecond() Checks if the instance is in the same second as the current moment. * @method bool isNextSecond() Checks if the instance is in the same second as the current moment next second. * @method bool isLastSecond() Checks if the instance is in the same second as the current moment last second. * @method bool isSameMilli(DateTimeInterface|string $date) Checks if the given date is in the same millisecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMilli() Checks if the instance is in the same millisecond as the current moment. * @method bool isNextMilli() Checks if the instance is in the same millisecond as the current moment next millisecond. * @method bool isLastMilli() Checks if the instance is in the same millisecond as the current moment last millisecond. * @method bool isSameMillisecond(DateTimeInterface|string $date) Checks if the given date is in the same millisecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMillisecond() Checks if the instance is in the same millisecond as the current moment. * @method bool isNextMillisecond() Checks if the instance is in the same millisecond as the current moment next millisecond. * @method bool isLastMillisecond() Checks if the instance is in the same millisecond as the current moment last millisecond. * @method bool isSameMicro(DateTimeInterface|string $date) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMicro() Checks if the instance is in the same microsecond as the current moment. * @method bool isNextMicro() Checks if the instance is in the same microsecond as the current moment next microsecond. * @method bool isLastMicro() Checks if the instance is in the same microsecond as the current moment last microsecond. * @method bool isSameMicrosecond(DateTimeInterface|string $date) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMicrosecond() Checks if the instance is in the same microsecond as the current moment. * @method bool isNextMicrosecond() Checks if the instance is in the same microsecond as the current moment next microsecond. * @method bool isLastMicrosecond() Checks if the instance is in the same microsecond as the current moment last microsecond. * @method bool isSameDecade(DateTimeInterface|string $date) Checks if the given date is in the same decade as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentDecade() Checks if the instance is in the same decade as the current moment. * @method bool isNextDecade() Checks if the instance is in the same decade as the current moment next decade. * @method bool isLastDecade() Checks if the instance is in the same decade as the current moment last decade. * @method bool isSameCentury(DateTimeInterface|string $date) Checks if the given date is in the same century as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentCentury() Checks if the instance is in the same century as the current moment. * @method bool isNextCentury() Checks if the instance is in the same century as the current moment next century. * @method bool isLastCentury() Checks if the instance is in the same century as the current moment last century. * @method bool isSameMillennium(DateTimeInterface|string $date) Checks if the given date is in the same millennium as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMillennium() Checks if the instance is in the same millennium as the current moment. * @method bool isNextMillennium() Checks if the instance is in the same millennium as the current moment next millennium. * @method bool isLastMillennium() Checks if the instance is in the same millennium as the current moment last millennium. * @method bool isCurrentQuarter() Checks if the instance is in the same quarter as the current moment. * @method bool isNextQuarter() Checks if the instance is in the same quarter as the current moment next quarter. * @method bool isLastQuarter() Checks if the instance is in the same quarter as the current moment last quarter. * @method CarbonInterface years(int $value) Set current instance year to the given value. * @method CarbonInterface year(int $value) Set current instance year to the given value. * @method CarbonInterface setYears(int $value) Set current instance year to the given value. * @method CarbonInterface setYear(int $value) Set current instance year to the given value. * @method CarbonInterface months(Month|int $value) Set current instance month to the given value. * @method CarbonInterface month(Month|int $value) Set current instance month to the given value. * @method CarbonInterface setMonths(Month|int $value) Set current instance month to the given value. * @method CarbonInterface setMonth(Month|int $value) Set current instance month to the given value. * @method CarbonInterface days(int $value) Set current instance day to the given value. * @method CarbonInterface day(int $value) Set current instance day to the given value. * @method CarbonInterface setDays(int $value) Set current instance day to the given value. * @method CarbonInterface setDay(int $value) Set current instance day to the given value. * @method CarbonInterface hours(int $value) Set current instance hour to the given value. * @method CarbonInterface hour(int $value) Set current instance hour to the given value. * @method CarbonInterface setHours(int $value) Set current instance hour to the given value. * @method CarbonInterface setHour(int $value) Set current instance hour to the given value. * @method CarbonInterface minutes(int $value) Set current instance minute to the given value. * @method CarbonInterface minute(int $value) Set current instance minute to the given value. * @method CarbonInterface setMinutes(int $value) Set current instance minute to the given value. * @method CarbonInterface setMinute(int $value) Set current instance minute to the given value. * @method CarbonInterface seconds(int $value) Set current instance second to the given value. * @method CarbonInterface second(int $value) Set current instance second to the given value. * @method CarbonInterface setSeconds(int $value) Set current instance second to the given value. * @method CarbonInterface setSecond(int $value) Set current instance second to the given value. * @method CarbonInterface millis(int $value) Set current instance millisecond to the given value. * @method CarbonInterface milli(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMillis(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMilli(int $value) Set current instance millisecond to the given value. * @method CarbonInterface milliseconds(int $value) Set current instance millisecond to the given value. * @method CarbonInterface millisecond(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMilliseconds(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMillisecond(int $value) Set current instance millisecond to the given value. * @method CarbonInterface micros(int $value) Set current instance microsecond to the given value. * @method CarbonInterface micro(int $value) Set current instance microsecond to the given value. * @method CarbonInterface setMicros(int $value) Set current instance microsecond to the given value. * @method CarbonInterface setMicro(int $value) Set current instance microsecond to the given value. * @method CarbonInterface microseconds(int $value) Set current instance microsecond to the given value. * @method CarbonInterface microsecond(int $value) Set current instance microsecond to the given value. * @method CarbonInterface setMicroseconds(int $value) Set current instance microsecond to the given value. * @method self setMicrosecond(int $value) Set current instance microsecond to the given value. * @method CarbonInterface addYears(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addYear() Add one year to the instance (using date interval). * @method CarbonInterface subYears(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subYear() Sub one year to the instance (using date interval). * @method CarbonInterface addYearsWithOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addYearWithOverflow() Add one year to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subYearsWithOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subYearWithOverflow() Sub one year to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addYearsWithoutOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearWithoutOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearsWithoutOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearWithoutOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearsWithNoOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearWithNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearsWithNoOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearWithNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearsNoOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearsNoOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonths(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMonth() Add one month to the instance (using date interval). * @method CarbonInterface subMonths(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMonth() Sub one month to the instance (using date interval). * @method CarbonInterface addMonthsWithOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMonthWithOverflow() Add one month to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMonthsWithOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMonthWithOverflow() Sub one month to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMonthsWithoutOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthWithoutOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthsWithoutOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthWithoutOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthsWithNoOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthWithNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthsWithNoOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthWithNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthsNoOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthsNoOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDays(int|float $value = 1) Add days (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addDay() Add one day to the instance (using date interval). * @method CarbonInterface subDays(int|float $value = 1) Sub days (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subDay() Sub one day to the instance (using date interval). * @method CarbonInterface addHours(int|float $value = 1) Add hours (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addHour() Add one hour to the instance (using date interval). * @method CarbonInterface subHours(int|float $value = 1) Sub hours (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subHour() Sub one hour to the instance (using date interval). * @method CarbonInterface addMinutes(int|float $value = 1) Add minutes (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMinute() Add one minute to the instance (using date interval). * @method CarbonInterface subMinutes(int|float $value = 1) Sub minutes (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMinute() Sub one minute to the instance (using date interval). * @method CarbonInterface addSeconds(int|float $value = 1) Add seconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addSecond() Add one second to the instance (using date interval). * @method CarbonInterface subSeconds(int|float $value = 1) Sub seconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subSecond() Sub one second to the instance (using date interval). * @method CarbonInterface addMillis(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMilli() Add one millisecond to the instance (using date interval). * @method CarbonInterface subMillis(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMilli() Sub one millisecond to the instance (using date interval). * @method CarbonInterface addMilliseconds(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMillisecond() Add one millisecond to the instance (using date interval). * @method CarbonInterface subMilliseconds(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMillisecond() Sub one millisecond to the instance (using date interval). * @method CarbonInterface addMicros(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMicro() Add one microsecond to the instance (using date interval). * @method CarbonInterface subMicros(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMicro() Sub one microsecond to the instance (using date interval). * @method CarbonInterface addMicroseconds(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMicrosecond() Add one microsecond to the instance (using date interval). * @method CarbonInterface subMicroseconds(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMicrosecond() Sub one microsecond to the instance (using date interval). * @method CarbonInterface addMillennia(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMillennium() Add one millennium to the instance (using date interval). * @method CarbonInterface subMillennia(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMillennium() Sub one millennium to the instance (using date interval). * @method CarbonInterface addMillenniaWithOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMillenniumWithOverflow() Add one millennium to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMillenniaWithOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMillenniumWithOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMillenniaWithoutOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniumWithoutOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniaWithoutOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniumWithoutOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniaWithNoOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniumWithNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniaWithNoOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniumWithNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniaNoOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniumNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniaNoOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniumNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturies(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addCentury() Add one century to the instance (using date interval). * @method CarbonInterface subCenturies(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subCentury() Sub one century to the instance (using date interval). * @method CarbonInterface addCenturiesWithOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addCenturyWithOverflow() Add one century to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subCenturiesWithOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subCenturyWithOverflow() Sub one century to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addCenturiesWithoutOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturyWithoutOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturiesWithoutOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturyWithoutOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturiesWithNoOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturyWithNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturiesWithNoOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturyWithNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturiesNoOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturyNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturiesNoOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturyNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecades(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addDecade() Add one decade to the instance (using date interval). * @method CarbonInterface subDecades(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subDecade() Sub one decade to the instance (using date interval). * @method CarbonInterface addDecadesWithOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addDecadeWithOverflow() Add one decade to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subDecadesWithOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subDecadeWithOverflow() Sub one decade to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addDecadesWithoutOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadeWithoutOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadesWithoutOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadeWithoutOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadesWithNoOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadeWithNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadesWithNoOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadeWithNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadesNoOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadeNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadesNoOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadeNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarters(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addQuarter() Add one quarter to the instance (using date interval). * @method CarbonInterface subQuarters(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subQuarter() Sub one quarter to the instance (using date interval). * @method CarbonInterface addQuartersWithOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addQuarterWithOverflow() Add one quarter to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subQuartersWithOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subQuarterWithOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addQuartersWithoutOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarterWithoutOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuartersWithoutOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuarterWithoutOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuartersWithNoOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarterWithNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuartersWithNoOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuarterWithNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuartersNoOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarterNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuartersNoOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuarterNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addWeeks(int|float $value = 1) Add weeks (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addWeek() Add one week to the instance (using date interval). * @method CarbonInterface subWeeks(int|float $value = 1) Sub weeks (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subWeek() Sub one week to the instance (using date interval). * @method CarbonInterface addWeekdays(int|float $value = 1) Add weekdays (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addWeekday() Add one weekday to the instance (using date interval). * @method CarbonInterface subWeekdays(int|float $value = 1) Sub weekdays (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subWeekday() Sub one weekday to the instance (using date interval). * @method CarbonInterface addUTCMicros(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMicro() Add one microsecond to the instance (using timestamp). * @method CarbonInterface subUTCMicros(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMicro() Sub one microsecond to the instance (using timestamp). * @method CarbonPeriod microsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. * @method float diffInUTCMicros(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of microseconds. * @method CarbonInterface addUTCMicroseconds(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMicrosecond() Add one microsecond to the instance (using timestamp). * @method CarbonInterface subUTCMicroseconds(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMicrosecond() Sub one microsecond to the instance (using timestamp). * @method CarbonPeriod microsecondsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. * @method float diffInUTCMicroseconds(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of microseconds. * @method CarbonInterface addUTCMillis(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMilli() Add one millisecond to the instance (using timestamp). * @method CarbonInterface subUTCMillis(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMilli() Sub one millisecond to the instance (using timestamp). * @method CarbonPeriod millisUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. * @method float diffInUTCMillis(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of milliseconds. * @method CarbonInterface addUTCMilliseconds(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMillisecond() Add one millisecond to the instance (using timestamp). * @method CarbonInterface subUTCMilliseconds(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMillisecond() Sub one millisecond to the instance (using timestamp). * @method CarbonPeriod millisecondsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. * @method float diffInUTCMilliseconds(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of milliseconds. * @method CarbonInterface addUTCSeconds(int|float $value = 1) Add seconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCSecond() Add one second to the instance (using timestamp). * @method CarbonInterface subUTCSeconds(int|float $value = 1) Sub seconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCSecond() Sub one second to the instance (using timestamp). * @method CarbonPeriod secondsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each second or every X seconds if a factor is given. * @method float diffInUTCSeconds(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of seconds. * @method CarbonInterface addUTCMinutes(int|float $value = 1) Add minutes (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMinute() Add one minute to the instance (using timestamp). * @method CarbonInterface subUTCMinutes(int|float $value = 1) Sub minutes (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMinute() Sub one minute to the instance (using timestamp). * @method CarbonPeriod minutesUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each minute or every X minutes if a factor is given. * @method float diffInUTCMinutes(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of minutes. * @method CarbonInterface addUTCHours(int|float $value = 1) Add hours (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCHour() Add one hour to the instance (using timestamp). * @method CarbonInterface subUTCHours(int|float $value = 1) Sub hours (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCHour() Sub one hour to the instance (using timestamp). * @method CarbonPeriod hoursUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each hour or every X hours if a factor is given. * @method float diffInUTCHours(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of hours. * @method CarbonInterface addUTCDays(int|float $value = 1) Add days (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCDay() Add one day to the instance (using timestamp). * @method CarbonInterface subUTCDays(int|float $value = 1) Sub days (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCDay() Sub one day to the instance (using timestamp). * @method CarbonPeriod daysUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each day or every X days if a factor is given. * @method float diffInUTCDays(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of days. * @method CarbonInterface addUTCWeeks(int|float $value = 1) Add weeks (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCWeek() Add one week to the instance (using timestamp). * @method CarbonInterface subUTCWeeks(int|float $value = 1) Sub weeks (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCWeek() Sub one week to the instance (using timestamp). * @method CarbonPeriod weeksUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each week or every X weeks if a factor is given. * @method float diffInUTCWeeks(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of weeks. * @method CarbonInterface addUTCMonths(int|float $value = 1) Add months (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMonth() Add one month to the instance (using timestamp). * @method CarbonInterface subUTCMonths(int|float $value = 1) Sub months (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMonth() Sub one month to the instance (using timestamp). * @method CarbonPeriod monthsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each month or every X months if a factor is given. * @method float diffInUTCMonths(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of months. * @method CarbonInterface addUTCQuarters(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCQuarter() Add one quarter to the instance (using timestamp). * @method CarbonInterface subUTCQuarters(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCQuarter() Sub one quarter to the instance (using timestamp). * @method CarbonPeriod quartersUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each quarter or every X quarters if a factor is given. * @method float diffInUTCQuarters(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of quarters. * @method CarbonInterface addUTCYears(int|float $value = 1) Add years (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCYear() Add one year to the instance (using timestamp). * @method CarbonInterface subUTCYears(int|float $value = 1) Sub years (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCYear() Sub one year to the instance (using timestamp). * @method CarbonPeriod yearsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each year or every X years if a factor is given. * @method float diffInUTCYears(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of years. * @method CarbonInterface addUTCDecades(int|float $value = 1) Add decades (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCDecade() Add one decade to the instance (using timestamp). * @method CarbonInterface subUTCDecades(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCDecade() Sub one decade to the instance (using timestamp). * @method CarbonPeriod decadesUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each decade or every X decades if a factor is given. * @method float diffInUTCDecades(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of decades. * @method CarbonInterface addUTCCenturies(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCCentury() Add one century to the instance (using timestamp). * @method CarbonInterface subUTCCenturies(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCCentury() Sub one century to the instance (using timestamp). * @method CarbonPeriod centuriesUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each century or every X centuries if a factor is given. * @method float diffInUTCCenturies(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of centuries. * @method CarbonInterface addUTCMillennia(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMillennium() Add one millennium to the instance (using timestamp). * @method CarbonInterface subUTCMillennia(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMillennium() Sub one millennium to the instance (using timestamp). * @method CarbonPeriod millenniaUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millennium or every X millennia if a factor is given. * @method float diffInUTCMillennia(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of millennia. * @method CarbonInterface roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method CarbonInterface roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method CarbonInterface floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method CarbonInterface floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method CarbonInterface ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method CarbonInterface ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method CarbonInterface roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method CarbonInterface roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method CarbonInterface floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method CarbonInterface floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method CarbonInterface ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method CarbonInterface ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method CarbonInterface roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method CarbonInterface roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method CarbonInterface floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method CarbonInterface floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method CarbonInterface ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method CarbonInterface ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method CarbonInterface roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method CarbonInterface roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method CarbonInterface floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method CarbonInterface floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method CarbonInterface ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method CarbonInterface ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method CarbonInterface roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method CarbonInterface roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method CarbonInterface floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method CarbonInterface floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method CarbonInterface ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method CarbonInterface ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method CarbonInterface roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method CarbonInterface roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method CarbonInterface floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method CarbonInterface floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method CarbonInterface ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method CarbonInterface ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method CarbonInterface roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method CarbonInterface roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method CarbonInterface floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method CarbonInterface floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method CarbonInterface ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method CarbonInterface ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method CarbonInterface roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method CarbonInterface roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method CarbonInterface floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method CarbonInterface floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method CarbonInterface ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method CarbonInterface ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method CarbonInterface roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method CarbonInterface roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method CarbonInterface floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method CarbonInterface floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method CarbonInterface ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method CarbonInterface ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method CarbonInterface roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method CarbonInterface roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method CarbonInterface floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method CarbonInterface floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method CarbonInterface ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method CarbonInterface ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method CarbonInterface roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method CarbonInterface roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method CarbonInterface floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method CarbonInterface floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method CarbonInterface ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method CarbonInterface ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method CarbonInterface roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method CarbonInterface roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method CarbonInterface floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method CarbonInterface floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method CarbonInterface ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method CarbonInterface ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * @method string shortAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string shortRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string shortRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string shortRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method int centuriesInMillennium() Return the number of centuries contained in the current millennium * @method int|static centuryOfMillennium(?int $century = null) Return the value of the century starting from the beginning of the current millennium when called with no parameters, change the current century when called with an integer value * @method int|static dayOfCentury(?int $day = null) Return the value of the day starting from the beginning of the current century when called with no parameters, change the current day when called with an integer value * @method int|static dayOfDecade(?int $day = null) Return the value of the day starting from the beginning of the current decade when called with no parameters, change the current day when called with an integer value * @method int|static dayOfMillennium(?int $day = null) Return the value of the day starting from the beginning of the current millennium when called with no parameters, change the current day when called with an integer value * @method int|static dayOfMonth(?int $day = null) Return the value of the day starting from the beginning of the current month when called with no parameters, change the current day when called with an integer value * @method int|static dayOfQuarter(?int $day = null) Return the value of the day starting from the beginning of the current quarter when called with no parameters, change the current day when called with an integer value * @method int|static dayOfWeek(?int $day = null) Return the value of the day starting from the beginning of the current week when called with no parameters, change the current day when called with an integer value * @method int daysInCentury() Return the number of days contained in the current century * @method int daysInDecade() Return the number of days contained in the current decade * @method int daysInMillennium() Return the number of days contained in the current millennium * @method int daysInMonth() Return the number of days contained in the current month * @method int daysInQuarter() Return the number of days contained in the current quarter * @method int daysInWeek() Return the number of days contained in the current week * @method int daysInYear() Return the number of days contained in the current year * @method int|static decadeOfCentury(?int $decade = null) Return the value of the decade starting from the beginning of the current century when called with no parameters, change the current decade when called with an integer value * @method int|static decadeOfMillennium(?int $decade = null) Return the value of the decade starting from the beginning of the current millennium when called with no parameters, change the current decade when called with an integer value * @method int decadesInCentury() Return the number of decades contained in the current century * @method int decadesInMillennium() Return the number of decades contained in the current millennium * @method int|static hourOfCentury(?int $hour = null) Return the value of the hour starting from the beginning of the current century when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfDay(?int $hour = null) Return the value of the hour starting from the beginning of the current day when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfDecade(?int $hour = null) Return the value of the hour starting from the beginning of the current decade when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfMillennium(?int $hour = null) Return the value of the hour starting from the beginning of the current millennium when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfMonth(?int $hour = null) Return the value of the hour starting from the beginning of the current month when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfQuarter(?int $hour = null) Return the value of the hour starting from the beginning of the current quarter when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfWeek(?int $hour = null) Return the value of the hour starting from the beginning of the current week when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfYear(?int $hour = null) Return the value of the hour starting from the beginning of the current year when called with no parameters, change the current hour when called with an integer value * @method int hoursInCentury() Return the number of hours contained in the current century * @method int hoursInDay() Return the number of hours contained in the current day * @method int hoursInDecade() Return the number of hours contained in the current decade * @method int hoursInMillennium() Return the number of hours contained in the current millennium * @method int hoursInMonth() Return the number of hours contained in the current month * @method int hoursInQuarter() Return the number of hours contained in the current quarter * @method int hoursInWeek() Return the number of hours contained in the current week * @method int hoursInYear() Return the number of hours contained in the current year * @method int|static microsecondOfCentury(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current century when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfDay(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current day when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfDecade(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current decade when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfHour(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current hour when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMillennium(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current millennium when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMillisecond(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current millisecond when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMinute(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current minute when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMonth(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current month when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfQuarter(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current quarter when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfSecond(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current second when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfWeek(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current week when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfYear(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current year when called with no parameters, change the current microsecond when called with an integer value * @method int microsecondsInCentury() Return the number of microseconds contained in the current century * @method int microsecondsInDay() Return the number of microseconds contained in the current day * @method int microsecondsInDecade() Return the number of microseconds contained in the current decade * @method int microsecondsInHour() Return the number of microseconds contained in the current hour * @method int microsecondsInMillennium() Return the number of microseconds contained in the current millennium * @method int microsecondsInMillisecond() Return the number of microseconds contained in the current millisecond * @method int microsecondsInMinute() Return the number of microseconds contained in the current minute * @method int microsecondsInMonth() Return the number of microseconds contained in the current month * @method int microsecondsInQuarter() Return the number of microseconds contained in the current quarter * @method int microsecondsInSecond() Return the number of microseconds contained in the current second * @method int microsecondsInWeek() Return the number of microseconds contained in the current week * @method int microsecondsInYear() Return the number of microseconds contained in the current year * @method int|static millisecondOfCentury(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current century when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfDay(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current day when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfDecade(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current decade when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfHour(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current hour when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfMillennium(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current millennium when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfMinute(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current minute when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfMonth(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current month when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfQuarter(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current quarter when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfSecond(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current second when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfWeek(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current week when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfYear(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current year when called with no parameters, change the current millisecond when called with an integer value * @method int millisecondsInCentury() Return the number of milliseconds contained in the current century * @method int millisecondsInDay() Return the number of milliseconds contained in the current day * @method int millisecondsInDecade() Return the number of milliseconds contained in the current decade * @method int millisecondsInHour() Return the number of milliseconds contained in the current hour * @method int millisecondsInMillennium() Return the number of milliseconds contained in the current millennium * @method int millisecondsInMinute() Return the number of milliseconds contained in the current minute * @method int millisecondsInMonth() Return the number of milliseconds contained in the current month * @method int millisecondsInQuarter() Return the number of milliseconds contained in the current quarter * @method int millisecondsInSecond() Return the number of milliseconds contained in the current second * @method int millisecondsInWeek() Return the number of milliseconds contained in the current week * @method int millisecondsInYear() Return the number of milliseconds contained in the current year * @method int|static minuteOfCentury(?int $minute = null) Return the value of the minute starting from the beginning of the current century when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfDay(?int $minute = null) Return the value of the minute starting from the beginning of the current day when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfDecade(?int $minute = null) Return the value of the minute starting from the beginning of the current decade when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfHour(?int $minute = null) Return the value of the minute starting from the beginning of the current hour when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfMillennium(?int $minute = null) Return the value of the minute starting from the beginning of the current millennium when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfMonth(?int $minute = null) Return the value of the minute starting from the beginning of the current month when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfQuarter(?int $minute = null) Return the value of the minute starting from the beginning of the current quarter when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfWeek(?int $minute = null) Return the value of the minute starting from the beginning of the current week when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfYear(?int $minute = null) Return the value of the minute starting from the beginning of the current year when called with no parameters, change the current minute when called with an integer value * @method int minutesInCentury() Return the number of minutes contained in the current century * @method int minutesInDay() Return the number of minutes contained in the current day * @method int minutesInDecade() Return the number of minutes contained in the current decade * @method int minutesInHour() Return the number of minutes contained in the current hour * @method int minutesInMillennium() Return the number of minutes contained in the current millennium * @method int minutesInMonth() Return the number of minutes contained in the current month * @method int minutesInQuarter() Return the number of minutes contained in the current quarter * @method int minutesInWeek() Return the number of minutes contained in the current week * @method int minutesInYear() Return the number of minutes contained in the current year * @method int|static monthOfCentury(?int $month = null) Return the value of the month starting from the beginning of the current century when called with no parameters, change the current month when called with an integer value * @method int|static monthOfDecade(?int $month = null) Return the value of the month starting from the beginning of the current decade when called with no parameters, change the current month when called with an integer value * @method int|static monthOfMillennium(?int $month = null) Return the value of the month starting from the beginning of the current millennium when called with no parameters, change the current month when called with an integer value * @method int|static monthOfQuarter(?int $month = null) Return the value of the month starting from the beginning of the current quarter when called with no parameters, change the current month when called with an integer value * @method int|static monthOfYear(?int $month = null) Return the value of the month starting from the beginning of the current year when called with no parameters, change the current month when called with an integer value * @method int monthsInCentury() Return the number of months contained in the current century * @method int monthsInDecade() Return the number of months contained in the current decade * @method int monthsInMillennium() Return the number of months contained in the current millennium * @method int monthsInQuarter() Return the number of months contained in the current quarter * @method int monthsInYear() Return the number of months contained in the current year * @method int|static quarterOfCentury(?int $quarter = null) Return the value of the quarter starting from the beginning of the current century when called with no parameters, change the current quarter when called with an integer value * @method int|static quarterOfDecade(?int $quarter = null) Return the value of the quarter starting from the beginning of the current decade when called with no parameters, change the current quarter when called with an integer value * @method int|static quarterOfMillennium(?int $quarter = null) Return the value of the quarter starting from the beginning of the current millennium when called with no parameters, change the current quarter when called with an integer value * @method int|static quarterOfYear(?int $quarter = null) Return the value of the quarter starting from the beginning of the current year when called with no parameters, change the current quarter when called with an integer value * @method int quartersInCentury() Return the number of quarters contained in the current century * @method int quartersInDecade() Return the number of quarters contained in the current decade * @method int quartersInMillennium() Return the number of quarters contained in the current millennium * @method int quartersInYear() Return the number of quarters contained in the current year * @method int|static secondOfCentury(?int $second = null) Return the value of the second starting from the beginning of the current century when called with no parameters, change the current second when called with an integer value * @method int|static secondOfDay(?int $second = null) Return the value of the second starting from the beginning of the current day when called with no parameters, change the current second when called with an integer value * @method int|static secondOfDecade(?int $second = null) Return the value of the second starting from the beginning of the current decade when called with no parameters, change the current second when called with an integer value * @method int|static secondOfHour(?int $second = null) Return the value of the second starting from the beginning of the current hour when called with no parameters, change the current second when called with an integer value * @method int|static secondOfMillennium(?int $second = null) Return the value of the second starting from the beginning of the current millennium when called with no parameters, change the current second when called with an integer value * @method int|static secondOfMinute(?int $second = null) Return the value of the second starting from the beginning of the current minute when called with no parameters, change the current second when called with an integer value * @method int|static secondOfMonth(?int $second = null) Return the value of the second starting from the beginning of the current month when called with no parameters, change the current second when called with an integer value * @method int|static secondOfQuarter(?int $second = null) Return the value of the second starting from the beginning of the current quarter when called with no parameters, change the current second when called with an integer value * @method int|static secondOfWeek(?int $second = null) Return the value of the second starting from the beginning of the current week when called with no parameters, change the current second when called with an integer value * @method int|static secondOfYear(?int $second = null) Return the value of the second starting from the beginning of the current year when called with no parameters, change the current second when called with an integer value * @method int secondsInCentury() Return the number of seconds contained in the current century * @method int secondsInDay() Return the number of seconds contained in the current day * @method int secondsInDecade() Return the number of seconds contained in the current decade * @method int secondsInHour() Return the number of seconds contained in the current hour * @method int secondsInMillennium() Return the number of seconds contained in the current millennium * @method int secondsInMinute() Return the number of seconds contained in the current minute * @method int secondsInMonth() Return the number of seconds contained in the current month * @method int secondsInQuarter() Return the number of seconds contained in the current quarter * @method int secondsInWeek() Return the number of seconds contained in the current week * @method int secondsInYear() Return the number of seconds contained in the current year * @method int|static weekOfCentury(?int $week = null) Return the value of the week starting from the beginning of the current century when called with no parameters, change the current week when called with an integer value * @method int|static weekOfDecade(?int $week = null) Return the value of the week starting from the beginning of the current decade when called with no parameters, change the current week when called with an integer value * @method int|static weekOfMillennium(?int $week = null) Return the value of the week starting from the beginning of the current millennium when called with no parameters, change the current week when called with an integer value * @method int|static weekOfMonth(?int $week = null) Return the value of the week starting from the beginning of the current month when called with no parameters, change the current week when called with an integer value * @method int|static weekOfQuarter(?int $week = null) Return the value of the week starting from the beginning of the current quarter when called with no parameters, change the current week when called with an integer value * @method int|static weekOfYear(?int $week = null) Return the value of the week starting from the beginning of the current year when called with no parameters, change the current week when called with an integer value * @method int weeksInCentury() Return the number of weeks contained in the current century * @method int weeksInDecade() Return the number of weeks contained in the current decade * @method int weeksInMillennium() Return the number of weeks contained in the current millennium * @method int weeksInMonth() Return the number of weeks contained in the current month * @method int weeksInQuarter() Return the number of weeks contained in the current quarter * @method int|static yearOfCentury(?int $year = null) Return the value of the year starting from the beginning of the current century when called with no parameters, change the current year when called with an integer value * @method int|static yearOfDecade(?int $year = null) Return the value of the year starting from the beginning of the current decade when called with no parameters, change the current year when called with an integer value * @method int|static yearOfMillennium(?int $year = null) Return the value of the year starting from the beginning of the current millennium when called with no parameters, change the current year when called with an integer value * @method int yearsInCentury() Return the number of years contained in the current century * @method int yearsInDecade() Return the number of years contained in the current decade * @method int yearsInMillennium() Return the number of years contained in the current millennium * * </autodoc> */ trait Date { use Boundaries; use Comparison; use Converter; use Creator; use Difference; use Macro; use MagicParameter; use Modifiers; use Mutability; use ObjectInitialisation; use Options; use Rounding; use Serialization; use Test; use Timestamp; use Units; use Week; /** * Names of days of the week. * * @var array */ protected static $days = [ // @call isDayOfWeek CarbonInterface::SUNDAY => 'Sunday', // @call isDayOfWeek CarbonInterface::MONDAY => 'Monday', // @call isDayOfWeek CarbonInterface::TUESDAY => 'Tuesday', // @call isDayOfWeek CarbonInterface::WEDNESDAY => 'Wednesday', // @call isDayOfWeek CarbonInterface::THURSDAY => 'Thursday', // @call isDayOfWeek CarbonInterface::FRIDAY => 'Friday', // @call isDayOfWeek CarbonInterface::SATURDAY => 'Saturday', ]; /** * List of unit and magic methods associated as doc-comments. * * @var array */ protected static $units = [ // @call setUnit // @call addUnit 'year', // @call setUnit // @call addUnit 'month', // @call setUnit // @call addUnit 'day', // @call setUnit // @call addUnit 'hour', // @call setUnit // @call addUnit 'minute', // @call setUnit // @call addUnit 'second', // @call setUnit // @call addUnit 'milli', // @call setUnit // @call addUnit 'millisecond', // @call setUnit // @call addUnit 'micro', // @call setUnit // @call addUnit 'microsecond', ]; /** * Creates a DateTimeZone from a string, DateTimeZone or integer offset. * * @param DateTimeZone|string|int|false|null $object original value to get CarbonTimeZone from it. * @param DateTimeZone|string|int|false|null $objectDump dump of the object for error messages. * * @throws InvalidTimeZoneException * * @return CarbonTimeZone|null */ protected static function safeCreateDateTimeZone( DateTimeZone|string|int|false|null $object, DateTimeZone|string|int|false|null $objectDump = null, ): ?CarbonTimeZone { return CarbonTimeZone::instance($object, $objectDump); } /** * Get the TimeZone associated with the Carbon instance (as CarbonTimeZone). * * @link https://php.net/manual/en/datetime.gettimezone.php */ public function getTimezone(): CarbonTimeZone { return $this->transmitFactory(fn () => CarbonTimeZone::instance(parent::getTimezone())); } /** * List of minimum and maximums for each unit. */ protected static function getRangesByUnit(int $daysInMonth = 31): array { return [ // @call roundUnit 'year' => [1, 9999], // @call roundUnit 'month' => [1, static::MONTHS_PER_YEAR], // @call roundUnit 'day' => [1, $daysInMonth], // @call roundUnit 'hour' => [0, static::HOURS_PER_DAY - 1], // @call roundUnit 'minute' => [0, static::MINUTES_PER_HOUR - 1], // @call roundUnit 'second' => [0, static::SECONDS_PER_MINUTE - 1], ]; } /** * Get a copy of the instance. * * @return static */ public function copy() { return clone $this; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Clone the current instance if it's mutable. * * This method is convenient to ensure you don't mutate the initial object * but avoid to make a useless copy of it if it's already immutable. * * @return static */ public function avoidMutation(): static { if ($this instanceof DateTimeImmutable) { return $this; } return clone $this; } /** * Returns a present instance in the same timezone. * * @return static */ public function nowWithSameTz(): static { $timezone = $this->getTimezone(); return $this->getClock()?->nowAs(static::class, $timezone) ?? static::now($timezone); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|DateTimeInterface|string|null $date * * @return static */ public function carbonize($date = null) { if ($date instanceof DateInterval) { return $this->avoidMutation()->add($date); } if ($date instanceof DatePeriod || $date instanceof CarbonPeriod) { $date = $date->getStartDate(); } return $this->resolveCarbon($date); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the Carbon object. * * @throws UnknownGetterException * * @return string|int|bool|DateTimeZone|null */ public function __get(string $name): mixed { return $this->get($name); } /** * Get a part of the Carbon object. * * @throws UnknownGetterException * * @return string|int|bool|DateTimeZone */ public function get(Unit|string $name): mixed { static $localizedFormats = [ // @property string the day of week in current locale 'localeDayOfWeek' => 'dddd', // @property string the abbreviated day of week in current locale 'shortLocaleDayOfWeek' => 'ddd', // @property string the month in current locale 'localeMonth' => 'MMMM', // @property string the abbreviated month in current locale 'shortLocaleMonth' => 'MMM', ]; $name = Unit::toName($name); if (isset($localizedFormats[$name])) { return $this->isoFormat($localizedFormats[$name]); } static $formats = [ // @property int 'year' => 'Y', // @property int 'yearIso' => 'o', // @--property-read int // @--property-write Month|int // @property int 'month' => 'n', // @property int 'day' => 'j', // @property int 'hour' => 'G', // @property int 'minute' => 'i', // @property int 'second' => 's', // @property int 'micro' => 'u', // @property int 'microsecond' => 'u', // @property int 0 (for Sunday) through 6 (for Saturday) 'dayOfWeek' => 'w', // @property int 1 (for Monday) through 7 (for Sunday) 'dayOfWeekIso' => 'N', // @property int ISO-8601 week number of year, weeks starting on Monday 'weekOfYear' => 'W', // @property-read int number of days in the given month 'daysInMonth' => 't', // @property int|float|string seconds since the Unix Epoch 'timestamp' => 'U', // @property-read string "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) 'latinMeridiem' => 'a', // @property-read string "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) 'latinUpperMeridiem' => 'A', // @property string the day of week in English 'englishDayOfWeek' => 'l', // @property string the abbreviated day of week in English 'shortEnglishDayOfWeek' => 'D', // @property string the month in English 'englishMonth' => 'F', // @property string the abbreviated month in English 'shortEnglishMonth' => 'M', // @property-read string $timezoneAbbreviatedName the current timezone abbreviated name 'timezoneAbbreviatedName' => 'T', // @property-read string $tzAbbrName alias of $timezoneAbbreviatedName 'tzAbbrName' => 'T', ]; switch (true) { case isset($formats[$name]): $value = $this->rawFormat($formats[$name]); return is_numeric($value) ? (int) $value : $value; // @property-read string long name of weekday translated according to Carbon locale, in english if no translation available for current language case $name === 'dayName': return $this->getTranslatedDayName(); // @property-read string short name of weekday translated according to Carbon locale, in english if no translation available for current language case $name === 'shortDayName': return $this->getTranslatedShortDayName(); // @property-read string very short name of weekday translated according to Carbon locale, in english if no translation available for current language case $name === 'minDayName': return $this->getTranslatedMinDayName(); // @property-read string long name of month translated according to Carbon locale, in english if no translation available for current language case $name === 'monthName': return $this->getTranslatedMonthName(); // @property-read string short name of month translated according to Carbon locale, in english if no translation available for current language case $name === 'shortMonthName': return $this->getTranslatedShortMonthName(); // @property-read string lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language case $name === 'meridiem': return $this->meridiem(true); // @property-read string uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language case $name === 'upperMeridiem': return $this->meridiem(); // @property-read int current hour from 1 to 24 case $name === 'noZeroHour': return $this->hour ?: 24; // @property int case $name === 'milliseconds': // @property int case $name === 'millisecond': // @property int case $name === 'milli': return (int) floor(((int) $this->rawFormat('u')) / 1000); // @property int 1 through 53 case $name === 'week': return (int) $this->week(); // @property int 1 through 53 case $name === 'isoWeek': return (int) $this->isoWeek(); // @property int year according to week format case $name === 'weekYear': return (int) $this->weekYear(); // @property int year according to ISO week format case $name === 'isoWeekYear': return (int) $this->isoWeekYear(); // @property-read int 51 through 53 case $name === 'weeksInYear': return $this->weeksInYear(); // @property-read int 51 through 53 case $name === 'isoWeeksInYear': return $this->isoWeeksInYear(); // @property int 1 through 5 case $name === 'weekOfMonth': return (int) ceil($this->day / static::DAYS_PER_WEEK); // @property-read int 1 through 5 case $name === 'weekNumberInMonth': return (int) ceil(($this->day + $this->avoidMutation()->startOfMonth()->dayOfWeekIso - 1) / static::DAYS_PER_WEEK); // @property-read int 0 through 6 case $name === 'firstWeekDay': return (int) $this->getTranslationMessage('first_day_of_week'); // @property-read int 0 through 6 case $name === 'lastWeekDay': return $this->transmitFactory(fn () => static::weekRotate((int) $this->getTranslationMessage('first_day_of_week'), -1)); // @property int 1 through 366 case $name === 'dayOfYear': return 1 + (int) ($this->rawFormat('z')); // @property-read int 365 or 366 case $name === 'daysInYear': return static::DAYS_PER_YEAR + ($this->isLeapYear() ? 1 : 0); // @property int does a diffInYears() with default parameters case $name === 'age': return (int) $this->diffInYears(); // @property-read int the quarter of this instance, 1 - 4 case $name === 'quarter': return (int) ceil($this->month / static::MONTHS_PER_QUARTER); // @property-read int the decade of this instance // @call isSameUnit case $name === 'decade': return (int) ceil($this->year / static::YEARS_PER_DECADE); // @property-read int the century of this instance // @call isSameUnit case $name === 'century': $factor = 1; $year = $this->year; if ($year < 0) { $year = -$year; $factor = -1; } return (int) ($factor * ceil($year / static::YEARS_PER_CENTURY)); // @property-read int the millennium of this instance // @call isSameUnit case $name === 'millennium': $factor = 1; $year = $this->year; if ($year < 0) { $year = -$year; $factor = -1; } return (int) ($factor * ceil($year / static::YEARS_PER_MILLENNIUM)); // @property int the timezone offset in seconds from UTC case $name === 'offset': return $this->getOffset(); // @property int the timezone offset in minutes from UTC case $name === 'offsetMinutes': return $this->getOffset() / static::SECONDS_PER_MINUTE; // @property int the timezone offset in hours from UTC case $name === 'offsetHours': return $this->getOffset() / static::SECONDS_PER_MINUTE / static::MINUTES_PER_HOUR; // @property-read bool daylight savings time indicator, true if DST, false otherwise case $name === 'dst': return $this->rawFormat('I') === '1'; // @property-read bool checks if the timezone is local, true if local, false otherwise case $name === 'local': return $this->getOffset() === $this->avoidMutation()->setTimezone(date_default_timezone_get())->getOffset(); // @property-read bool checks if the timezone is UTC, true if UTC, false otherwise case $name === 'utc': return $this->getOffset() === 0; // @--property-write DateTimeZone|string|int $timezone the current timezone // @--property-write DateTimeZone|string|int $tz alias of $timezone // @--property-read CarbonTimeZone $timezone the current timezone // @--property-read CarbonTimeZone $tz alias of $timezone // @property CarbonTimeZone $timezone the current timezone // @property CarbonTimeZone $tz alias of $timezone case $name === 'timezone' || $name === 'tz': return $this->getTimezone(); // @property-read string $timezoneName the current timezone name // @property-read string $tzName alias of $timezoneName case $name === 'timezoneName' || $name === 'tzName': return $this->getTimezone()->getName(); // @property-read string locale of the current instance case $name === 'locale': return $this->getTranslatorLocale(); case preg_match('/^([a-z]{2,})(In|Of)([A-Z][a-z]+)$/', $name, $match): [, $firstUnit, $operator, $secondUnit] = $match; try { $start = $this->avoidMutation()->startOf($secondUnit); $value = $operator === 'Of' ? (\in_array($firstUnit, [ // Unit with indexes starting at 1 (other units start at 0) 'day', 'week', 'month', 'quarter', ], true) ? 1 : 0) + floor($start->diffInUnit($firstUnit, $this)) : round($start->diffInUnit($firstUnit, $start->avoidMutation()->add($secondUnit, 1))); return (int) $value; } catch (UnknownUnitException) { // default to macro } default: $macro = $this->getLocalMacro('get'.ucfirst($name)); if ($macro) { return $this->executeCallableWithContext($macro); } throw new UnknownGetterException($name); } } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset($name) { try { $this->__get($name); } catch (UnknownGetterException | ReflectionException) { return false; } return true; } /** * Set a part of the Carbon object * * @param string $name * @param string|int|DateTimeZone $value * * @throws UnknownSetterException|ReflectionException * * @return void */ public function __set($name, $value) { if ($this->constructedObjectId === spl_object_hash($this)) { $this->set($name, $value); return; } $this->$name = $value; } /** * Set a part of the Carbon object. * * @throws ImmutableException|UnknownSetterException * * @return $this */ public function set(Unit|array|string $name, DateTimeZone|Month|string|int|float|null $value = null): static { if ($this->isImmutable()) { throw new ImmutableException(\sprintf('%s class', static::class)); } if (\is_array($name)) { foreach ($name as $key => $value) { $this->set($key, $value); } return $this; } $name = Unit::toName($name); switch ($name) { case 'milliseconds': case 'millisecond': case 'milli': case 'microseconds': case 'microsecond': case 'micro': if (str_starts_with($name, 'milli')) { $value *= 1000; } while ($value < 0) { $this->subSecond(); $value += static::MICROSECONDS_PER_SECOND; } while ($value >= static::MICROSECONDS_PER_SECOND) { $this->addSecond(); $value -= static::MICROSECONDS_PER_SECOND; } $this->modify($this->rawFormat('H:i:s.').str_pad((string) round($value), 6, '0', STR_PAD_LEFT)); break; case 'year': case 'month': case 'day': case 'hour': case 'minute': case 'second': [$year, $month, $day, $hour, $minute, $second] = array_map('intval', explode('-', $this->rawFormat('Y-n-j-G-i-s'))); $$name = self::monthToInt($value, $name); $this->setDateTime($year, $month, $day, $hour, $minute, $second); break; case 'week': $this->week($value); break; case 'isoWeek': $this->isoWeek($value); break; case 'weekYear': $this->weekYear($value); break; case 'isoWeekYear': $this->isoWeekYear($value); break; case 'dayOfYear': $this->addDays($value - $this->dayOfYear); break; case 'dayOfWeek': $this->addDays($value - $this->dayOfWeek); break; case 'dayOfWeekIso': $this->addDays($value - $this->dayOfWeekIso); break; case 'timestamp': $this->setTimestamp($value); break; case 'offset': $this->setTimezone(static::safeCreateDateTimeZone($value / static::SECONDS_PER_MINUTE / static::MINUTES_PER_HOUR)); break; case 'offsetMinutes': $this->setTimezone(static::safeCreateDateTimeZone($value / static::MINUTES_PER_HOUR)); break; case 'offsetHours': $this->setTimezone(static::safeCreateDateTimeZone($value)); break; case 'timezone': case 'tz': $this->setTimezone($value); break; default: if (preg_match('/^([a-z]{2,})Of([A-Z][a-z]+)$/', $name, $match)) { [, $firstUnit, $secondUnit] = $match; try { $start = $this->avoidMutation()->startOf($secondUnit); $currentValue = (\in_array($firstUnit, [ // Unit with indexes starting at 1 (other units start at 0) 'day', 'week', 'month', 'quarter', ], true) ? 1 : 0) + (int) floor($start->diffInUnit($firstUnit, $this)); // We check $value a posteriori to give precedence to UnknownUnitException if (!\is_int($value)) { throw new UnitException("->$name expects integer value"); } $this->addUnit($firstUnit, $value - $currentValue); break; } catch (UnknownUnitException) { // default to macro } } $macro = $this->getLocalMacro('set'.ucfirst($name)); if ($macro) { $this->executeCallableWithContext($macro, $value); break; } if ($this->isLocalStrictModeEnabled()) { throw new UnknownSetterException($name); } $this->$name = $value; } return $this; } /** * Get the translation of the current week day name (with context for languages with multiple forms). * * @param string|null $context whole format string * @param string $keySuffix "", "_short" or "_min" * @param string|null $defaultValue default value if translation missing */ public function getTranslatedDayName( ?string $context = null, string $keySuffix = '', ?string $defaultValue = null, ): string { return $this->getTranslatedFormByRegExp('weekdays', $keySuffix, $context, $this->dayOfWeek, $defaultValue ?: $this->englishDayOfWeek); } /** * Get the translation of the current short week day name (with context for languages with multiple forms). * * @param string|null $context whole format string */ public function getTranslatedShortDayName(?string $context = null): string { return $this->getTranslatedDayName($context, '_short', $this->shortEnglishDayOfWeek); } /** * Get the translation of the current abbreviated week day name (with context for languages with multiple forms). * * @param string|null $context whole format string */ public function getTranslatedMinDayName(?string $context = null): string { return $this->getTranslatedDayName($context, '_min', $this->shortEnglishDayOfWeek); } /** * Get the translation of the current month day name (with context for languages with multiple forms). * * @param string|null $context whole format string * @param string $keySuffix "" or "_short" * @param string|null $defaultValue default value if translation missing */ public function getTranslatedMonthName( ?string $context = null, string $keySuffix = '', ?string $defaultValue = null, ): string { return $this->getTranslatedFormByRegExp('months', $keySuffix, $context, $this->month - 1, $defaultValue ?: $this->englishMonth); } /** * Get the translation of the current short month day name (with context for languages with multiple forms). * * @param string|null $context whole format string */ public function getTranslatedShortMonthName(?string $context = null): string { return $this->getTranslatedMonthName($context, '_short', $this->shortEnglishMonth); } /** * Get/set the day of year. * * @template T of int|null * * @param int|null $value new value for day of year if using as setter. * * @psalm-param T $value * * @return static|int * * @psalm-return (T is int ? static : int) */ public function dayOfYear(?int $value = null): static|int { $dayOfYear = $this->dayOfYear; return $value === null ? $dayOfYear : $this->addDays($value - $dayOfYear); } /** * Get/set the weekday from 0 (Sunday) to 6 (Saturday). * * @param WeekDay|int|null $value new value for weekday if using as setter. */ public function weekday(WeekDay|int|null $value = null): static|int { if ($value === null) { return $this->dayOfWeek; } $firstDay = (int) ($this->getTranslationMessage('first_day_of_week') ?? 0); $dayOfWeek = ($this->dayOfWeek + 7 - $firstDay) % 7; return $this->addDays(((WeekDay::int($value) + 7 - $firstDay) % 7) - $dayOfWeek); } /** * Get/set the ISO weekday from 1 (Monday) to 7 (Sunday). * * @param WeekDay|int|null $value new value for weekday if using as setter. */ public function isoWeekday(WeekDay|int|null $value = null): static|int { $dayOfWeekIso = $this->dayOfWeekIso; return $value === null ? $dayOfWeekIso : $this->addDays(WeekDay::int($value) - $dayOfWeekIso); } /** * Return the number of days since the start of the week (using the current locale or the first parameter * if explicitly given). * * @param WeekDay|int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week, * if not provided, start of week is inferred from the locale * (Sunday for en_US, Monday for de_DE, etc.) */ public function getDaysFromStartOfWeek(WeekDay|int|null $weekStartsAt = null): int { $firstDay = (int) (WeekDay::int($weekStartsAt) ?? $this->getTranslationMessage('first_day_of_week') ?? 0); return ($this->dayOfWeek + 7 - $firstDay) % 7; } /** * Set the day (keeping the current time) to the start of the week + the number of days passed as the first * parameter. First day of week is driven by the locale unless explicitly set with the second parameter. * * @param int $numberOfDays number of days to add after the start of the current week * @param WeekDay|int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week, * if not provided, start of week is inferred from the locale * (Sunday for en_US, Monday for de_DE, etc.) */ public function setDaysFromStartOfWeek(int $numberOfDays, WeekDay|int|null $weekStartsAt = null): static { return $this->addDays($numberOfDays - $this->getDaysFromStartOfWeek(WeekDay::int($weekStartsAt))); } /** * Set any unit to a new value without overflowing current other unit given. * * @param string $valueUnit unit name to modify * @param int $value new value for the input unit * @param string $overflowUnit unit name to not overflow */ public function setUnitNoOverflow(string $valueUnit, int $value, string $overflowUnit): static { try { $start = $this->avoidMutation()->startOf($overflowUnit); $end = $this->avoidMutation()->endOf($overflowUnit); /** @var static $date */ $date = $this->$valueUnit($value); if ($date < $start) { return $date->mutateIfMutable($start); } if ($date > $end) { return $date->mutateIfMutable($end); } return $date; } catch (BadMethodCallException | ReflectionException $exception) { throw new UnknownUnitException($valueUnit, 0, $exception); } } /** * Add any unit to a new value without overflowing current other unit given. * * @param string $valueUnit unit name to modify * @param int $value amount to add to the input unit * @param string $overflowUnit unit name to not overflow */ public function addUnitNoOverflow(string $valueUnit, int $value, string $overflowUnit): static { return $this->setUnitNoOverflow($valueUnit, $this->$valueUnit + $value, $overflowUnit); } /** * Subtract any unit to a new value without overflowing current other unit given. * * @param string $valueUnit unit name to modify * @param int $value amount to subtract to the input unit * @param string $overflowUnit unit name to not overflow */ public function subUnitNoOverflow(string $valueUnit, int $value, string $overflowUnit): static { return $this->setUnitNoOverflow($valueUnit, $this->$valueUnit - $value, $overflowUnit); } /** * Returns the minutes offset to UTC if no arguments passed, else set the timezone with given minutes shift passed. */ public function utcOffset(?int $minuteOffset = null): static|int { if ($minuteOffset === null) { return $this->offsetMinutes; } return $this->setTimezone(CarbonTimeZone::createFromMinuteOffset($minuteOffset)); } /** * Set the date with gregorian year, month and day numbers. * * @see https://php.net/manual/en/datetime.setdate.php */ public function setDate(int $year, int $month, int $day): static { return parent::setDate($year, $month, $day); } /** * Set a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates. * * @see https://php.net/manual/en/datetime.setisodate.php */ public function setISODate(int $year, int $week, int $day = 1): static { return parent::setISODate($year, $week, $day); } /** * Set the date and time all together. */ public function setDateTime( int $year, int $month, int $day, int $hour, int $minute, int $second = 0, int $microseconds = 0, ): static { return $this->setDate($year, $month, $day)->setTime($hour, $minute, $second, $microseconds); } /** * Resets the current time of the DateTime object to a different time. * * @see https://php.net/manual/en/datetime.settime.php */ public function setTime(int $hour, int $minute, int $second = 0, int $microseconds = 0): static { return parent::setTime($hour, $minute, $second, $microseconds); } /** * Set the instance's timestamp. * * Timestamp input can be given as int, float or a string containing one or more numbers. */ public function setTimestamp(float|int|string $timestamp): static { [$seconds, $microseconds] = self::getIntegerAndDecimalParts($timestamp); return parent::setTimestamp((int) $seconds)->setMicroseconds((int) $microseconds); } /** * Set the time by time string. */ public function setTimeFromTimeString(string $time): static { if (!str_contains($time, ':')) { $time .= ':0'; } return $this->modify($time); } /** * @alias setTimezone */ public function timezone(DateTimeZone|string|int $value): static { return $this->setTimezone($value); } /** * Set the timezone or returns the timezone name if no arguments passed. * * @return ($value is null ? string : static) */ public function tz(DateTimeZone|string|int|null $value = null): static|string { if ($value === null) { return $this->tzName; } return $this->setTimezone($value); } /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timeZone): static { return parent::setTimezone(static::safeCreateDateTimeZone($timeZone)); } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string $value): static { $dateTimeString = $this->format('Y-m-d H:i:s.u'); return $this ->setTimezone($value) ->modify($dateTimeString); } /** * Set the instance's timezone to UTC. */ public function utc(): static { return $this->setTimezone('UTC'); } /** * Set the year, month, and date for this instance to that of the passed instance. */ public function setDateFrom(DateTimeInterface|string $date): static { $date = $this->resolveCarbon($date); return $this->setDate($date->year, $date->month, $date->day); } /** * Set the hour, minute, second and microseconds for this instance to that of the passed instance. */ public function setTimeFrom(DateTimeInterface|string $date): static { $date = $this->resolveCarbon($date); return $this->setTime($date->hour, $date->minute, $date->second, $date->microsecond); } /** * Set the date and time for this instance to that of the passed instance. */ public function setDateTimeFrom(DateTimeInterface|string $date): static { $date = $this->resolveCarbon($date); return $this->modify($date->rawFormat('Y-m-d H:i:s.u')); } /** * Get the days of the week. */ public static function getDays(): array { return static::$days; } /////////////////////////////////////////////////////////////////// /////////////////////// WEEK SPECIAL DAYS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Get the first day of week. * * @return int */ public static function getWeekStartsAt(?string $locale = null): int { return (int) static::getTranslationMessageWith( $locale ? Translator::get($locale) : static::getTranslator(), 'first_day_of_week', ); } /** * Get the last day of week. * * @param string $locale local to consider the last day of week. * * @return int */ public static function getWeekEndsAt(?string $locale = null): int { return static::weekRotate(static::getWeekStartsAt($locale), -1); } /** * Get weekend days */ public static function getWeekendDays(): array { return FactoryImmutable::getInstance()->getWeekendDays(); } /** * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. * You should rather consider week-end is always saturday and sunday, and if you have some custom * week-end days to handle, give to those days an other name and create a macro for them: * * ``` * Carbon::macro('isDayOff', function ($date) { * return $date->isSunday() || $date->isMonday(); * }); * Carbon::macro('isNotDayOff', function ($date) { * return !$date->isDayOff(); * }); * if ($someDate->isDayOff()) ... * if ($someDate->isNotDayOff()) ... * // Add 5 not-off days * $count = 5; * while ($someDate->isDayOff() || ($count-- > 0)) { * $someDate->addDay(); * } * ``` * * Set weekend days */ public static function setWeekendDays(array $days): void { FactoryImmutable::getDefaultInstance()->setWeekendDays($days); } /** * Determine if a time string will produce a relative date. * * @return bool true if time match a relative date, false if absolute or invalid time string */ public static function hasRelativeKeywords(?string $time): bool { if (!$time || strtotime($time) === false) { return false; } $date1 = new DateTime('2000-01-01T00:00:00Z'); $date1->modify($time); $date2 = new DateTime('2001-12-25T00:00:00Z'); $date2->modify($time); return $date1 != $date2; } /////////////////////////////////////////////////////////////////// /////////////////////// STRING FORMATTING ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Returns list of locale formats for ISO formatting. * * @param string|null $locale current locale used if null */ public function getIsoFormats(?string $locale = null): array { return [ 'LT' => $this->getTranslationMessage('formats.LT', $locale), 'LTS' => $this->getTranslationMessage('formats.LTS', $locale), 'L' => $this->getTranslationMessage('formats.L', $locale), 'LL' => $this->getTranslationMessage('formats.LL', $locale), 'LLL' => $this->getTranslationMessage('formats.LLL', $locale), 'LLLL' => $this->getTranslationMessage('formats.LLLL', $locale), 'l' => $this->getTranslationMessage('formats.l', $locale), 'll' => $this->getTranslationMessage('formats.ll', $locale), 'lll' => $this->getTranslationMessage('formats.lll', $locale), 'llll' => $this->getTranslationMessage('formats.llll', $locale), ]; } /** * Returns list of calendar formats for ISO formatting. * * @param string|null $locale current locale used if null */ public function getCalendarFormats(?string $locale = null): array { return [ 'sameDay' => $this->getTranslationMessage('calendar.sameDay', $locale, '[Today at] LT'), 'nextDay' => $this->getTranslationMessage('calendar.nextDay', $locale, '[Tomorrow at] LT'), 'nextWeek' => $this->getTranslationMessage('calendar.nextWeek', $locale, 'dddd [at] LT'), 'lastDay' => $this->getTranslationMessage('calendar.lastDay', $locale, '[Yesterday at] LT'), 'lastWeek' => $this->getTranslationMessage('calendar.lastWeek', $locale, '[Last] dddd [at] LT'), 'sameElse' => $this->getTranslationMessage('calendar.sameElse', $locale, 'L'), ]; } /** * Returns list of locale units for ISO formatting. */ public static function getIsoUnits(): array { static $units = null; $units ??= [ 'OD' => ['getAltNumber', ['day']], 'OM' => ['getAltNumber', ['month']], 'OY' => ['getAltNumber', ['year']], 'OH' => ['getAltNumber', ['hour']], 'Oh' => ['getAltNumber', ['h']], 'Om' => ['getAltNumber', ['minute']], 'Os' => ['getAltNumber', ['second']], 'D' => 'day', 'DD' => ['rawFormat', ['d']], 'Do' => ['ordinal', ['day', 'D']], 'd' => 'dayOfWeek', 'dd' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedMinDayName( $originalFormat, ), 'ddd' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedShortDayName( $originalFormat, ), 'dddd' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedDayName( $originalFormat, ), 'DDD' => 'dayOfYear', 'DDDD' => ['getPaddedUnit', ['dayOfYear', 3]], 'DDDo' => ['ordinal', ['dayOfYear', 'DDD']], 'e' => ['weekday', []], 'E' => 'dayOfWeekIso', 'H' => ['rawFormat', ['G']], 'HH' => ['rawFormat', ['H']], 'h' => ['rawFormat', ['g']], 'hh' => ['rawFormat', ['h']], 'k' => 'noZeroHour', 'kk' => ['getPaddedUnit', ['noZeroHour']], 'hmm' => ['rawFormat', ['gi']], 'hmmss' => ['rawFormat', ['gis']], 'Hmm' => ['rawFormat', ['Gi']], 'Hmmss' => ['rawFormat', ['Gis']], 'm' => 'minute', 'mm' => ['rawFormat', ['i']], 'a' => 'meridiem', 'A' => 'upperMeridiem', 's' => 'second', 'ss' => ['getPaddedUnit', ['second']], 'S' => static fn (CarbonInterface $date) => (string) floor($date->micro / 100000), 'SS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 10000, 2), 'SSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 1000, 3), 'SSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 100, 4), 'SSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 10, 5), 'SSSSSS' => ['getPaddedUnit', ['micro', 6]], 'SSSSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro * 10, 7), 'SSSSSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro * 100, 8), 'SSSSSSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro * 1000, 9), 'M' => 'month', 'MM' => ['rawFormat', ['m']], 'MMM' => static function (CarbonInterface $date, $originalFormat = null) { $month = $date->getTranslatedShortMonthName($originalFormat); $suffix = $date->getTranslationMessage('mmm_suffix'); if ($suffix && $month !== $date->monthName) { $month .= $suffix; } return $month; }, 'MMMM' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedMonthName( $originalFormat, ), 'Mo' => ['ordinal', ['month', 'M']], 'Q' => 'quarter', 'Qo' => ['ordinal', ['quarter', 'M']], 'G' => 'isoWeekYear', 'GG' => ['getPaddedUnit', ['isoWeekYear']], 'GGG' => ['getPaddedUnit', ['isoWeekYear', 3]], 'GGGG' => ['getPaddedUnit', ['isoWeekYear', 4]], 'GGGGG' => ['getPaddedUnit', ['isoWeekYear', 5]], 'g' => 'weekYear', 'gg' => ['getPaddedUnit', ['weekYear']], 'ggg' => ['getPaddedUnit', ['weekYear', 3]], 'gggg' => ['getPaddedUnit', ['weekYear', 4]], 'ggggg' => ['getPaddedUnit', ['weekYear', 5]], 'W' => 'isoWeek', 'WW' => ['getPaddedUnit', ['isoWeek']], 'Wo' => ['ordinal', ['isoWeek', 'W']], 'w' => 'week', 'ww' => ['getPaddedUnit', ['week']], 'wo' => ['ordinal', ['week', 'w']], 'x' => ['valueOf', []], 'X' => 'timestamp', 'Y' => 'year', 'YY' => ['rawFormat', ['y']], 'YYYY' => ['getPaddedUnit', ['year', 4]], 'YYYYY' => ['getPaddedUnit', ['year', 5]], 'YYYYYY' => static fn (CarbonInterface $date) => ($date->year < 0 ? '' : '+'). $date->getPaddedUnit('year', 6), 'z' => ['rawFormat', ['T']], 'zz' => 'tzName', 'Z' => ['getOffsetString', []], 'ZZ' => ['getOffsetString', ['']], ]; return $units; } /** * Returns a unit of the instance padded with 0 by default or any other string if specified. * * @param string $unit Carbon unit name * @param int $length Length of the output (2 by default) * @param string $padString String to use for padding ("0" by default) * @param int $padType Side(s) to pad (STR_PAD_LEFT by default) */ public function getPaddedUnit($unit, $length = 2, $padString = '0', $padType = STR_PAD_LEFT): string { return ($this->$unit < 0 ? '-' : '').str_pad((string) abs($this->$unit), $length, $padString, $padType); } /** * Return a property with its ordinal. */ public function ordinal(string $key, ?string $period = null): string { $number = $this->$key; $result = $this->translate('ordinal', [ ':number' => $number, ':period' => (string) $period, ]); return (string) ($result === 'ordinal' ? $number : $result); } /** * Return the meridiem of the current time in the current locale. * * @param bool $isLower if true, returns lowercase variant if available in the current locale. */ public function meridiem(bool $isLower = false): string { $hour = $this->hour; $index = $hour < static::HOURS_PER_DAY / 2 ? 0 : 1; if ($isLower) { $key = 'meridiem.'.($index + 2); $result = $this->translate($key); if ($result !== $key) { return $result; } } $key = "meridiem.$index"; $result = $this->translate($key); if ($result === $key) { $result = $this->translate('meridiem', [ ':hour' => $this->hour, ':minute' => $this->minute, ':isLower' => $isLower, ]); if ($result === 'meridiem') { return $isLower ? $this->latinMeridiem : $this->latinUpperMeridiem; } } elseif ($isLower) { $result = mb_strtolower($result); } return $result; } /** * Returns the alternative number for a given date property if available in the current locale. * * @param string $key date property */ public function getAltNumber(string $key): string { return $this->translateNumber((int) (\strlen($key) > 1 ? $this->$key : $this->rawFormat($key))); } /** * Format in the current language using ISO replacement patterns. * * @param string|null $originalFormat provide context if a chunk has been passed alone */ public function isoFormat(string $format, ?string $originalFormat = null): string { $result = ''; $length = mb_strlen($format); $originalFormat ??= $format; $inEscaped = false; $formats = null; $units = null; for ($i = 0; $i < $length; $i++) { $char = mb_substr($format, $i, 1); if ($char === '\\') { $result .= mb_substr($format, ++$i, 1); continue; } if ($char === '[' && !$inEscaped) { $inEscaped = true; continue; } if ($char === ']' && $inEscaped) { $inEscaped = false; continue; } if ($inEscaped) { $result .= $char; continue; } $input = mb_substr($format, $i); if (preg_match('/^(LTS|LT|l{1,4}|L{1,4})/', $input, $match)) { if ($formats === null) { $formats = $this->getIsoFormats(); } $code = $match[0]; $sequence = $formats[$code] ?? preg_replace_callback( '/MMMM|MM|DD|dddd/', static fn ($code) => mb_substr($code[0], 1), $formats[strtoupper($code)] ?? '', ); $rest = mb_substr($format, $i + mb_strlen($code)); $format = mb_substr($format, 0, $i).$sequence.$rest; $length = mb_strlen($format); $input = $sequence.$rest; } if (preg_match('/^'.CarbonInterface::ISO_FORMAT_REGEXP.'/', $input, $match)) { $code = $match[0]; if ($units === null) { $units = static::getIsoUnits(); } $sequence = $units[$code] ?? ''; if ($sequence instanceof Closure) { $sequence = $sequence($this, $originalFormat); } elseif (\is_array($sequence)) { try { $sequence = $this->{$sequence[0]}(...$sequence[1]); } catch (ReflectionException | InvalidArgumentException | BadMethodCallException) { $sequence = ''; } } elseif (\is_string($sequence)) { $sequence = $this->$sequence ?? $code; } $format = mb_substr($format, 0, $i).$sequence.mb_substr($format, $i + mb_strlen($code)); $i += mb_strlen((string) $sequence) - 1; $length = mb_strlen($format); $char = $sequence; } $result .= $char; } return $result; } /** * List of replacements from date() format to isoFormat(). */ public static function getFormatsToIsoReplacements(): array { static $replacements = null; $replacements ??= [ 'd' => true, 'D' => 'ddd', 'j' => true, 'l' => 'dddd', 'N' => true, 'S' => static fn ($date) => str_replace((string) $date->rawFormat('j'), '', $date->isoFormat('Do')), 'w' => true, 'z' => true, 'W' => true, 'F' => 'MMMM', 'm' => true, 'M' => 'MMM', 'n' => true, 't' => true, 'L' => true, 'o' => true, 'Y' => true, 'y' => true, 'a' => 'a', 'A' => 'A', 'B' => true, 'g' => true, 'G' => true, 'h' => true, 'H' => true, 'i' => true, 's' => true, 'u' => true, 'v' => true, 'E' => true, 'I' => true, 'O' => true, 'P' => true, 'Z' => true, 'c' => true, 'r' => true, 'U' => true, 'T' => true, ]; return $replacements; } /** * Format as ->format() do (using date replacements patterns from https://php.net/manual/en/function.date.php) * but translate words whenever possible (months, day names, etc.) using the current locale. */ public function translatedFormat(string $format): string { $replacements = static::getFormatsToIsoReplacements(); $context = ''; $isoFormat = ''; $length = mb_strlen($format); for ($i = 0; $i < $length; $i++) { $char = mb_substr($format, $i, 1); if ($char === '\\') { $replacement = mb_substr($format, $i, 2); $isoFormat .= $replacement; $i++; continue; } if (!isset($replacements[$char])) { $replacement = preg_match('/^[A-Za-z]$/', $char) ? "\\$char" : $char; $isoFormat .= $replacement; $context .= $replacement; continue; } $replacement = $replacements[$char]; if ($replacement === true) { static $contextReplacements = null; if ($contextReplacements === null) { $contextReplacements = [ 'm' => 'MM', 'd' => 'DD', 't' => 'D', 'j' => 'D', 'N' => 'e', 'w' => 'e', 'n' => 'M', 'o' => 'YYYY', 'Y' => 'YYYY', 'y' => 'YY', 'g' => 'h', 'G' => 'H', 'h' => 'hh', 'H' => 'HH', 'i' => 'mm', 's' => 'ss', ]; } $isoFormat .= '['.$this->rawFormat($char).']'; $context .= $contextReplacements[$char] ?? ' '; continue; } if ($replacement instanceof Closure) { $replacement = '['.$replacement($this).']'; $isoFormat .= $replacement; $context .= $replacement; continue; } $isoFormat .= $replacement; $context .= $replacement; } return $this->isoFormat($isoFormat, $context); } /** * Returns the offset hour and minute formatted with +/- and a given separator (":" by default). * For example, if the time zone is 9 hours 30 minutes, you'll get "+09:30", with "@@" as first * argument, "+09@@30", with "" as first argument, "+0930". Negative offset will return something * like "-12:00". * * @param string $separator string to place between hours and minutes (":" by default) */ public function getOffsetString(string $separator = ':'): string { $second = $this->getOffset(); $symbol = $second < 0 ? '-' : '+'; $minute = abs($second) / static::SECONDS_PER_MINUTE; $hour = self::floorZeroPad($minute / static::MINUTES_PER_HOUR, 2); $minute = self::floorZeroPad(((int) $minute) % static::MINUTES_PER_HOUR, 2); return "$symbol$hour$separator$minute"; } /** * Dynamically handle calls to the class. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadMethodCallException */ public static function __callStatic(string $method, array $parameters): mixed { if (!static::hasMacro($method)) { foreach (static::getGenericMacros() as $callback) { try { return static::executeStaticCallable($callback, $method, ...$parameters); } catch (BadMethodCallException) { continue; } } if (static::isStrictModeEnabled()) { throw new UnknownMethodException(\sprintf('%s::%s', static::class, $method)); } return null; } return static::executeStaticCallable(static::getMacro($method), ...$parameters); } /** * Set specified unit to new given value. * * @param string $unit year, month, day, hour, minute, second or microsecond * @param Month|int $value new value for given unit */ public function setUnit(string $unit, Month|int|float|null $value = null): static { if (\is_float($value)) { $int = (int) $value; if ((float) $int !== $value) { throw new InvalidArgumentException( "$unit cannot be changed to float value $value, integer expected", ); } $value = $int; } $unit = static::singularUnit($unit); $value = self::monthToInt($value, $unit); $dateUnits = ['year', 'month', 'day']; if (\in_array($unit, $dateUnits)) { return $this->setDate(...array_map( fn ($name) => (int) ($name === $unit ? $value : $this->$name), $dateUnits, )); } $units = ['hour', 'minute', 'second', 'micro']; if ($unit === 'millisecond' || $unit === 'milli') { $value *= 1000; $unit = 'micro'; } elseif ($unit === 'microsecond') { $unit = 'micro'; } return $this->setTime(...array_map( fn ($name) => (int) ($name === $unit ? $value : $this->$name), $units, )); } /** * Returns standardized singular of a given singular/plural unit name (in English). */ public static function singularUnit(string $unit): string { $unit = rtrim(mb_strtolower($unit), 's'); return match ($unit) { 'centurie' => 'century', 'millennia' => 'millennium', default => $unit, }; } /** * Returns standardized plural of a given singular/plural unit name (in English). */ public static function pluralUnit(string $unit): string { $unit = rtrim(strtolower($unit), 's'); return match ($unit) { 'century' => 'centuries', 'millennium', 'millennia' => 'millennia', default => "{$unit}s", }; } public static function sleep(int|float $seconds): void { if (static::hasTestNow()) { static::setTestNow(static::getTestNow()->avoidMutation()->addSeconds($seconds)); return; } (new NativeClock('UTC'))->sleep($seconds); } /** * Dynamically handle calls to the class. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws UnknownMethodException|BadMethodCallException|ReflectionException|Throwable */ public function __call(string $method, array $parameters): mixed { $unit = rtrim($method, 's'); return $this->callDiffAlias($unit, $parameters) ?? $this->callHumanDiffAlias($unit, $parameters) ?? $this->callRoundMethod($unit, $parameters) ?? $this->callIsMethod($unit, $parameters) ?? $this->callModifierMethod($unit, $parameters) ?? $this->callPeriodMethod($method, $parameters) ?? $this->callGetOrSetMethod($method, $parameters) ?? $this->callMacroMethod($method, $parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. */ protected function resolveCarbon(DateTimeInterface|string|null $date): self { if (!$date) { return $this->nowWithSameTz(); } if (\is_string($date)) { return $this->transmitFactory(fn () => static::parse($date, $this->getTimezone())); } return $date instanceof self ? $date : $this->transmitFactory(static fn () => static::instance($date)); } protected static function weekRotate(int $day, int $rotation): int { return (static::DAYS_PER_WEEK + $rotation % static::DAYS_PER_WEEK + $day) % static::DAYS_PER_WEEK; } protected function executeCallable(callable $macro, ...$parameters) { if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return \call_user_func_array($boundMacro ?: $macro, $parameters); } return \call_user_func_array($macro, $parameters); } protected function executeCallableWithContext(callable $macro, ...$parameters) { return static::bindMacroContext($this, function () use (&$macro, &$parameters) { return $this->executeCallable($macro, ...$parameters); }); } protected function getAllGenericMacros(): Generator { yield from $this->localGenericMacros ?? []; yield from $this->transmitFactory(static fn () => static::getGenericMacros()); } protected static function getGenericMacros(): Generator { foreach ((FactoryImmutable::getInstance()->getSettings()['genericMacros'] ?? []) as $list) { foreach ($list as $macro) { yield $macro; } } } protected static function executeStaticCallable(callable $macro, ...$parameters) { return static::bindMacroContext(null, function () use (&$macro, &$parameters) { if ($macro instanceof Closure) { $boundMacro = @Closure::bind($macro, null, static::class); return \call_user_func_array($boundMacro ?: $macro, $parameters); } return \call_user_func_array($macro, $parameters); }); } protected function getTranslatedFormByRegExp($baseKey, $keySuffix, $context, $subKey, $defaultValue) { $key = $baseKey.$keySuffix; $standaloneKey = $key.'_standalone'; $baseTranslation = $this->getTranslationMessage($key); if ($baseTranslation instanceof Closure) { return $baseTranslation($this, $context, $subKey) ?: $defaultValue; } if ( $this->getTranslationMessage("$standaloneKey.$subKey") && (!$context || (($regExp = $this->getTranslationMessage($baseKey.'_regexp')) && !preg_match($regExp, $context))) ) { $key = $standaloneKey; } return $this->getTranslationMessage("$key.$subKey", null, $defaultValue); } private function callGetOrSetMethod(string $method, array $parameters): mixed { if (preg_match('/^([a-z]{2,})(In|Of)([A-Z][a-z]+)$/', $method)) { $localStrictModeEnabled = $this->localStrictModeEnabled; $this->localStrictModeEnabled = true; try { return $this->callGetOrSet($method, $parameters[0] ?? null); } catch (UnknownGetterException|UnknownSetterException|ImmutableException) { // continue to macro } finally { $this->localStrictModeEnabled = $localStrictModeEnabled; } } return null; } private function callGetOrSet(string $name, mixed $value): mixed { if ($value !== null) { if (\is_string($value) || \is_int($value) || \is_float($value) || $value instanceof DateTimeZone || $value instanceof Month) { return $this->set($name, $value); } return null; } return $this->get($name); } private function getUTCUnit(string $unit): ?string { if (str_starts_with($unit, 'Real')) { return substr($unit, 4); } if (str_starts_with($unit, 'UTC')) { return substr($unit, 3); } return null; } private function callDiffAlias(string $method, array $parameters): mixed { if (preg_match('/^(diff|floatDiff)In(Real|UTC|Utc)?(.+)$/', $method, $match)) { $mode = strtoupper($match[2] ?? ''); $betterMethod = $match[1] === 'floatDiff' ? str_replace('floatDiff', 'diff', $method) : null; if ($mode === 'REAL') { $mode = 'UTC'; $betterMethod = str_replace($match[2], 'UTC', $betterMethod ?? $method); } if ($betterMethod) { @trigger_error( "Use the method $betterMethod instead to make it more explicit about what it does.\n". 'On next major version, "float" prefix will be removed (as all diff are now returning floating numbers)'. ' and "Real" methods will be removed in favor of "UTC" because what it actually does is to convert both'. ' dates to UTC timezone before comparison, while by default it does it only if both dates don\'t have'. ' exactly the same timezone (Note: 2 timezones with the same offset but different names are considered'. " different as it's not safe to assume they will always have the same offset).", \E_USER_DEPRECATED, ); } $unit = self::pluralUnit($match[3]); $diffMethod = 'diffIn'.ucfirst($unit); if (\in_array($unit, ['days', 'weeks', 'months', 'quarters', 'years'])) { $parameters['utc'] = ($mode === 'UTC'); } if (method_exists($this, $diffMethod)) { return $this->$diffMethod(...$parameters); } } return null; } private function callHumanDiffAlias(string $method, array $parameters): ?string { $diffSizes = [ // @mode diffForHumans 'short' => true, // @mode diffForHumans 'long' => false, ]; $diffSyntaxModes = [ // @call diffForHumans 'Absolute' => CarbonInterface::DIFF_ABSOLUTE, // @call diffForHumans 'Relative' => CarbonInterface::DIFF_RELATIVE_AUTO, // @call diffForHumans 'RelativeToNow' => CarbonInterface::DIFF_RELATIVE_TO_NOW, // @call diffForHumans 'RelativeToOther' => CarbonInterface::DIFF_RELATIVE_TO_OTHER, ]; $sizePattern = implode('|', array_keys($diffSizes)); $syntaxPattern = implode('|', array_keys($diffSyntaxModes)); if (preg_match("/^(?<size>$sizePattern)(?<syntax>$syntaxPattern)DiffForHuman$/", $method, $match)) { $dates = array_filter($parameters, function ($parameter) { return $parameter instanceof DateTimeInterface; }); $other = null; if (\count($dates)) { $key = key($dates); $other = current($dates); array_splice($parameters, $key, 1); } return $this->diffForHumans($other, $diffSyntaxModes[$match['syntax']], $diffSizes[$match['size']], ...$parameters); } return null; } private function callIsMethod(string $unit, array $parameters): ?bool { if (!str_starts_with($unit, 'is')) { return null; } $word = substr($unit, 2); if (\in_array($word, static::$days, true)) { return $this->isDayOfWeek($word); } return match ($word) { // @call is Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) 'Utc', 'UTC' => $this->utc, // @call is Check if the current instance has non-UTC timezone. 'Local' => $this->local, // @call is Check if the current instance is a valid date. 'Valid' => $this->year !== 0, // @call is Check if the current instance is in a daylight saving time. 'DST' => $this->dst, default => $this->callComparatorMethod($word, $parameters), }; } private function callComparatorMethod(string $unit, array $parameters): ?bool { $start = substr($unit, 0, 4); $factor = -1; if ($start === 'Last') { $start = 'Next'; $factor = 1; } if ($start === 'Next') { $lowerUnit = strtolower(substr($unit, 4)); if (static::isModifiableUnit($lowerUnit)) { return $this->avoidMutation()->addUnit($lowerUnit, $factor, false)->isSameUnit($lowerUnit, ...($parameters ?: ['now'])); } } if ($start === 'Same') { try { return $this->isSameUnit(strtolower(substr($unit, 4)), ...$parameters); } catch (BadComparisonUnitException) { // Try next } } if (str_starts_with($unit, 'Current')) { try { return $this->isCurrentUnit(strtolower(substr($unit, 7))); } catch (BadComparisonUnitException | BadMethodCallException) { // Try next } } return null; } private function callModifierMethod(string $unit, array $parameters): ?static { $action = substr($unit, 0, 3); $overflow = null; if ($action === 'set') { $unit = strtolower(substr($unit, 3)); } if (\in_array($unit, static::$units, true)) { return $this->setUnit($unit, ...$parameters); } if ($action === 'add' || $action === 'sub') { $unit = substr($unit, 3); $utcUnit = $this->getUTCUnit($unit); if ($utcUnit) { $unit = static::singularUnit($utcUnit); return $this->{"{$action}UTCUnit"}($unit, ...$parameters); } if (preg_match('/^(Month|Quarter|Year|Decade|Century|Centurie|Millennium|Millennia)s?(No|With|Without|WithNo)Overflow$/', $unit, $match)) { $unit = $match[1]; $overflow = $match[2] === 'With'; } $unit = static::singularUnit($unit); } if (static::isModifiableUnit($unit)) { return $this->{"{$action}Unit"}($unit, $this->getMagicParameter($parameters, 0, 'value', 1), $overflow); } return null; } private function callPeriodMethod(string $method, array $parameters): ?CarbonPeriod { if (str_ends_with($method, 'Until')) { try { $unit = static::singularUnit(substr($method, 0, -5)); return $this->range( $this->getMagicParameter($parameters, 0, 'endDate', $this), $this->getMagicParameter($parameters, 1, 'factor', 1), $unit ); } catch (InvalidArgumentException) { // Try macros } } return null; } private function callMacroMethod(string $method, array $parameters): mixed { return static::bindMacroContext($this, function () use (&$method, &$parameters) { $macro = $this->getLocalMacro($method); if (!$macro) { foreach ($this->getAllGenericMacros() as $callback) { try { return $this->executeCallable($callback, $method, ...$parameters); } catch (BadMethodCallException) { continue; } } if ($this->isLocalStrictModeEnabled()) { throw new UnknownMethodException($method); } return null; } return $this->executeCallable($macro, ...$parameters); }); } private static function floorZeroPad(int|float $value, int $length): string { return str_pad((string) floor($value), $length, '0', STR_PAD_LEFT); } /** * @template T of CarbonInterface * * @param T $date * * @return T */ private function mutateIfMutable(CarbonInterface $date): CarbonInterface { return $this instanceof DateTimeImmutable ? $date : $this->modify('@'.$date->rawFormat('U.u'))->setTimezone($date->getTimezone()); } }
PHP
{ "end_line": 2317, "name": "isoFormat", "signature": "public function isoFormat(string $format, ?string $originalFormat = null): string", "start_line": 2231 }
{ "class_name": "Date", "class_signature": "trait Date", "namespace": "Carbon\\Traits" }
translatedFormat
Carbon/src/Carbon/Traits/Date.php
public function translatedFormat(string $format): string { $replacements = static::getFormatsToIsoReplacements(); $context = ''; $isoFormat = ''; $length = mb_strlen($format); for ($i = 0; $i < $length; $i++) { $char = mb_substr($format, $i, 1); if ($char === '\\') { $replacement = mb_substr($format, $i, 2); $isoFormat .= $replacement; $i++; continue; } if (!isset($replacements[$char])) { $replacement = preg_match('/^[A-Za-z]$/', $char) ? "\\$char" : $char; $isoFormat .= $replacement; $context .= $replacement; continue; } $replacement = $replacements[$char]; if ($replacement === true) { static $contextReplacements = null; if ($contextReplacements === null) { $contextReplacements = [ 'm' => 'MM', 'd' => 'DD', 't' => 'D', 'j' => 'D', 'N' => 'e', 'w' => 'e', 'n' => 'M', 'o' => 'YYYY', 'Y' => 'YYYY', 'y' => 'YY', 'g' => 'h', 'G' => 'H', 'h' => 'hh', 'H' => 'HH', 'i' => 'mm', 's' => 'ss', ]; } $isoFormat .= '['.$this->rawFormat($char).']'; $context .= $contextReplacements[$char] ?? ' '; continue; } if ($replacement instanceof Closure) { $replacement = '['.$replacement($this).']'; $isoFormat .= $replacement; $context .= $replacement; continue; } $isoFormat .= $replacement; $context .= $replacement; } return $this->isoFormat($isoFormat, $context); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use BadMethodCallException; use Carbon\Carbon; use Carbon\CarbonInterface; use Carbon\CarbonPeriod; use Carbon\CarbonTimeZone; use Carbon\Exceptions\BadComparisonUnitException; use Carbon\Exceptions\ImmutableException; use Carbon\Exceptions\InvalidTimeZoneException; use Carbon\Exceptions\UnitException; use Carbon\Exceptions\UnknownGetterException; use Carbon\Exceptions\UnknownMethodException; use Carbon\Exceptions\UnknownSetterException; use Carbon\Exceptions\UnknownUnitException; use Carbon\FactoryImmutable; use Carbon\Month; use Carbon\Translator; use Carbon\Unit; use Carbon\WeekDay; use Closure; use DateInterval; use DatePeriod; use DateTime; use DateTimeImmutable; use DateTimeInterface; use DateTimeZone; use Generator; use InvalidArgumentException; use ReflectionException; use Symfony\Component\Clock\NativeClock; use Throwable; /** * A simple API extension for DateTime. * * <autodoc generated by `composer phpdoc`> * * @property string $localeDayOfWeek the day of week in current locale * @property string $shortLocaleDayOfWeek the abbreviated day of week in current locale * @property string $localeMonth the month in current locale * @property string $shortLocaleMonth the abbreviated month in current locale * @property int $year * @property int $yearIso * @property int $month * @property int $day * @property int $hour * @property int $minute * @property int $second * @property int $micro * @property int $microsecond * @property int $dayOfWeekIso 1 (for Monday) through 7 (for Sunday) * @property int|float|string $timestamp seconds since the Unix Epoch * @property string $englishDayOfWeek the day of week in English * @property string $shortEnglishDayOfWeek the abbreviated day of week in English * @property string $englishMonth the month in English * @property string $shortEnglishMonth the abbreviated month in English * @property int $milliseconds * @property int $millisecond * @property int $milli * @property int $week 1 through 53 * @property int $isoWeek 1 through 53 * @property int $weekYear year according to week format * @property int $isoWeekYear year according to ISO week format * @property int $age does a diffInYears() with default parameters * @property int $offset the timezone offset in seconds from UTC * @property int $offsetMinutes the timezone offset in minutes from UTC * @property int $offsetHours the timezone offset in hours from UTC * @property CarbonTimeZone $timezone the current timezone * @property CarbonTimeZone $tz alias of $timezone * @property int $centuryOfMillennium The value of the century starting from the beginning of the current millennium * @property int $dayOfCentury The value of the day starting from the beginning of the current century * @property int $dayOfDecade The value of the day starting from the beginning of the current decade * @property int $dayOfMillennium The value of the day starting from the beginning of the current millennium * @property int $dayOfMonth The value of the day starting from the beginning of the current month * @property int $dayOfQuarter The value of the day starting from the beginning of the current quarter * @property int $dayOfWeek 0 (for Sunday) through 6 (for Saturday) * @property int $dayOfYear 1 through 366 * @property int $decadeOfCentury The value of the decade starting from the beginning of the current century * @property int $decadeOfMillennium The value of the decade starting from the beginning of the current millennium * @property int $hourOfCentury The value of the hour starting from the beginning of the current century * @property int $hourOfDay The value of the hour starting from the beginning of the current day * @property int $hourOfDecade The value of the hour starting from the beginning of the current decade * @property int $hourOfMillennium The value of the hour starting from the beginning of the current millennium * @property int $hourOfMonth The value of the hour starting from the beginning of the current month * @property int $hourOfQuarter The value of the hour starting from the beginning of the current quarter * @property int $hourOfWeek The value of the hour starting from the beginning of the current week * @property int $hourOfYear The value of the hour starting from the beginning of the current year * @property int $microsecondOfCentury The value of the microsecond starting from the beginning of the current century * @property int $microsecondOfDay The value of the microsecond starting from the beginning of the current day * @property int $microsecondOfDecade The value of the microsecond starting from the beginning of the current decade * @property int $microsecondOfHour The value of the microsecond starting from the beginning of the current hour * @property int $microsecondOfMillennium The value of the microsecond starting from the beginning of the current millennium * @property int $microsecondOfMillisecond The value of the microsecond starting from the beginning of the current millisecond * @property int $microsecondOfMinute The value of the microsecond starting from the beginning of the current minute * @property int $microsecondOfMonth The value of the microsecond starting from the beginning of the current month * @property int $microsecondOfQuarter The value of the microsecond starting from the beginning of the current quarter * @property int $microsecondOfSecond The value of the microsecond starting from the beginning of the current second * @property int $microsecondOfWeek The value of the microsecond starting from the beginning of the current week * @property int $microsecondOfYear The value of the microsecond starting from the beginning of the current year * @property int $millisecondOfCentury The value of the millisecond starting from the beginning of the current century * @property int $millisecondOfDay The value of the millisecond starting from the beginning of the current day * @property int $millisecondOfDecade The value of the millisecond starting from the beginning of the current decade * @property int $millisecondOfHour The value of the millisecond starting from the beginning of the current hour * @property int $millisecondOfMillennium The value of the millisecond starting from the beginning of the current millennium * @property int $millisecondOfMinute The value of the millisecond starting from the beginning of the current minute * @property int $millisecondOfMonth The value of the millisecond starting from the beginning of the current month * @property int $millisecondOfQuarter The value of the millisecond starting from the beginning of the current quarter * @property int $millisecondOfSecond The value of the millisecond starting from the beginning of the current second * @property int $millisecondOfWeek The value of the millisecond starting from the beginning of the current week * @property int $millisecondOfYear The value of the millisecond starting from the beginning of the current year * @property int $minuteOfCentury The value of the minute starting from the beginning of the current century * @property int $minuteOfDay The value of the minute starting from the beginning of the current day * @property int $minuteOfDecade The value of the minute starting from the beginning of the current decade * @property int $minuteOfHour The value of the minute starting from the beginning of the current hour * @property int $minuteOfMillennium The value of the minute starting from the beginning of the current millennium * @property int $minuteOfMonth The value of the minute starting from the beginning of the current month * @property int $minuteOfQuarter The value of the minute starting from the beginning of the current quarter * @property int $minuteOfWeek The value of the minute starting from the beginning of the current week * @property int $minuteOfYear The value of the minute starting from the beginning of the current year * @property int $monthOfCentury The value of the month starting from the beginning of the current century * @property int $monthOfDecade The value of the month starting from the beginning of the current decade * @property int $monthOfMillennium The value of the month starting from the beginning of the current millennium * @property int $monthOfQuarter The value of the month starting from the beginning of the current quarter * @property int $monthOfYear The value of the month starting from the beginning of the current year * @property int $quarterOfCentury The value of the quarter starting from the beginning of the current century * @property int $quarterOfDecade The value of the quarter starting from the beginning of the current decade * @property int $quarterOfMillennium The value of the quarter starting from the beginning of the current millennium * @property int $quarterOfYear The value of the quarter starting from the beginning of the current year * @property int $secondOfCentury The value of the second starting from the beginning of the current century * @property int $secondOfDay The value of the second starting from the beginning of the current day * @property int $secondOfDecade The value of the second starting from the beginning of the current decade * @property int $secondOfHour The value of the second starting from the beginning of the current hour * @property int $secondOfMillennium The value of the second starting from the beginning of the current millennium * @property int $secondOfMinute The value of the second starting from the beginning of the current minute * @property int $secondOfMonth The value of the second starting from the beginning of the current month * @property int $secondOfQuarter The value of the second starting from the beginning of the current quarter * @property int $secondOfWeek The value of the second starting from the beginning of the current week * @property int $secondOfYear The value of the second starting from the beginning of the current year * @property int $weekOfCentury The value of the week starting from the beginning of the current century * @property int $weekOfDecade The value of the week starting from the beginning of the current decade * @property int $weekOfMillennium The value of the week starting from the beginning of the current millennium * @property int $weekOfMonth 1 through 5 * @property int $weekOfQuarter The value of the week starting from the beginning of the current quarter * @property int $weekOfYear ISO-8601 week number of year, weeks starting on Monday * @property int $yearOfCentury The value of the year starting from the beginning of the current century * @property int $yearOfDecade The value of the year starting from the beginning of the current decade * @property int $yearOfMillennium The value of the year starting from the beginning of the current millennium * @property-read string $latinMeridiem "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) * @property-read string $latinUpperMeridiem "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) * @property-read string $timezoneAbbreviatedName the current timezone abbreviated name * @property-read string $tzAbbrName alias of $timezoneAbbreviatedName * @property-read string $dayName long name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $shortDayName short name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $minDayName very short name of weekday translated according to Carbon locale, in english if no translation available for current language * @property-read string $monthName long name of month translated according to Carbon locale, in english if no translation available for current language * @property-read string $shortMonthName short name of month translated according to Carbon locale, in english if no translation available for current language * @property-read string $meridiem lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language * @property-read string $upperMeridiem uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language * @property-read int $noZeroHour current hour from 1 to 24 * @property-read int $isoWeeksInYear 51 through 53 * @property-read int $weekNumberInMonth 1 through 5 * @property-read int $firstWeekDay 0 through 6 * @property-read int $lastWeekDay 0 through 6 * @property-read int $quarter the quarter of this instance, 1 - 4 * @property-read int $decade the decade of this instance * @property-read int $century the century of this instance * @property-read int $millennium the millennium of this instance * @property-read bool $dst daylight savings time indicator, true if DST, false otherwise * @property-read bool $local checks if the timezone is local, true if local, false otherwise * @property-read bool $utc checks if the timezone is UTC, true if UTC, false otherwise * @property-read string $timezoneName the current timezone name * @property-read string $tzName alias of $timezoneName * @property-read string $locale locale of the current instance * @property-read int $centuriesInMillennium The number of centuries contained in the current millennium * @property-read int $daysInCentury The number of days contained in the current century * @property-read int $daysInDecade The number of days contained in the current decade * @property-read int $daysInMillennium The number of days contained in the current millennium * @property-read int $daysInMonth number of days in the given month * @property-read int $daysInQuarter The number of days contained in the current quarter * @property-read int $daysInWeek The number of days contained in the current week * @property-read int $daysInYear 365 or 366 * @property-read int $decadesInCentury The number of decades contained in the current century * @property-read int $decadesInMillennium The number of decades contained in the current millennium * @property-read int $hoursInCentury The number of hours contained in the current century * @property-read int $hoursInDay The number of hours contained in the current day * @property-read int $hoursInDecade The number of hours contained in the current decade * @property-read int $hoursInMillennium The number of hours contained in the current millennium * @property-read int $hoursInMonth The number of hours contained in the current month * @property-read int $hoursInQuarter The number of hours contained in the current quarter * @property-read int $hoursInWeek The number of hours contained in the current week * @property-read int $hoursInYear The number of hours contained in the current year * @property-read int $microsecondsInCentury The number of microseconds contained in the current century * @property-read int $microsecondsInDay The number of microseconds contained in the current day * @property-read int $microsecondsInDecade The number of microseconds contained in the current decade * @property-read int $microsecondsInHour The number of microseconds contained in the current hour * @property-read int $microsecondsInMillennium The number of microseconds contained in the current millennium * @property-read int $microsecondsInMillisecond The number of microseconds contained in the current millisecond * @property-read int $microsecondsInMinute The number of microseconds contained in the current minute * @property-read int $microsecondsInMonth The number of microseconds contained in the current month * @property-read int $microsecondsInQuarter The number of microseconds contained in the current quarter * @property-read int $microsecondsInSecond The number of microseconds contained in the current second * @property-read int $microsecondsInWeek The number of microseconds contained in the current week * @property-read int $microsecondsInYear The number of microseconds contained in the current year * @property-read int $millisecondsInCentury The number of milliseconds contained in the current century * @property-read int $millisecondsInDay The number of milliseconds contained in the current day * @property-read int $millisecondsInDecade The number of milliseconds contained in the current decade * @property-read int $millisecondsInHour The number of milliseconds contained in the current hour * @property-read int $millisecondsInMillennium The number of milliseconds contained in the current millennium * @property-read int $millisecondsInMinute The number of milliseconds contained in the current minute * @property-read int $millisecondsInMonth The number of milliseconds contained in the current month * @property-read int $millisecondsInQuarter The number of milliseconds contained in the current quarter * @property-read int $millisecondsInSecond The number of milliseconds contained in the current second * @property-read int $millisecondsInWeek The number of milliseconds contained in the current week * @property-read int $millisecondsInYear The number of milliseconds contained in the current year * @property-read int $minutesInCentury The number of minutes contained in the current century * @property-read int $minutesInDay The number of minutes contained in the current day * @property-read int $minutesInDecade The number of minutes contained in the current decade * @property-read int $minutesInHour The number of minutes contained in the current hour * @property-read int $minutesInMillennium The number of minutes contained in the current millennium * @property-read int $minutesInMonth The number of minutes contained in the current month * @property-read int $minutesInQuarter The number of minutes contained in the current quarter * @property-read int $minutesInWeek The number of minutes contained in the current week * @property-read int $minutesInYear The number of minutes contained in the current year * @property-read int $monthsInCentury The number of months contained in the current century * @property-read int $monthsInDecade The number of months contained in the current decade * @property-read int $monthsInMillennium The number of months contained in the current millennium * @property-read int $monthsInQuarter The number of months contained in the current quarter * @property-read int $monthsInYear The number of months contained in the current year * @property-read int $quartersInCentury The number of quarters contained in the current century * @property-read int $quartersInDecade The number of quarters contained in the current decade * @property-read int $quartersInMillennium The number of quarters contained in the current millennium * @property-read int $quartersInYear The number of quarters contained in the current year * @property-read int $secondsInCentury The number of seconds contained in the current century * @property-read int $secondsInDay The number of seconds contained in the current day * @property-read int $secondsInDecade The number of seconds contained in the current decade * @property-read int $secondsInHour The number of seconds contained in the current hour * @property-read int $secondsInMillennium The number of seconds contained in the current millennium * @property-read int $secondsInMinute The number of seconds contained in the current minute * @property-read int $secondsInMonth The number of seconds contained in the current month * @property-read int $secondsInQuarter The number of seconds contained in the current quarter * @property-read int $secondsInWeek The number of seconds contained in the current week * @property-read int $secondsInYear The number of seconds contained in the current year * @property-read int $weeksInCentury The number of weeks contained in the current century * @property-read int $weeksInDecade The number of weeks contained in the current decade * @property-read int $weeksInMillennium The number of weeks contained in the current millennium * @property-read int $weeksInMonth The number of weeks contained in the current month * @property-read int $weeksInQuarter The number of weeks contained in the current quarter * @property-read int $weeksInYear 51 through 53 * @property-read int $yearsInCentury The number of years contained in the current century * @property-read int $yearsInDecade The number of years contained in the current decade * @property-read int $yearsInMillennium The number of years contained in the current millennium * * @method bool isUtc() Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) * @method bool isLocal() Check if the current instance has non-UTC timezone. * @method bool isValid() Check if the current instance is a valid date. * @method bool isDST() Check if the current instance is in a daylight saving time. * @method bool isSunday() Checks if the instance day is sunday. * @method bool isMonday() Checks if the instance day is monday. * @method bool isTuesday() Checks if the instance day is tuesday. * @method bool isWednesday() Checks if the instance day is wednesday. * @method bool isThursday() Checks if the instance day is thursday. * @method bool isFriday() Checks if the instance day is friday. * @method bool isSaturday() Checks if the instance day is saturday. * @method bool isSameYear(DateTimeInterface|string $date) Checks if the given date is in the same year as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentYear() Checks if the instance is in the same year as the current moment. * @method bool isNextYear() Checks if the instance is in the same year as the current moment next year. * @method bool isLastYear() Checks if the instance is in the same year as the current moment last year. * @method bool isCurrentMonth() Checks if the instance is in the same month as the current moment. * @method bool isNextMonth() Checks if the instance is in the same month as the current moment next month. * @method bool isLastMonth() Checks if the instance is in the same month as the current moment last month. * @method bool isSameWeek(DateTimeInterface|string $date) Checks if the given date is in the same week as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentWeek() Checks if the instance is in the same week as the current moment. * @method bool isNextWeek() Checks if the instance is in the same week as the current moment next week. * @method bool isLastWeek() Checks if the instance is in the same week as the current moment last week. * @method bool isSameDay(DateTimeInterface|string $date) Checks if the given date is in the same day as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentDay() Checks if the instance is in the same day as the current moment. * @method bool isNextDay() Checks if the instance is in the same day as the current moment next day. * @method bool isLastDay() Checks if the instance is in the same day as the current moment last day. * @method bool isSameHour(DateTimeInterface|string $date) Checks if the given date is in the same hour as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentHour() Checks if the instance is in the same hour as the current moment. * @method bool isNextHour() Checks if the instance is in the same hour as the current moment next hour. * @method bool isLastHour() Checks if the instance is in the same hour as the current moment last hour. * @method bool isSameMinute(DateTimeInterface|string $date) Checks if the given date is in the same minute as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMinute() Checks if the instance is in the same minute as the current moment. * @method bool isNextMinute() Checks if the instance is in the same minute as the current moment next minute. * @method bool isLastMinute() Checks if the instance is in the same minute as the current moment last minute. * @method bool isSameSecond(DateTimeInterface|string $date) Checks if the given date is in the same second as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentSecond() Checks if the instance is in the same second as the current moment. * @method bool isNextSecond() Checks if the instance is in the same second as the current moment next second. * @method bool isLastSecond() Checks if the instance is in the same second as the current moment last second. * @method bool isSameMilli(DateTimeInterface|string $date) Checks if the given date is in the same millisecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMilli() Checks if the instance is in the same millisecond as the current moment. * @method bool isNextMilli() Checks if the instance is in the same millisecond as the current moment next millisecond. * @method bool isLastMilli() Checks if the instance is in the same millisecond as the current moment last millisecond. * @method bool isSameMillisecond(DateTimeInterface|string $date) Checks if the given date is in the same millisecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMillisecond() Checks if the instance is in the same millisecond as the current moment. * @method bool isNextMillisecond() Checks if the instance is in the same millisecond as the current moment next millisecond. * @method bool isLastMillisecond() Checks if the instance is in the same millisecond as the current moment last millisecond. * @method bool isSameMicro(DateTimeInterface|string $date) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMicro() Checks if the instance is in the same microsecond as the current moment. * @method bool isNextMicro() Checks if the instance is in the same microsecond as the current moment next microsecond. * @method bool isLastMicro() Checks if the instance is in the same microsecond as the current moment last microsecond. * @method bool isSameMicrosecond(DateTimeInterface|string $date) Checks if the given date is in the same microsecond as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMicrosecond() Checks if the instance is in the same microsecond as the current moment. * @method bool isNextMicrosecond() Checks if the instance is in the same microsecond as the current moment next microsecond. * @method bool isLastMicrosecond() Checks if the instance is in the same microsecond as the current moment last microsecond. * @method bool isSameDecade(DateTimeInterface|string $date) Checks if the given date is in the same decade as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentDecade() Checks if the instance is in the same decade as the current moment. * @method bool isNextDecade() Checks if the instance is in the same decade as the current moment next decade. * @method bool isLastDecade() Checks if the instance is in the same decade as the current moment last decade. * @method bool isSameCentury(DateTimeInterface|string $date) Checks if the given date is in the same century as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentCentury() Checks if the instance is in the same century as the current moment. * @method bool isNextCentury() Checks if the instance is in the same century as the current moment next century. * @method bool isLastCentury() Checks if the instance is in the same century as the current moment last century. * @method bool isSameMillennium(DateTimeInterface|string $date) Checks if the given date is in the same millennium as the instance. If null passed, compare to now (with the same timezone). * @method bool isCurrentMillennium() Checks if the instance is in the same millennium as the current moment. * @method bool isNextMillennium() Checks if the instance is in the same millennium as the current moment next millennium. * @method bool isLastMillennium() Checks if the instance is in the same millennium as the current moment last millennium. * @method bool isCurrentQuarter() Checks if the instance is in the same quarter as the current moment. * @method bool isNextQuarter() Checks if the instance is in the same quarter as the current moment next quarter. * @method bool isLastQuarter() Checks if the instance is in the same quarter as the current moment last quarter. * @method CarbonInterface years(int $value) Set current instance year to the given value. * @method CarbonInterface year(int $value) Set current instance year to the given value. * @method CarbonInterface setYears(int $value) Set current instance year to the given value. * @method CarbonInterface setYear(int $value) Set current instance year to the given value. * @method CarbonInterface months(Month|int $value) Set current instance month to the given value. * @method CarbonInterface month(Month|int $value) Set current instance month to the given value. * @method CarbonInterface setMonths(Month|int $value) Set current instance month to the given value. * @method CarbonInterface setMonth(Month|int $value) Set current instance month to the given value. * @method CarbonInterface days(int $value) Set current instance day to the given value. * @method CarbonInterface day(int $value) Set current instance day to the given value. * @method CarbonInterface setDays(int $value) Set current instance day to the given value. * @method CarbonInterface setDay(int $value) Set current instance day to the given value. * @method CarbonInterface hours(int $value) Set current instance hour to the given value. * @method CarbonInterface hour(int $value) Set current instance hour to the given value. * @method CarbonInterface setHours(int $value) Set current instance hour to the given value. * @method CarbonInterface setHour(int $value) Set current instance hour to the given value. * @method CarbonInterface minutes(int $value) Set current instance minute to the given value. * @method CarbonInterface minute(int $value) Set current instance minute to the given value. * @method CarbonInterface setMinutes(int $value) Set current instance minute to the given value. * @method CarbonInterface setMinute(int $value) Set current instance minute to the given value. * @method CarbonInterface seconds(int $value) Set current instance second to the given value. * @method CarbonInterface second(int $value) Set current instance second to the given value. * @method CarbonInterface setSeconds(int $value) Set current instance second to the given value. * @method CarbonInterface setSecond(int $value) Set current instance second to the given value. * @method CarbonInterface millis(int $value) Set current instance millisecond to the given value. * @method CarbonInterface milli(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMillis(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMilli(int $value) Set current instance millisecond to the given value. * @method CarbonInterface milliseconds(int $value) Set current instance millisecond to the given value. * @method CarbonInterface millisecond(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMilliseconds(int $value) Set current instance millisecond to the given value. * @method CarbonInterface setMillisecond(int $value) Set current instance millisecond to the given value. * @method CarbonInterface micros(int $value) Set current instance microsecond to the given value. * @method CarbonInterface micro(int $value) Set current instance microsecond to the given value. * @method CarbonInterface setMicros(int $value) Set current instance microsecond to the given value. * @method CarbonInterface setMicro(int $value) Set current instance microsecond to the given value. * @method CarbonInterface microseconds(int $value) Set current instance microsecond to the given value. * @method CarbonInterface microsecond(int $value) Set current instance microsecond to the given value. * @method CarbonInterface setMicroseconds(int $value) Set current instance microsecond to the given value. * @method self setMicrosecond(int $value) Set current instance microsecond to the given value. * @method CarbonInterface addYears(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addYear() Add one year to the instance (using date interval). * @method CarbonInterface subYears(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subYear() Sub one year to the instance (using date interval). * @method CarbonInterface addYearsWithOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addYearWithOverflow() Add one year to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subYearsWithOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subYearWithOverflow() Sub one year to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addYearsWithoutOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearWithoutOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearsWithoutOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearWithoutOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearsWithNoOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearWithNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearsWithNoOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearWithNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearsNoOverflow(int|float $value = 1) Add years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addYearNoOverflow() Add one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearsNoOverflow(int|float $value = 1) Sub years (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subYearNoOverflow() Sub one year to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonths(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMonth() Add one month to the instance (using date interval). * @method CarbonInterface subMonths(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMonth() Sub one month to the instance (using date interval). * @method CarbonInterface addMonthsWithOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMonthWithOverflow() Add one month to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMonthsWithOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMonthWithOverflow() Sub one month to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMonthsWithoutOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthWithoutOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthsWithoutOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthWithoutOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthsWithNoOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthWithNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthsWithNoOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthWithNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthsNoOverflow(int|float $value = 1) Add months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMonthNoOverflow() Add one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthsNoOverflow(int|float $value = 1) Sub months (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMonthNoOverflow() Sub one month to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDays(int|float $value = 1) Add days (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addDay() Add one day to the instance (using date interval). * @method CarbonInterface subDays(int|float $value = 1) Sub days (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subDay() Sub one day to the instance (using date interval). * @method CarbonInterface addHours(int|float $value = 1) Add hours (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addHour() Add one hour to the instance (using date interval). * @method CarbonInterface subHours(int|float $value = 1) Sub hours (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subHour() Sub one hour to the instance (using date interval). * @method CarbonInterface addMinutes(int|float $value = 1) Add minutes (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMinute() Add one minute to the instance (using date interval). * @method CarbonInterface subMinutes(int|float $value = 1) Sub minutes (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMinute() Sub one minute to the instance (using date interval). * @method CarbonInterface addSeconds(int|float $value = 1) Add seconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addSecond() Add one second to the instance (using date interval). * @method CarbonInterface subSeconds(int|float $value = 1) Sub seconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subSecond() Sub one second to the instance (using date interval). * @method CarbonInterface addMillis(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMilli() Add one millisecond to the instance (using date interval). * @method CarbonInterface subMillis(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMilli() Sub one millisecond to the instance (using date interval). * @method CarbonInterface addMilliseconds(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMillisecond() Add one millisecond to the instance (using date interval). * @method CarbonInterface subMilliseconds(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMillisecond() Sub one millisecond to the instance (using date interval). * @method CarbonInterface addMicros(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMicro() Add one microsecond to the instance (using date interval). * @method CarbonInterface subMicros(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMicro() Sub one microsecond to the instance (using date interval). * @method CarbonInterface addMicroseconds(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMicrosecond() Add one microsecond to the instance (using date interval). * @method CarbonInterface subMicroseconds(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMicrosecond() Sub one microsecond to the instance (using date interval). * @method CarbonInterface addMillennia(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addMillennium() Add one millennium to the instance (using date interval). * @method CarbonInterface subMillennia(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subMillennium() Sub one millennium to the instance (using date interval). * @method CarbonInterface addMillenniaWithOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMillenniumWithOverflow() Add one millennium to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMillenniaWithOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subMillenniumWithOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addMillenniaWithoutOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniumWithoutOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniaWithoutOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniumWithoutOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniaWithNoOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniumWithNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniaWithNoOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniumWithNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniaNoOverflow(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addMillenniumNoOverflow() Add one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniaNoOverflow(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subMillenniumNoOverflow() Sub one millennium to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturies(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addCentury() Add one century to the instance (using date interval). * @method CarbonInterface subCenturies(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subCentury() Sub one century to the instance (using date interval). * @method CarbonInterface addCenturiesWithOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addCenturyWithOverflow() Add one century to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subCenturiesWithOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subCenturyWithOverflow() Sub one century to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addCenturiesWithoutOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturyWithoutOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturiesWithoutOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturyWithoutOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturiesWithNoOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturyWithNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturiesWithNoOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturyWithNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturiesNoOverflow(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addCenturyNoOverflow() Add one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturiesNoOverflow(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subCenturyNoOverflow() Sub one century to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecades(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addDecade() Add one decade to the instance (using date interval). * @method CarbonInterface subDecades(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subDecade() Sub one decade to the instance (using date interval). * @method CarbonInterface addDecadesWithOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addDecadeWithOverflow() Add one decade to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subDecadesWithOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subDecadeWithOverflow() Sub one decade to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addDecadesWithoutOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadeWithoutOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadesWithoutOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadeWithoutOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadesWithNoOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadeWithNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadesWithNoOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadeWithNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadesNoOverflow(int|float $value = 1) Add decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addDecadeNoOverflow() Add one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadesNoOverflow(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subDecadeNoOverflow() Sub one decade to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarters(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addQuarter() Add one quarter to the instance (using date interval). * @method CarbonInterface subQuarters(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subQuarter() Sub one quarter to the instance (using date interval). * @method CarbonInterface addQuartersWithOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addQuarterWithOverflow() Add one quarter to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subQuartersWithOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface subQuarterWithOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly allowed. * @method CarbonInterface addQuartersWithoutOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarterWithoutOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuartersWithoutOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuarterWithoutOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuartersWithNoOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarterWithNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuartersWithNoOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuarterWithNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuartersNoOverflow(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addQuarterNoOverflow() Add one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuartersNoOverflow(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface subQuarterNoOverflow() Sub one quarter to the instance (using date interval) with overflow explicitly forbidden. * @method CarbonInterface addWeeks(int|float $value = 1) Add weeks (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addWeek() Add one week to the instance (using date interval). * @method CarbonInterface subWeeks(int|float $value = 1) Sub weeks (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subWeek() Sub one week to the instance (using date interval). * @method CarbonInterface addWeekdays(int|float $value = 1) Add weekdays (the $value count passed in) to the instance (using date interval). * @method CarbonInterface addWeekday() Add one weekday to the instance (using date interval). * @method CarbonInterface subWeekdays(int|float $value = 1) Sub weekdays (the $value count passed in) to the instance (using date interval). * @method CarbonInterface subWeekday() Sub one weekday to the instance (using date interval). * @method CarbonInterface addUTCMicros(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMicro() Add one microsecond to the instance (using timestamp). * @method CarbonInterface subUTCMicros(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMicro() Sub one microsecond to the instance (using timestamp). * @method CarbonPeriod microsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. * @method float diffInUTCMicros(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of microseconds. * @method CarbonInterface addUTCMicroseconds(int|float $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMicrosecond() Add one microsecond to the instance (using timestamp). * @method CarbonInterface subUTCMicroseconds(int|float $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMicrosecond() Sub one microsecond to the instance (using timestamp). * @method CarbonPeriod microsecondsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each microsecond or every X microseconds if a factor is given. * @method float diffInUTCMicroseconds(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of microseconds. * @method CarbonInterface addUTCMillis(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMilli() Add one millisecond to the instance (using timestamp). * @method CarbonInterface subUTCMillis(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMilli() Sub one millisecond to the instance (using timestamp). * @method CarbonPeriod millisUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. * @method float diffInUTCMillis(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of milliseconds. * @method CarbonInterface addUTCMilliseconds(int|float $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMillisecond() Add one millisecond to the instance (using timestamp). * @method CarbonInterface subUTCMilliseconds(int|float $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMillisecond() Sub one millisecond to the instance (using timestamp). * @method CarbonPeriod millisecondsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millisecond or every X milliseconds if a factor is given. * @method float diffInUTCMilliseconds(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of milliseconds. * @method CarbonInterface addUTCSeconds(int|float $value = 1) Add seconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCSecond() Add one second to the instance (using timestamp). * @method CarbonInterface subUTCSeconds(int|float $value = 1) Sub seconds (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCSecond() Sub one second to the instance (using timestamp). * @method CarbonPeriod secondsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each second or every X seconds if a factor is given. * @method float diffInUTCSeconds(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of seconds. * @method CarbonInterface addUTCMinutes(int|float $value = 1) Add minutes (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMinute() Add one minute to the instance (using timestamp). * @method CarbonInterface subUTCMinutes(int|float $value = 1) Sub minutes (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMinute() Sub one minute to the instance (using timestamp). * @method CarbonPeriod minutesUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each minute or every X minutes if a factor is given. * @method float diffInUTCMinutes(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of minutes. * @method CarbonInterface addUTCHours(int|float $value = 1) Add hours (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCHour() Add one hour to the instance (using timestamp). * @method CarbonInterface subUTCHours(int|float $value = 1) Sub hours (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCHour() Sub one hour to the instance (using timestamp). * @method CarbonPeriod hoursUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each hour or every X hours if a factor is given. * @method float diffInUTCHours(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of hours. * @method CarbonInterface addUTCDays(int|float $value = 1) Add days (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCDay() Add one day to the instance (using timestamp). * @method CarbonInterface subUTCDays(int|float $value = 1) Sub days (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCDay() Sub one day to the instance (using timestamp). * @method CarbonPeriod daysUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each day or every X days if a factor is given. * @method float diffInUTCDays(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of days. * @method CarbonInterface addUTCWeeks(int|float $value = 1) Add weeks (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCWeek() Add one week to the instance (using timestamp). * @method CarbonInterface subUTCWeeks(int|float $value = 1) Sub weeks (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCWeek() Sub one week to the instance (using timestamp). * @method CarbonPeriod weeksUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each week or every X weeks if a factor is given. * @method float diffInUTCWeeks(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of weeks. * @method CarbonInterface addUTCMonths(int|float $value = 1) Add months (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMonth() Add one month to the instance (using timestamp). * @method CarbonInterface subUTCMonths(int|float $value = 1) Sub months (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMonth() Sub one month to the instance (using timestamp). * @method CarbonPeriod monthsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each month or every X months if a factor is given. * @method float diffInUTCMonths(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of months. * @method CarbonInterface addUTCQuarters(int|float $value = 1) Add quarters (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCQuarter() Add one quarter to the instance (using timestamp). * @method CarbonInterface subUTCQuarters(int|float $value = 1) Sub quarters (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCQuarter() Sub one quarter to the instance (using timestamp). * @method CarbonPeriod quartersUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each quarter or every X quarters if a factor is given. * @method float diffInUTCQuarters(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of quarters. * @method CarbonInterface addUTCYears(int|float $value = 1) Add years (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCYear() Add one year to the instance (using timestamp). * @method CarbonInterface subUTCYears(int|float $value = 1) Sub years (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCYear() Sub one year to the instance (using timestamp). * @method CarbonPeriod yearsUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each year or every X years if a factor is given. * @method float diffInUTCYears(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of years. * @method CarbonInterface addUTCDecades(int|float $value = 1) Add decades (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCDecade() Add one decade to the instance (using timestamp). * @method CarbonInterface subUTCDecades(int|float $value = 1) Sub decades (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCDecade() Sub one decade to the instance (using timestamp). * @method CarbonPeriod decadesUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each decade or every X decades if a factor is given. * @method float diffInUTCDecades(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of decades. * @method CarbonInterface addUTCCenturies(int|float $value = 1) Add centuries (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCCentury() Add one century to the instance (using timestamp). * @method CarbonInterface subUTCCenturies(int|float $value = 1) Sub centuries (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCCentury() Sub one century to the instance (using timestamp). * @method CarbonPeriod centuriesUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each century or every X centuries if a factor is given. * @method float diffInUTCCenturies(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of centuries. * @method CarbonInterface addUTCMillennia(int|float $value = 1) Add millennia (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface addUTCMillennium() Add one millennium to the instance (using timestamp). * @method CarbonInterface subUTCMillennia(int|float $value = 1) Sub millennia (the $value count passed in) to the instance (using timestamp). * @method CarbonInterface subUTCMillennium() Sub one millennium to the instance (using timestamp). * @method CarbonPeriod millenniaUntil($endDate = null, int|float $factor = 1) Return an iterable period from current date to given end (string, DateTime or Carbon instance) for each millennium or every X millennia if a factor is given. * @method float diffInUTCMillennia(DateTimeInterface|string|null $date, bool $absolute = false) Convert current and given date in UTC timezone and return a floating number of millennia. * @method CarbonInterface roundYear(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method CarbonInterface roundYears(float $precision = 1, string $function = "round") Round the current instance year with given precision using the given function. * @method CarbonInterface floorYear(float $precision = 1) Truncate the current instance year with given precision. * @method CarbonInterface floorYears(float $precision = 1) Truncate the current instance year with given precision. * @method CarbonInterface ceilYear(float $precision = 1) Ceil the current instance year with given precision. * @method CarbonInterface ceilYears(float $precision = 1) Ceil the current instance year with given precision. * @method CarbonInterface roundMonth(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method CarbonInterface roundMonths(float $precision = 1, string $function = "round") Round the current instance month with given precision using the given function. * @method CarbonInterface floorMonth(float $precision = 1) Truncate the current instance month with given precision. * @method CarbonInterface floorMonths(float $precision = 1) Truncate the current instance month with given precision. * @method CarbonInterface ceilMonth(float $precision = 1) Ceil the current instance month with given precision. * @method CarbonInterface ceilMonths(float $precision = 1) Ceil the current instance month with given precision. * @method CarbonInterface roundDay(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method CarbonInterface roundDays(float $precision = 1, string $function = "round") Round the current instance day with given precision using the given function. * @method CarbonInterface floorDay(float $precision = 1) Truncate the current instance day with given precision. * @method CarbonInterface floorDays(float $precision = 1) Truncate the current instance day with given precision. * @method CarbonInterface ceilDay(float $precision = 1) Ceil the current instance day with given precision. * @method CarbonInterface ceilDays(float $precision = 1) Ceil the current instance day with given precision. * @method CarbonInterface roundHour(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method CarbonInterface roundHours(float $precision = 1, string $function = "round") Round the current instance hour with given precision using the given function. * @method CarbonInterface floorHour(float $precision = 1) Truncate the current instance hour with given precision. * @method CarbonInterface floorHours(float $precision = 1) Truncate the current instance hour with given precision. * @method CarbonInterface ceilHour(float $precision = 1) Ceil the current instance hour with given precision. * @method CarbonInterface ceilHours(float $precision = 1) Ceil the current instance hour with given precision. * @method CarbonInterface roundMinute(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method CarbonInterface roundMinutes(float $precision = 1, string $function = "round") Round the current instance minute with given precision using the given function. * @method CarbonInterface floorMinute(float $precision = 1) Truncate the current instance minute with given precision. * @method CarbonInterface floorMinutes(float $precision = 1) Truncate the current instance minute with given precision. * @method CarbonInterface ceilMinute(float $precision = 1) Ceil the current instance minute with given precision. * @method CarbonInterface ceilMinutes(float $precision = 1) Ceil the current instance minute with given precision. * @method CarbonInterface roundSecond(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method CarbonInterface roundSeconds(float $precision = 1, string $function = "round") Round the current instance second with given precision using the given function. * @method CarbonInterface floorSecond(float $precision = 1) Truncate the current instance second with given precision. * @method CarbonInterface floorSeconds(float $precision = 1) Truncate the current instance second with given precision. * @method CarbonInterface ceilSecond(float $precision = 1) Ceil the current instance second with given precision. * @method CarbonInterface ceilSeconds(float $precision = 1) Ceil the current instance second with given precision. * @method CarbonInterface roundMillennium(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method CarbonInterface roundMillennia(float $precision = 1, string $function = "round") Round the current instance millennium with given precision using the given function. * @method CarbonInterface floorMillennium(float $precision = 1) Truncate the current instance millennium with given precision. * @method CarbonInterface floorMillennia(float $precision = 1) Truncate the current instance millennium with given precision. * @method CarbonInterface ceilMillennium(float $precision = 1) Ceil the current instance millennium with given precision. * @method CarbonInterface ceilMillennia(float $precision = 1) Ceil the current instance millennium with given precision. * @method CarbonInterface roundCentury(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method CarbonInterface roundCenturies(float $precision = 1, string $function = "round") Round the current instance century with given precision using the given function. * @method CarbonInterface floorCentury(float $precision = 1) Truncate the current instance century with given precision. * @method CarbonInterface floorCenturies(float $precision = 1) Truncate the current instance century with given precision. * @method CarbonInterface ceilCentury(float $precision = 1) Ceil the current instance century with given precision. * @method CarbonInterface ceilCenturies(float $precision = 1) Ceil the current instance century with given precision. * @method CarbonInterface roundDecade(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method CarbonInterface roundDecades(float $precision = 1, string $function = "round") Round the current instance decade with given precision using the given function. * @method CarbonInterface floorDecade(float $precision = 1) Truncate the current instance decade with given precision. * @method CarbonInterface floorDecades(float $precision = 1) Truncate the current instance decade with given precision. * @method CarbonInterface ceilDecade(float $precision = 1) Ceil the current instance decade with given precision. * @method CarbonInterface ceilDecades(float $precision = 1) Ceil the current instance decade with given precision. * @method CarbonInterface roundQuarter(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method CarbonInterface roundQuarters(float $precision = 1, string $function = "round") Round the current instance quarter with given precision using the given function. * @method CarbonInterface floorQuarter(float $precision = 1) Truncate the current instance quarter with given precision. * @method CarbonInterface floorQuarters(float $precision = 1) Truncate the current instance quarter with given precision. * @method CarbonInterface ceilQuarter(float $precision = 1) Ceil the current instance quarter with given precision. * @method CarbonInterface ceilQuarters(float $precision = 1) Ceil the current instance quarter with given precision. * @method CarbonInterface roundMillisecond(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method CarbonInterface roundMilliseconds(float $precision = 1, string $function = "round") Round the current instance millisecond with given precision using the given function. * @method CarbonInterface floorMillisecond(float $precision = 1) Truncate the current instance millisecond with given precision. * @method CarbonInterface floorMilliseconds(float $precision = 1) Truncate the current instance millisecond with given precision. * @method CarbonInterface ceilMillisecond(float $precision = 1) Ceil the current instance millisecond with given precision. * @method CarbonInterface ceilMilliseconds(float $precision = 1) Ceil the current instance millisecond with given precision. * @method CarbonInterface roundMicrosecond(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method CarbonInterface roundMicroseconds(float $precision = 1, string $function = "round") Round the current instance microsecond with given precision using the given function. * @method CarbonInterface floorMicrosecond(float $precision = 1) Truncate the current instance microsecond with given precision. * @method CarbonInterface floorMicroseconds(float $precision = 1) Truncate the current instance microsecond with given precision. * @method CarbonInterface ceilMicrosecond(float $precision = 1) Ceil the current instance microsecond with given precision. * @method CarbonInterface ceilMicroseconds(float $precision = 1) Ceil the current instance microsecond with given precision. * @method string shortAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longAbsoluteDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Absolute' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string shortRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longRelativeDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'Relative' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string shortRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longRelativeToNowDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToNow' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string shortRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (short format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method string longRelativeToOtherDiffForHumans(DateTimeInterface $other = null, int $parts = 1) Get the difference (long format, 'RelativeToOther' mode) in a human readable format in the current locale. ($other and $parts parameters can be swapped.) * @method int centuriesInMillennium() Return the number of centuries contained in the current millennium * @method int|static centuryOfMillennium(?int $century = null) Return the value of the century starting from the beginning of the current millennium when called with no parameters, change the current century when called with an integer value * @method int|static dayOfCentury(?int $day = null) Return the value of the day starting from the beginning of the current century when called with no parameters, change the current day when called with an integer value * @method int|static dayOfDecade(?int $day = null) Return the value of the day starting from the beginning of the current decade when called with no parameters, change the current day when called with an integer value * @method int|static dayOfMillennium(?int $day = null) Return the value of the day starting from the beginning of the current millennium when called with no parameters, change the current day when called with an integer value * @method int|static dayOfMonth(?int $day = null) Return the value of the day starting from the beginning of the current month when called with no parameters, change the current day when called with an integer value * @method int|static dayOfQuarter(?int $day = null) Return the value of the day starting from the beginning of the current quarter when called with no parameters, change the current day when called with an integer value * @method int|static dayOfWeek(?int $day = null) Return the value of the day starting from the beginning of the current week when called with no parameters, change the current day when called with an integer value * @method int daysInCentury() Return the number of days contained in the current century * @method int daysInDecade() Return the number of days contained in the current decade * @method int daysInMillennium() Return the number of days contained in the current millennium * @method int daysInMonth() Return the number of days contained in the current month * @method int daysInQuarter() Return the number of days contained in the current quarter * @method int daysInWeek() Return the number of days contained in the current week * @method int daysInYear() Return the number of days contained in the current year * @method int|static decadeOfCentury(?int $decade = null) Return the value of the decade starting from the beginning of the current century when called with no parameters, change the current decade when called with an integer value * @method int|static decadeOfMillennium(?int $decade = null) Return the value of the decade starting from the beginning of the current millennium when called with no parameters, change the current decade when called with an integer value * @method int decadesInCentury() Return the number of decades contained in the current century * @method int decadesInMillennium() Return the number of decades contained in the current millennium * @method int|static hourOfCentury(?int $hour = null) Return the value of the hour starting from the beginning of the current century when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfDay(?int $hour = null) Return the value of the hour starting from the beginning of the current day when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfDecade(?int $hour = null) Return the value of the hour starting from the beginning of the current decade when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfMillennium(?int $hour = null) Return the value of the hour starting from the beginning of the current millennium when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfMonth(?int $hour = null) Return the value of the hour starting from the beginning of the current month when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfQuarter(?int $hour = null) Return the value of the hour starting from the beginning of the current quarter when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfWeek(?int $hour = null) Return the value of the hour starting from the beginning of the current week when called with no parameters, change the current hour when called with an integer value * @method int|static hourOfYear(?int $hour = null) Return the value of the hour starting from the beginning of the current year when called with no parameters, change the current hour when called with an integer value * @method int hoursInCentury() Return the number of hours contained in the current century * @method int hoursInDay() Return the number of hours contained in the current day * @method int hoursInDecade() Return the number of hours contained in the current decade * @method int hoursInMillennium() Return the number of hours contained in the current millennium * @method int hoursInMonth() Return the number of hours contained in the current month * @method int hoursInQuarter() Return the number of hours contained in the current quarter * @method int hoursInWeek() Return the number of hours contained in the current week * @method int hoursInYear() Return the number of hours contained in the current year * @method int|static microsecondOfCentury(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current century when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfDay(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current day when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfDecade(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current decade when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfHour(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current hour when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMillennium(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current millennium when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMillisecond(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current millisecond when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMinute(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current minute when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfMonth(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current month when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfQuarter(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current quarter when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfSecond(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current second when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfWeek(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current week when called with no parameters, change the current microsecond when called with an integer value * @method int|static microsecondOfYear(?int $microsecond = null) Return the value of the microsecond starting from the beginning of the current year when called with no parameters, change the current microsecond when called with an integer value * @method int microsecondsInCentury() Return the number of microseconds contained in the current century * @method int microsecondsInDay() Return the number of microseconds contained in the current day * @method int microsecondsInDecade() Return the number of microseconds contained in the current decade * @method int microsecondsInHour() Return the number of microseconds contained in the current hour * @method int microsecondsInMillennium() Return the number of microseconds contained in the current millennium * @method int microsecondsInMillisecond() Return the number of microseconds contained in the current millisecond * @method int microsecondsInMinute() Return the number of microseconds contained in the current minute * @method int microsecondsInMonth() Return the number of microseconds contained in the current month * @method int microsecondsInQuarter() Return the number of microseconds contained in the current quarter * @method int microsecondsInSecond() Return the number of microseconds contained in the current second * @method int microsecondsInWeek() Return the number of microseconds contained in the current week * @method int microsecondsInYear() Return the number of microseconds contained in the current year * @method int|static millisecondOfCentury(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current century when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfDay(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current day when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfDecade(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current decade when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfHour(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current hour when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfMillennium(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current millennium when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfMinute(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current minute when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfMonth(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current month when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfQuarter(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current quarter when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfSecond(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current second when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfWeek(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current week when called with no parameters, change the current millisecond when called with an integer value * @method int|static millisecondOfYear(?int $millisecond = null) Return the value of the millisecond starting from the beginning of the current year when called with no parameters, change the current millisecond when called with an integer value * @method int millisecondsInCentury() Return the number of milliseconds contained in the current century * @method int millisecondsInDay() Return the number of milliseconds contained in the current day * @method int millisecondsInDecade() Return the number of milliseconds contained in the current decade * @method int millisecondsInHour() Return the number of milliseconds contained in the current hour * @method int millisecondsInMillennium() Return the number of milliseconds contained in the current millennium * @method int millisecondsInMinute() Return the number of milliseconds contained in the current minute * @method int millisecondsInMonth() Return the number of milliseconds contained in the current month * @method int millisecondsInQuarter() Return the number of milliseconds contained in the current quarter * @method int millisecondsInSecond() Return the number of milliseconds contained in the current second * @method int millisecondsInWeek() Return the number of milliseconds contained in the current week * @method int millisecondsInYear() Return the number of milliseconds contained in the current year * @method int|static minuteOfCentury(?int $minute = null) Return the value of the minute starting from the beginning of the current century when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfDay(?int $minute = null) Return the value of the minute starting from the beginning of the current day when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfDecade(?int $minute = null) Return the value of the minute starting from the beginning of the current decade when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfHour(?int $minute = null) Return the value of the minute starting from the beginning of the current hour when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfMillennium(?int $minute = null) Return the value of the minute starting from the beginning of the current millennium when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfMonth(?int $minute = null) Return the value of the minute starting from the beginning of the current month when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfQuarter(?int $minute = null) Return the value of the minute starting from the beginning of the current quarter when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfWeek(?int $minute = null) Return the value of the minute starting from the beginning of the current week when called with no parameters, change the current minute when called with an integer value * @method int|static minuteOfYear(?int $minute = null) Return the value of the minute starting from the beginning of the current year when called with no parameters, change the current minute when called with an integer value * @method int minutesInCentury() Return the number of minutes contained in the current century * @method int minutesInDay() Return the number of minutes contained in the current day * @method int minutesInDecade() Return the number of minutes contained in the current decade * @method int minutesInHour() Return the number of minutes contained in the current hour * @method int minutesInMillennium() Return the number of minutes contained in the current millennium * @method int minutesInMonth() Return the number of minutes contained in the current month * @method int minutesInQuarter() Return the number of minutes contained in the current quarter * @method int minutesInWeek() Return the number of minutes contained in the current week * @method int minutesInYear() Return the number of minutes contained in the current year * @method int|static monthOfCentury(?int $month = null) Return the value of the month starting from the beginning of the current century when called with no parameters, change the current month when called with an integer value * @method int|static monthOfDecade(?int $month = null) Return the value of the month starting from the beginning of the current decade when called with no parameters, change the current month when called with an integer value * @method int|static monthOfMillennium(?int $month = null) Return the value of the month starting from the beginning of the current millennium when called with no parameters, change the current month when called with an integer value * @method int|static monthOfQuarter(?int $month = null) Return the value of the month starting from the beginning of the current quarter when called with no parameters, change the current month when called with an integer value * @method int|static monthOfYear(?int $month = null) Return the value of the month starting from the beginning of the current year when called with no parameters, change the current month when called with an integer value * @method int monthsInCentury() Return the number of months contained in the current century * @method int monthsInDecade() Return the number of months contained in the current decade * @method int monthsInMillennium() Return the number of months contained in the current millennium * @method int monthsInQuarter() Return the number of months contained in the current quarter * @method int monthsInYear() Return the number of months contained in the current year * @method int|static quarterOfCentury(?int $quarter = null) Return the value of the quarter starting from the beginning of the current century when called with no parameters, change the current quarter when called with an integer value * @method int|static quarterOfDecade(?int $quarter = null) Return the value of the quarter starting from the beginning of the current decade when called with no parameters, change the current quarter when called with an integer value * @method int|static quarterOfMillennium(?int $quarter = null) Return the value of the quarter starting from the beginning of the current millennium when called with no parameters, change the current quarter when called with an integer value * @method int|static quarterOfYear(?int $quarter = null) Return the value of the quarter starting from the beginning of the current year when called with no parameters, change the current quarter when called with an integer value * @method int quartersInCentury() Return the number of quarters contained in the current century * @method int quartersInDecade() Return the number of quarters contained in the current decade * @method int quartersInMillennium() Return the number of quarters contained in the current millennium * @method int quartersInYear() Return the number of quarters contained in the current year * @method int|static secondOfCentury(?int $second = null) Return the value of the second starting from the beginning of the current century when called with no parameters, change the current second when called with an integer value * @method int|static secondOfDay(?int $second = null) Return the value of the second starting from the beginning of the current day when called with no parameters, change the current second when called with an integer value * @method int|static secondOfDecade(?int $second = null) Return the value of the second starting from the beginning of the current decade when called with no parameters, change the current second when called with an integer value * @method int|static secondOfHour(?int $second = null) Return the value of the second starting from the beginning of the current hour when called with no parameters, change the current second when called with an integer value * @method int|static secondOfMillennium(?int $second = null) Return the value of the second starting from the beginning of the current millennium when called with no parameters, change the current second when called with an integer value * @method int|static secondOfMinute(?int $second = null) Return the value of the second starting from the beginning of the current minute when called with no parameters, change the current second when called with an integer value * @method int|static secondOfMonth(?int $second = null) Return the value of the second starting from the beginning of the current month when called with no parameters, change the current second when called with an integer value * @method int|static secondOfQuarter(?int $second = null) Return the value of the second starting from the beginning of the current quarter when called with no parameters, change the current second when called with an integer value * @method int|static secondOfWeek(?int $second = null) Return the value of the second starting from the beginning of the current week when called with no parameters, change the current second when called with an integer value * @method int|static secondOfYear(?int $second = null) Return the value of the second starting from the beginning of the current year when called with no parameters, change the current second when called with an integer value * @method int secondsInCentury() Return the number of seconds contained in the current century * @method int secondsInDay() Return the number of seconds contained in the current day * @method int secondsInDecade() Return the number of seconds contained in the current decade * @method int secondsInHour() Return the number of seconds contained in the current hour * @method int secondsInMillennium() Return the number of seconds contained in the current millennium * @method int secondsInMinute() Return the number of seconds contained in the current minute * @method int secondsInMonth() Return the number of seconds contained in the current month * @method int secondsInQuarter() Return the number of seconds contained in the current quarter * @method int secondsInWeek() Return the number of seconds contained in the current week * @method int secondsInYear() Return the number of seconds contained in the current year * @method int|static weekOfCentury(?int $week = null) Return the value of the week starting from the beginning of the current century when called with no parameters, change the current week when called with an integer value * @method int|static weekOfDecade(?int $week = null) Return the value of the week starting from the beginning of the current decade when called with no parameters, change the current week when called with an integer value * @method int|static weekOfMillennium(?int $week = null) Return the value of the week starting from the beginning of the current millennium when called with no parameters, change the current week when called with an integer value * @method int|static weekOfMonth(?int $week = null) Return the value of the week starting from the beginning of the current month when called with no parameters, change the current week when called with an integer value * @method int|static weekOfQuarter(?int $week = null) Return the value of the week starting from the beginning of the current quarter when called with no parameters, change the current week when called with an integer value * @method int|static weekOfYear(?int $week = null) Return the value of the week starting from the beginning of the current year when called with no parameters, change the current week when called with an integer value * @method int weeksInCentury() Return the number of weeks contained in the current century * @method int weeksInDecade() Return the number of weeks contained in the current decade * @method int weeksInMillennium() Return the number of weeks contained in the current millennium * @method int weeksInMonth() Return the number of weeks contained in the current month * @method int weeksInQuarter() Return the number of weeks contained in the current quarter * @method int|static yearOfCentury(?int $year = null) Return the value of the year starting from the beginning of the current century when called with no parameters, change the current year when called with an integer value * @method int|static yearOfDecade(?int $year = null) Return the value of the year starting from the beginning of the current decade when called with no parameters, change the current year when called with an integer value * @method int|static yearOfMillennium(?int $year = null) Return the value of the year starting from the beginning of the current millennium when called with no parameters, change the current year when called with an integer value * @method int yearsInCentury() Return the number of years contained in the current century * @method int yearsInDecade() Return the number of years contained in the current decade * @method int yearsInMillennium() Return the number of years contained in the current millennium * * </autodoc> */ trait Date { use Boundaries; use Comparison; use Converter; use Creator; use Difference; use Macro; use MagicParameter; use Modifiers; use Mutability; use ObjectInitialisation; use Options; use Rounding; use Serialization; use Test; use Timestamp; use Units; use Week; /** * Names of days of the week. * * @var array */ protected static $days = [ // @call isDayOfWeek CarbonInterface::SUNDAY => 'Sunday', // @call isDayOfWeek CarbonInterface::MONDAY => 'Monday', // @call isDayOfWeek CarbonInterface::TUESDAY => 'Tuesday', // @call isDayOfWeek CarbonInterface::WEDNESDAY => 'Wednesday', // @call isDayOfWeek CarbonInterface::THURSDAY => 'Thursday', // @call isDayOfWeek CarbonInterface::FRIDAY => 'Friday', // @call isDayOfWeek CarbonInterface::SATURDAY => 'Saturday', ]; /** * List of unit and magic methods associated as doc-comments. * * @var array */ protected static $units = [ // @call setUnit // @call addUnit 'year', // @call setUnit // @call addUnit 'month', // @call setUnit // @call addUnit 'day', // @call setUnit // @call addUnit 'hour', // @call setUnit // @call addUnit 'minute', // @call setUnit // @call addUnit 'second', // @call setUnit // @call addUnit 'milli', // @call setUnit // @call addUnit 'millisecond', // @call setUnit // @call addUnit 'micro', // @call setUnit // @call addUnit 'microsecond', ]; /** * Creates a DateTimeZone from a string, DateTimeZone or integer offset. * * @param DateTimeZone|string|int|false|null $object original value to get CarbonTimeZone from it. * @param DateTimeZone|string|int|false|null $objectDump dump of the object for error messages. * * @throws InvalidTimeZoneException * * @return CarbonTimeZone|null */ protected static function safeCreateDateTimeZone( DateTimeZone|string|int|false|null $object, DateTimeZone|string|int|false|null $objectDump = null, ): ?CarbonTimeZone { return CarbonTimeZone::instance($object, $objectDump); } /** * Get the TimeZone associated with the Carbon instance (as CarbonTimeZone). * * @link https://php.net/manual/en/datetime.gettimezone.php */ public function getTimezone(): CarbonTimeZone { return $this->transmitFactory(fn () => CarbonTimeZone::instance(parent::getTimezone())); } /** * List of minimum and maximums for each unit. */ protected static function getRangesByUnit(int $daysInMonth = 31): array { return [ // @call roundUnit 'year' => [1, 9999], // @call roundUnit 'month' => [1, static::MONTHS_PER_YEAR], // @call roundUnit 'day' => [1, $daysInMonth], // @call roundUnit 'hour' => [0, static::HOURS_PER_DAY - 1], // @call roundUnit 'minute' => [0, static::MINUTES_PER_HOUR - 1], // @call roundUnit 'second' => [0, static::SECONDS_PER_MINUTE - 1], ]; } /** * Get a copy of the instance. * * @return static */ public function copy() { return clone $this; } /** * @alias copy * * Get a copy of the instance. * * @return static */ public function clone() { return clone $this; } /** * Clone the current instance if it's mutable. * * This method is convenient to ensure you don't mutate the initial object * but avoid to make a useless copy of it if it's already immutable. * * @return static */ public function avoidMutation(): static { if ($this instanceof DateTimeImmutable) { return $this; } return clone $this; } /** * Returns a present instance in the same timezone. * * @return static */ public function nowWithSameTz(): static { $timezone = $this->getTimezone(); return $this->getClock()?->nowAs(static::class, $timezone) ?? static::now($timezone); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. * * @param Carbon|\Carbon\CarbonPeriod|\Carbon\CarbonInterval|\DateInterval|\DatePeriod|DateTimeInterface|string|null $date * * @return static */ public function carbonize($date = null) { if ($date instanceof DateInterval) { return $this->avoidMutation()->add($date); } if ($date instanceof DatePeriod || $date instanceof CarbonPeriod) { $date = $date->getStartDate(); } return $this->resolveCarbon($date); } /////////////////////////////////////////////////////////////////// ///////////////////////// GETTERS AND SETTERS ///////////////////// /////////////////////////////////////////////////////////////////// /** * Get a part of the Carbon object. * * @throws UnknownGetterException * * @return string|int|bool|DateTimeZone|null */ public function __get(string $name): mixed { return $this->get($name); } /** * Get a part of the Carbon object. * * @throws UnknownGetterException * * @return string|int|bool|DateTimeZone */ public function get(Unit|string $name): mixed { static $localizedFormats = [ // @property string the day of week in current locale 'localeDayOfWeek' => 'dddd', // @property string the abbreviated day of week in current locale 'shortLocaleDayOfWeek' => 'ddd', // @property string the month in current locale 'localeMonth' => 'MMMM', // @property string the abbreviated month in current locale 'shortLocaleMonth' => 'MMM', ]; $name = Unit::toName($name); if (isset($localizedFormats[$name])) { return $this->isoFormat($localizedFormats[$name]); } static $formats = [ // @property int 'year' => 'Y', // @property int 'yearIso' => 'o', // @--property-read int // @--property-write Month|int // @property int 'month' => 'n', // @property int 'day' => 'j', // @property int 'hour' => 'G', // @property int 'minute' => 'i', // @property int 'second' => 's', // @property int 'micro' => 'u', // @property int 'microsecond' => 'u', // @property int 0 (for Sunday) through 6 (for Saturday) 'dayOfWeek' => 'w', // @property int 1 (for Monday) through 7 (for Sunday) 'dayOfWeekIso' => 'N', // @property int ISO-8601 week number of year, weeks starting on Monday 'weekOfYear' => 'W', // @property-read int number of days in the given month 'daysInMonth' => 't', // @property int|float|string seconds since the Unix Epoch 'timestamp' => 'U', // @property-read string "am"/"pm" (Ante meridiem or Post meridiem latin lowercase mark) 'latinMeridiem' => 'a', // @property-read string "AM"/"PM" (Ante meridiem or Post meridiem latin uppercase mark) 'latinUpperMeridiem' => 'A', // @property string the day of week in English 'englishDayOfWeek' => 'l', // @property string the abbreviated day of week in English 'shortEnglishDayOfWeek' => 'D', // @property string the month in English 'englishMonth' => 'F', // @property string the abbreviated month in English 'shortEnglishMonth' => 'M', // @property-read string $timezoneAbbreviatedName the current timezone abbreviated name 'timezoneAbbreviatedName' => 'T', // @property-read string $tzAbbrName alias of $timezoneAbbreviatedName 'tzAbbrName' => 'T', ]; switch (true) { case isset($formats[$name]): $value = $this->rawFormat($formats[$name]); return is_numeric($value) ? (int) $value : $value; // @property-read string long name of weekday translated according to Carbon locale, in english if no translation available for current language case $name === 'dayName': return $this->getTranslatedDayName(); // @property-read string short name of weekday translated according to Carbon locale, in english if no translation available for current language case $name === 'shortDayName': return $this->getTranslatedShortDayName(); // @property-read string very short name of weekday translated according to Carbon locale, in english if no translation available for current language case $name === 'minDayName': return $this->getTranslatedMinDayName(); // @property-read string long name of month translated according to Carbon locale, in english if no translation available for current language case $name === 'monthName': return $this->getTranslatedMonthName(); // @property-read string short name of month translated according to Carbon locale, in english if no translation available for current language case $name === 'shortMonthName': return $this->getTranslatedShortMonthName(); // @property-read string lowercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language case $name === 'meridiem': return $this->meridiem(true); // @property-read string uppercase meridiem mark translated according to Carbon locale, in latin if no translation available for current language case $name === 'upperMeridiem': return $this->meridiem(); // @property-read int current hour from 1 to 24 case $name === 'noZeroHour': return $this->hour ?: 24; // @property int case $name === 'milliseconds': // @property int case $name === 'millisecond': // @property int case $name === 'milli': return (int) floor(((int) $this->rawFormat('u')) / 1000); // @property int 1 through 53 case $name === 'week': return (int) $this->week(); // @property int 1 through 53 case $name === 'isoWeek': return (int) $this->isoWeek(); // @property int year according to week format case $name === 'weekYear': return (int) $this->weekYear(); // @property int year according to ISO week format case $name === 'isoWeekYear': return (int) $this->isoWeekYear(); // @property-read int 51 through 53 case $name === 'weeksInYear': return $this->weeksInYear(); // @property-read int 51 through 53 case $name === 'isoWeeksInYear': return $this->isoWeeksInYear(); // @property int 1 through 5 case $name === 'weekOfMonth': return (int) ceil($this->day / static::DAYS_PER_WEEK); // @property-read int 1 through 5 case $name === 'weekNumberInMonth': return (int) ceil(($this->day + $this->avoidMutation()->startOfMonth()->dayOfWeekIso - 1) / static::DAYS_PER_WEEK); // @property-read int 0 through 6 case $name === 'firstWeekDay': return (int) $this->getTranslationMessage('first_day_of_week'); // @property-read int 0 through 6 case $name === 'lastWeekDay': return $this->transmitFactory(fn () => static::weekRotate((int) $this->getTranslationMessage('first_day_of_week'), -1)); // @property int 1 through 366 case $name === 'dayOfYear': return 1 + (int) ($this->rawFormat('z')); // @property-read int 365 or 366 case $name === 'daysInYear': return static::DAYS_PER_YEAR + ($this->isLeapYear() ? 1 : 0); // @property int does a diffInYears() with default parameters case $name === 'age': return (int) $this->diffInYears(); // @property-read int the quarter of this instance, 1 - 4 case $name === 'quarter': return (int) ceil($this->month / static::MONTHS_PER_QUARTER); // @property-read int the decade of this instance // @call isSameUnit case $name === 'decade': return (int) ceil($this->year / static::YEARS_PER_DECADE); // @property-read int the century of this instance // @call isSameUnit case $name === 'century': $factor = 1; $year = $this->year; if ($year < 0) { $year = -$year; $factor = -1; } return (int) ($factor * ceil($year / static::YEARS_PER_CENTURY)); // @property-read int the millennium of this instance // @call isSameUnit case $name === 'millennium': $factor = 1; $year = $this->year; if ($year < 0) { $year = -$year; $factor = -1; } return (int) ($factor * ceil($year / static::YEARS_PER_MILLENNIUM)); // @property int the timezone offset in seconds from UTC case $name === 'offset': return $this->getOffset(); // @property int the timezone offset in minutes from UTC case $name === 'offsetMinutes': return $this->getOffset() / static::SECONDS_PER_MINUTE; // @property int the timezone offset in hours from UTC case $name === 'offsetHours': return $this->getOffset() / static::SECONDS_PER_MINUTE / static::MINUTES_PER_HOUR; // @property-read bool daylight savings time indicator, true if DST, false otherwise case $name === 'dst': return $this->rawFormat('I') === '1'; // @property-read bool checks if the timezone is local, true if local, false otherwise case $name === 'local': return $this->getOffset() === $this->avoidMutation()->setTimezone(date_default_timezone_get())->getOffset(); // @property-read bool checks if the timezone is UTC, true if UTC, false otherwise case $name === 'utc': return $this->getOffset() === 0; // @--property-write DateTimeZone|string|int $timezone the current timezone // @--property-write DateTimeZone|string|int $tz alias of $timezone // @--property-read CarbonTimeZone $timezone the current timezone // @--property-read CarbonTimeZone $tz alias of $timezone // @property CarbonTimeZone $timezone the current timezone // @property CarbonTimeZone $tz alias of $timezone case $name === 'timezone' || $name === 'tz': return $this->getTimezone(); // @property-read string $timezoneName the current timezone name // @property-read string $tzName alias of $timezoneName case $name === 'timezoneName' || $name === 'tzName': return $this->getTimezone()->getName(); // @property-read string locale of the current instance case $name === 'locale': return $this->getTranslatorLocale(); case preg_match('/^([a-z]{2,})(In|Of)([A-Z][a-z]+)$/', $name, $match): [, $firstUnit, $operator, $secondUnit] = $match; try { $start = $this->avoidMutation()->startOf($secondUnit); $value = $operator === 'Of' ? (\in_array($firstUnit, [ // Unit with indexes starting at 1 (other units start at 0) 'day', 'week', 'month', 'quarter', ], true) ? 1 : 0) + floor($start->diffInUnit($firstUnit, $this)) : round($start->diffInUnit($firstUnit, $start->avoidMutation()->add($secondUnit, 1))); return (int) $value; } catch (UnknownUnitException) { // default to macro } default: $macro = $this->getLocalMacro('get'.ucfirst($name)); if ($macro) { return $this->executeCallableWithContext($macro); } throw new UnknownGetterException($name); } } /** * Check if an attribute exists on the object * * @param string $name * * @return bool */ public function __isset($name) { try { $this->__get($name); } catch (UnknownGetterException | ReflectionException) { return false; } return true; } /** * Set a part of the Carbon object * * @param string $name * @param string|int|DateTimeZone $value * * @throws UnknownSetterException|ReflectionException * * @return void */ public function __set($name, $value) { if ($this->constructedObjectId === spl_object_hash($this)) { $this->set($name, $value); return; } $this->$name = $value; } /** * Set a part of the Carbon object. * * @throws ImmutableException|UnknownSetterException * * @return $this */ public function set(Unit|array|string $name, DateTimeZone|Month|string|int|float|null $value = null): static { if ($this->isImmutable()) { throw new ImmutableException(\sprintf('%s class', static::class)); } if (\is_array($name)) { foreach ($name as $key => $value) { $this->set($key, $value); } return $this; } $name = Unit::toName($name); switch ($name) { case 'milliseconds': case 'millisecond': case 'milli': case 'microseconds': case 'microsecond': case 'micro': if (str_starts_with($name, 'milli')) { $value *= 1000; } while ($value < 0) { $this->subSecond(); $value += static::MICROSECONDS_PER_SECOND; } while ($value >= static::MICROSECONDS_PER_SECOND) { $this->addSecond(); $value -= static::MICROSECONDS_PER_SECOND; } $this->modify($this->rawFormat('H:i:s.').str_pad((string) round($value), 6, '0', STR_PAD_LEFT)); break; case 'year': case 'month': case 'day': case 'hour': case 'minute': case 'second': [$year, $month, $day, $hour, $minute, $second] = array_map('intval', explode('-', $this->rawFormat('Y-n-j-G-i-s'))); $$name = self::monthToInt($value, $name); $this->setDateTime($year, $month, $day, $hour, $minute, $second); break; case 'week': $this->week($value); break; case 'isoWeek': $this->isoWeek($value); break; case 'weekYear': $this->weekYear($value); break; case 'isoWeekYear': $this->isoWeekYear($value); break; case 'dayOfYear': $this->addDays($value - $this->dayOfYear); break; case 'dayOfWeek': $this->addDays($value - $this->dayOfWeek); break; case 'dayOfWeekIso': $this->addDays($value - $this->dayOfWeekIso); break; case 'timestamp': $this->setTimestamp($value); break; case 'offset': $this->setTimezone(static::safeCreateDateTimeZone($value / static::SECONDS_PER_MINUTE / static::MINUTES_PER_HOUR)); break; case 'offsetMinutes': $this->setTimezone(static::safeCreateDateTimeZone($value / static::MINUTES_PER_HOUR)); break; case 'offsetHours': $this->setTimezone(static::safeCreateDateTimeZone($value)); break; case 'timezone': case 'tz': $this->setTimezone($value); break; default: if (preg_match('/^([a-z]{2,})Of([A-Z][a-z]+)$/', $name, $match)) { [, $firstUnit, $secondUnit] = $match; try { $start = $this->avoidMutation()->startOf($secondUnit); $currentValue = (\in_array($firstUnit, [ // Unit with indexes starting at 1 (other units start at 0) 'day', 'week', 'month', 'quarter', ], true) ? 1 : 0) + (int) floor($start->diffInUnit($firstUnit, $this)); // We check $value a posteriori to give precedence to UnknownUnitException if (!\is_int($value)) { throw new UnitException("->$name expects integer value"); } $this->addUnit($firstUnit, $value - $currentValue); break; } catch (UnknownUnitException) { // default to macro } } $macro = $this->getLocalMacro('set'.ucfirst($name)); if ($macro) { $this->executeCallableWithContext($macro, $value); break; } if ($this->isLocalStrictModeEnabled()) { throw new UnknownSetterException($name); } $this->$name = $value; } return $this; } /** * Get the translation of the current week day name (with context for languages with multiple forms). * * @param string|null $context whole format string * @param string $keySuffix "", "_short" or "_min" * @param string|null $defaultValue default value if translation missing */ public function getTranslatedDayName( ?string $context = null, string $keySuffix = '', ?string $defaultValue = null, ): string { return $this->getTranslatedFormByRegExp('weekdays', $keySuffix, $context, $this->dayOfWeek, $defaultValue ?: $this->englishDayOfWeek); } /** * Get the translation of the current short week day name (with context for languages with multiple forms). * * @param string|null $context whole format string */ public function getTranslatedShortDayName(?string $context = null): string { return $this->getTranslatedDayName($context, '_short', $this->shortEnglishDayOfWeek); } /** * Get the translation of the current abbreviated week day name (with context for languages with multiple forms). * * @param string|null $context whole format string */ public function getTranslatedMinDayName(?string $context = null): string { return $this->getTranslatedDayName($context, '_min', $this->shortEnglishDayOfWeek); } /** * Get the translation of the current month day name (with context for languages with multiple forms). * * @param string|null $context whole format string * @param string $keySuffix "" or "_short" * @param string|null $defaultValue default value if translation missing */ public function getTranslatedMonthName( ?string $context = null, string $keySuffix = '', ?string $defaultValue = null, ): string { return $this->getTranslatedFormByRegExp('months', $keySuffix, $context, $this->month - 1, $defaultValue ?: $this->englishMonth); } /** * Get the translation of the current short month day name (with context for languages with multiple forms). * * @param string|null $context whole format string */ public function getTranslatedShortMonthName(?string $context = null): string { return $this->getTranslatedMonthName($context, '_short', $this->shortEnglishMonth); } /** * Get/set the day of year. * * @template T of int|null * * @param int|null $value new value for day of year if using as setter. * * @psalm-param T $value * * @return static|int * * @psalm-return (T is int ? static : int) */ public function dayOfYear(?int $value = null): static|int { $dayOfYear = $this->dayOfYear; return $value === null ? $dayOfYear : $this->addDays($value - $dayOfYear); } /** * Get/set the weekday from 0 (Sunday) to 6 (Saturday). * * @param WeekDay|int|null $value new value for weekday if using as setter. */ public function weekday(WeekDay|int|null $value = null): static|int { if ($value === null) { return $this->dayOfWeek; } $firstDay = (int) ($this->getTranslationMessage('first_day_of_week') ?? 0); $dayOfWeek = ($this->dayOfWeek + 7 - $firstDay) % 7; return $this->addDays(((WeekDay::int($value) + 7 - $firstDay) % 7) - $dayOfWeek); } /** * Get/set the ISO weekday from 1 (Monday) to 7 (Sunday). * * @param WeekDay|int|null $value new value for weekday if using as setter. */ public function isoWeekday(WeekDay|int|null $value = null): static|int { $dayOfWeekIso = $this->dayOfWeekIso; return $value === null ? $dayOfWeekIso : $this->addDays(WeekDay::int($value) - $dayOfWeekIso); } /** * Return the number of days since the start of the week (using the current locale or the first parameter * if explicitly given). * * @param WeekDay|int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week, * if not provided, start of week is inferred from the locale * (Sunday for en_US, Monday for de_DE, etc.) */ public function getDaysFromStartOfWeek(WeekDay|int|null $weekStartsAt = null): int { $firstDay = (int) (WeekDay::int($weekStartsAt) ?? $this->getTranslationMessage('first_day_of_week') ?? 0); return ($this->dayOfWeek + 7 - $firstDay) % 7; } /** * Set the day (keeping the current time) to the start of the week + the number of days passed as the first * parameter. First day of week is driven by the locale unless explicitly set with the second parameter. * * @param int $numberOfDays number of days to add after the start of the current week * @param WeekDay|int|null $weekStartsAt optional start allow you to specify the day of week to use to start the week, * if not provided, start of week is inferred from the locale * (Sunday for en_US, Monday for de_DE, etc.) */ public function setDaysFromStartOfWeek(int $numberOfDays, WeekDay|int|null $weekStartsAt = null): static { return $this->addDays($numberOfDays - $this->getDaysFromStartOfWeek(WeekDay::int($weekStartsAt))); } /** * Set any unit to a new value without overflowing current other unit given. * * @param string $valueUnit unit name to modify * @param int $value new value for the input unit * @param string $overflowUnit unit name to not overflow */ public function setUnitNoOverflow(string $valueUnit, int $value, string $overflowUnit): static { try { $start = $this->avoidMutation()->startOf($overflowUnit); $end = $this->avoidMutation()->endOf($overflowUnit); /** @var static $date */ $date = $this->$valueUnit($value); if ($date < $start) { return $date->mutateIfMutable($start); } if ($date > $end) { return $date->mutateIfMutable($end); } return $date; } catch (BadMethodCallException | ReflectionException $exception) { throw new UnknownUnitException($valueUnit, 0, $exception); } } /** * Add any unit to a new value without overflowing current other unit given. * * @param string $valueUnit unit name to modify * @param int $value amount to add to the input unit * @param string $overflowUnit unit name to not overflow */ public function addUnitNoOverflow(string $valueUnit, int $value, string $overflowUnit): static { return $this->setUnitNoOverflow($valueUnit, $this->$valueUnit + $value, $overflowUnit); } /** * Subtract any unit to a new value without overflowing current other unit given. * * @param string $valueUnit unit name to modify * @param int $value amount to subtract to the input unit * @param string $overflowUnit unit name to not overflow */ public function subUnitNoOverflow(string $valueUnit, int $value, string $overflowUnit): static { return $this->setUnitNoOverflow($valueUnit, $this->$valueUnit - $value, $overflowUnit); } /** * Returns the minutes offset to UTC if no arguments passed, else set the timezone with given minutes shift passed. */ public function utcOffset(?int $minuteOffset = null): static|int { if ($minuteOffset === null) { return $this->offsetMinutes; } return $this->setTimezone(CarbonTimeZone::createFromMinuteOffset($minuteOffset)); } /** * Set the date with gregorian year, month and day numbers. * * @see https://php.net/manual/en/datetime.setdate.php */ public function setDate(int $year, int $month, int $day): static { return parent::setDate($year, $month, $day); } /** * Set a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates. * * @see https://php.net/manual/en/datetime.setisodate.php */ public function setISODate(int $year, int $week, int $day = 1): static { return parent::setISODate($year, $week, $day); } /** * Set the date and time all together. */ public function setDateTime( int $year, int $month, int $day, int $hour, int $minute, int $second = 0, int $microseconds = 0, ): static { return $this->setDate($year, $month, $day)->setTime($hour, $minute, $second, $microseconds); } /** * Resets the current time of the DateTime object to a different time. * * @see https://php.net/manual/en/datetime.settime.php */ public function setTime(int $hour, int $minute, int $second = 0, int $microseconds = 0): static { return parent::setTime($hour, $minute, $second, $microseconds); } /** * Set the instance's timestamp. * * Timestamp input can be given as int, float or a string containing one or more numbers. */ public function setTimestamp(float|int|string $timestamp): static { [$seconds, $microseconds] = self::getIntegerAndDecimalParts($timestamp); return parent::setTimestamp((int) $seconds)->setMicroseconds((int) $microseconds); } /** * Set the time by time string. */ public function setTimeFromTimeString(string $time): static { if (!str_contains($time, ':')) { $time .= ':0'; } return $this->modify($time); } /** * @alias setTimezone */ public function timezone(DateTimeZone|string|int $value): static { return $this->setTimezone($value); } /** * Set the timezone or returns the timezone name if no arguments passed. * * @return ($value is null ? string : static) */ public function tz(DateTimeZone|string|int|null $value = null): static|string { if ($value === null) { return $this->tzName; } return $this->setTimezone($value); } /** * Set the instance's timezone from a string or object. */ public function setTimezone(DateTimeZone|string|int $timeZone): static { return parent::setTimezone(static::safeCreateDateTimeZone($timeZone)); } /** * Set the instance's timezone from a string or object and add/subtract the offset difference. */ public function shiftTimezone(DateTimeZone|string $value): static { $dateTimeString = $this->format('Y-m-d H:i:s.u'); return $this ->setTimezone($value) ->modify($dateTimeString); } /** * Set the instance's timezone to UTC. */ public function utc(): static { return $this->setTimezone('UTC'); } /** * Set the year, month, and date for this instance to that of the passed instance. */ public function setDateFrom(DateTimeInterface|string $date): static { $date = $this->resolveCarbon($date); return $this->setDate($date->year, $date->month, $date->day); } /** * Set the hour, minute, second and microseconds for this instance to that of the passed instance. */ public function setTimeFrom(DateTimeInterface|string $date): static { $date = $this->resolveCarbon($date); return $this->setTime($date->hour, $date->minute, $date->second, $date->microsecond); } /** * Set the date and time for this instance to that of the passed instance. */ public function setDateTimeFrom(DateTimeInterface|string $date): static { $date = $this->resolveCarbon($date); return $this->modify($date->rawFormat('Y-m-d H:i:s.u')); } /** * Get the days of the week. */ public static function getDays(): array { return static::$days; } /////////////////////////////////////////////////////////////////// /////////////////////// WEEK SPECIAL DAYS ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Get the first day of week. * * @return int */ public static function getWeekStartsAt(?string $locale = null): int { return (int) static::getTranslationMessageWith( $locale ? Translator::get($locale) : static::getTranslator(), 'first_day_of_week', ); } /** * Get the last day of week. * * @param string $locale local to consider the last day of week. * * @return int */ public static function getWeekEndsAt(?string $locale = null): int { return static::weekRotate(static::getWeekStartsAt($locale), -1); } /** * Get weekend days */ public static function getWeekendDays(): array { return FactoryImmutable::getInstance()->getWeekendDays(); } /** * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. * You should rather consider week-end is always saturday and sunday, and if you have some custom * week-end days to handle, give to those days an other name and create a macro for them: * * ``` * Carbon::macro('isDayOff', function ($date) { * return $date->isSunday() || $date->isMonday(); * }); * Carbon::macro('isNotDayOff', function ($date) { * return !$date->isDayOff(); * }); * if ($someDate->isDayOff()) ... * if ($someDate->isNotDayOff()) ... * // Add 5 not-off days * $count = 5; * while ($someDate->isDayOff() || ($count-- > 0)) { * $someDate->addDay(); * } * ``` * * Set weekend days */ public static function setWeekendDays(array $days): void { FactoryImmutable::getDefaultInstance()->setWeekendDays($days); } /** * Determine if a time string will produce a relative date. * * @return bool true if time match a relative date, false if absolute or invalid time string */ public static function hasRelativeKeywords(?string $time): bool { if (!$time || strtotime($time) === false) { return false; } $date1 = new DateTime('2000-01-01T00:00:00Z'); $date1->modify($time); $date2 = new DateTime('2001-12-25T00:00:00Z'); $date2->modify($time); return $date1 != $date2; } /////////////////////////////////////////////////////////////////// /////////////////////// STRING FORMATTING ///////////////////////// /////////////////////////////////////////////////////////////////// /** * Returns list of locale formats for ISO formatting. * * @param string|null $locale current locale used if null */ public function getIsoFormats(?string $locale = null): array { return [ 'LT' => $this->getTranslationMessage('formats.LT', $locale), 'LTS' => $this->getTranslationMessage('formats.LTS', $locale), 'L' => $this->getTranslationMessage('formats.L', $locale), 'LL' => $this->getTranslationMessage('formats.LL', $locale), 'LLL' => $this->getTranslationMessage('formats.LLL', $locale), 'LLLL' => $this->getTranslationMessage('formats.LLLL', $locale), 'l' => $this->getTranslationMessage('formats.l', $locale), 'll' => $this->getTranslationMessage('formats.ll', $locale), 'lll' => $this->getTranslationMessage('formats.lll', $locale), 'llll' => $this->getTranslationMessage('formats.llll', $locale), ]; } /** * Returns list of calendar formats for ISO formatting. * * @param string|null $locale current locale used if null */ public function getCalendarFormats(?string $locale = null): array { return [ 'sameDay' => $this->getTranslationMessage('calendar.sameDay', $locale, '[Today at] LT'), 'nextDay' => $this->getTranslationMessage('calendar.nextDay', $locale, '[Tomorrow at] LT'), 'nextWeek' => $this->getTranslationMessage('calendar.nextWeek', $locale, 'dddd [at] LT'), 'lastDay' => $this->getTranslationMessage('calendar.lastDay', $locale, '[Yesterday at] LT'), 'lastWeek' => $this->getTranslationMessage('calendar.lastWeek', $locale, '[Last] dddd [at] LT'), 'sameElse' => $this->getTranslationMessage('calendar.sameElse', $locale, 'L'), ]; } /** * Returns list of locale units for ISO formatting. */ public static function getIsoUnits(): array { static $units = null; $units ??= [ 'OD' => ['getAltNumber', ['day']], 'OM' => ['getAltNumber', ['month']], 'OY' => ['getAltNumber', ['year']], 'OH' => ['getAltNumber', ['hour']], 'Oh' => ['getAltNumber', ['h']], 'Om' => ['getAltNumber', ['minute']], 'Os' => ['getAltNumber', ['second']], 'D' => 'day', 'DD' => ['rawFormat', ['d']], 'Do' => ['ordinal', ['day', 'D']], 'd' => 'dayOfWeek', 'dd' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedMinDayName( $originalFormat, ), 'ddd' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedShortDayName( $originalFormat, ), 'dddd' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedDayName( $originalFormat, ), 'DDD' => 'dayOfYear', 'DDDD' => ['getPaddedUnit', ['dayOfYear', 3]], 'DDDo' => ['ordinal', ['dayOfYear', 'DDD']], 'e' => ['weekday', []], 'E' => 'dayOfWeekIso', 'H' => ['rawFormat', ['G']], 'HH' => ['rawFormat', ['H']], 'h' => ['rawFormat', ['g']], 'hh' => ['rawFormat', ['h']], 'k' => 'noZeroHour', 'kk' => ['getPaddedUnit', ['noZeroHour']], 'hmm' => ['rawFormat', ['gi']], 'hmmss' => ['rawFormat', ['gis']], 'Hmm' => ['rawFormat', ['Gi']], 'Hmmss' => ['rawFormat', ['Gis']], 'm' => 'minute', 'mm' => ['rawFormat', ['i']], 'a' => 'meridiem', 'A' => 'upperMeridiem', 's' => 'second', 'ss' => ['getPaddedUnit', ['second']], 'S' => static fn (CarbonInterface $date) => (string) floor($date->micro / 100000), 'SS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 10000, 2), 'SSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 1000, 3), 'SSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 100, 4), 'SSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro / 10, 5), 'SSSSSS' => ['getPaddedUnit', ['micro', 6]], 'SSSSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro * 10, 7), 'SSSSSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro * 100, 8), 'SSSSSSSSS' => static fn (CarbonInterface $date) => self::floorZeroPad($date->micro * 1000, 9), 'M' => 'month', 'MM' => ['rawFormat', ['m']], 'MMM' => static function (CarbonInterface $date, $originalFormat = null) { $month = $date->getTranslatedShortMonthName($originalFormat); $suffix = $date->getTranslationMessage('mmm_suffix'); if ($suffix && $month !== $date->monthName) { $month .= $suffix; } return $month; }, 'MMMM' => static fn (CarbonInterface $date, $originalFormat = null) => $date->getTranslatedMonthName( $originalFormat, ), 'Mo' => ['ordinal', ['month', 'M']], 'Q' => 'quarter', 'Qo' => ['ordinal', ['quarter', 'M']], 'G' => 'isoWeekYear', 'GG' => ['getPaddedUnit', ['isoWeekYear']], 'GGG' => ['getPaddedUnit', ['isoWeekYear', 3]], 'GGGG' => ['getPaddedUnit', ['isoWeekYear', 4]], 'GGGGG' => ['getPaddedUnit', ['isoWeekYear', 5]], 'g' => 'weekYear', 'gg' => ['getPaddedUnit', ['weekYear']], 'ggg' => ['getPaddedUnit', ['weekYear', 3]], 'gggg' => ['getPaddedUnit', ['weekYear', 4]], 'ggggg' => ['getPaddedUnit', ['weekYear', 5]], 'W' => 'isoWeek', 'WW' => ['getPaddedUnit', ['isoWeek']], 'Wo' => ['ordinal', ['isoWeek', 'W']], 'w' => 'week', 'ww' => ['getPaddedUnit', ['week']], 'wo' => ['ordinal', ['week', 'w']], 'x' => ['valueOf', []], 'X' => 'timestamp', 'Y' => 'year', 'YY' => ['rawFormat', ['y']], 'YYYY' => ['getPaddedUnit', ['year', 4]], 'YYYYY' => ['getPaddedUnit', ['year', 5]], 'YYYYYY' => static fn (CarbonInterface $date) => ($date->year < 0 ? '' : '+'). $date->getPaddedUnit('year', 6), 'z' => ['rawFormat', ['T']], 'zz' => 'tzName', 'Z' => ['getOffsetString', []], 'ZZ' => ['getOffsetString', ['']], ]; return $units; } /** * Returns a unit of the instance padded with 0 by default or any other string if specified. * * @param string $unit Carbon unit name * @param int $length Length of the output (2 by default) * @param string $padString String to use for padding ("0" by default) * @param int $padType Side(s) to pad (STR_PAD_LEFT by default) */ public function getPaddedUnit($unit, $length = 2, $padString = '0', $padType = STR_PAD_LEFT): string { return ($this->$unit < 0 ? '-' : '').str_pad((string) abs($this->$unit), $length, $padString, $padType); } /** * Return a property with its ordinal. */ public function ordinal(string $key, ?string $period = null): string { $number = $this->$key; $result = $this->translate('ordinal', [ ':number' => $number, ':period' => (string) $period, ]); return (string) ($result === 'ordinal' ? $number : $result); } /** * Return the meridiem of the current time in the current locale. * * @param bool $isLower if true, returns lowercase variant if available in the current locale. */ public function meridiem(bool $isLower = false): string { $hour = $this->hour; $index = $hour < static::HOURS_PER_DAY / 2 ? 0 : 1; if ($isLower) { $key = 'meridiem.'.($index + 2); $result = $this->translate($key); if ($result !== $key) { return $result; } } $key = "meridiem.$index"; $result = $this->translate($key); if ($result === $key) { $result = $this->translate('meridiem', [ ':hour' => $this->hour, ':minute' => $this->minute, ':isLower' => $isLower, ]); if ($result === 'meridiem') { return $isLower ? $this->latinMeridiem : $this->latinUpperMeridiem; } } elseif ($isLower) { $result = mb_strtolower($result); } return $result; } /** * Returns the alternative number for a given date property if available in the current locale. * * @param string $key date property */ public function getAltNumber(string $key): string { return $this->translateNumber((int) (\strlen($key) > 1 ? $this->$key : $this->rawFormat($key))); } /** * Format in the current language using ISO replacement patterns. * * @param string|null $originalFormat provide context if a chunk has been passed alone */ public function isoFormat(string $format, ?string $originalFormat = null): string { $result = ''; $length = mb_strlen($format); $originalFormat ??= $format; $inEscaped = false; $formats = null; $units = null; for ($i = 0; $i < $length; $i++) { $char = mb_substr($format, $i, 1); if ($char === '\\') { $result .= mb_substr($format, ++$i, 1); continue; } if ($char === '[' && !$inEscaped) { $inEscaped = true; continue; } if ($char === ']' && $inEscaped) { $inEscaped = false; continue; } if ($inEscaped) { $result .= $char; continue; } $input = mb_substr($format, $i); if (preg_match('/^(LTS|LT|l{1,4}|L{1,4})/', $input, $match)) { if ($formats === null) { $formats = $this->getIsoFormats(); } $code = $match[0]; $sequence = $formats[$code] ?? preg_replace_callback( '/MMMM|MM|DD|dddd/', static fn ($code) => mb_substr($code[0], 1), $formats[strtoupper($code)] ?? '', ); $rest = mb_substr($format, $i + mb_strlen($code)); $format = mb_substr($format, 0, $i).$sequence.$rest; $length = mb_strlen($format); $input = $sequence.$rest; } if (preg_match('/^'.CarbonInterface::ISO_FORMAT_REGEXP.'/', $input, $match)) { $code = $match[0]; if ($units === null) { $units = static::getIsoUnits(); } $sequence = $units[$code] ?? ''; if ($sequence instanceof Closure) { $sequence = $sequence($this, $originalFormat); } elseif (\is_array($sequence)) { try { $sequence = $this->{$sequence[0]}(...$sequence[1]); } catch (ReflectionException | InvalidArgumentException | BadMethodCallException) { $sequence = ''; } } elseif (\is_string($sequence)) { $sequence = $this->$sequence ?? $code; } $format = mb_substr($format, 0, $i).$sequence.mb_substr($format, $i + mb_strlen($code)); $i += mb_strlen((string) $sequence) - 1; $length = mb_strlen($format); $char = $sequence; } $result .= $char; } return $result; } /** * List of replacements from date() format to isoFormat(). */ public static function getFormatsToIsoReplacements(): array { static $replacements = null; $replacements ??= [ 'd' => true, 'D' => 'ddd', 'j' => true, 'l' => 'dddd', 'N' => true, 'S' => static fn ($date) => str_replace((string) $date->rawFormat('j'), '', $date->isoFormat('Do')), 'w' => true, 'z' => true, 'W' => true, 'F' => 'MMMM', 'm' => true, 'M' => 'MMM', 'n' => true, 't' => true, 'L' => true, 'o' => true, 'Y' => true, 'y' => true, 'a' => 'a', 'A' => 'A', 'B' => true, 'g' => true, 'G' => true, 'h' => true, 'H' => true, 'i' => true, 's' => true, 'u' => true, 'v' => true, 'E' => true, 'I' => true, 'O' => true, 'P' => true, 'Z' => true, 'c' => true, 'r' => true, 'U' => true, 'T' => true, ]; return $replacements; } /** * Format as ->format() do (using date replacements patterns from https://php.net/manual/en/function.date.php) * but translate words whenever possible (months, day names, etc.) using the current locale. */ public function translatedFormat(string $format): string { $replacements = static::getFormatsToIsoReplacements(); $context = ''; $isoFormat = ''; $length = mb_strlen($format); for ($i = 0; $i < $length; $i++) { $char = mb_substr($format, $i, 1); if ($char === '\\') { $replacement = mb_substr($format, $i, 2); $isoFormat .= $replacement; $i++; continue; } if (!isset($replacements[$char])) { $replacement = preg_match('/^[A-Za-z]$/', $char) ? "\\$char" : $char; $isoFormat .= $replacement; $context .= $replacement; continue; } $replacement = $replacements[$char]; if ($replacement === true) { static $contextReplacements = null; if ($contextReplacements === null) { $contextReplacements = [ 'm' => 'MM', 'd' => 'DD', 't' => 'D', 'j' => 'D', 'N' => 'e', 'w' => 'e', 'n' => 'M', 'o' => 'YYYY', 'Y' => 'YYYY', 'y' => 'YY', 'g' => 'h', 'G' => 'H', 'h' => 'hh', 'H' => 'HH', 'i' => 'mm', 's' => 'ss', ]; } $isoFormat .= '['.$this->rawFormat($char).']'; $context .= $contextReplacements[$char] ?? ' '; continue; } if ($replacement instanceof Closure) { $replacement = '['.$replacement($this).']'; $isoFormat .= $replacement; $context .= $replacement; continue; } $isoFormat .= $replacement; $context .= $replacement; } return $this->isoFormat($isoFormat, $context); } /** * Returns the offset hour and minute formatted with +/- and a given separator (":" by default). * For example, if the time zone is 9 hours 30 minutes, you'll get "+09:30", with "@@" as first * argument, "+09@@30", with "" as first argument, "+0930". Negative offset will return something * like "-12:00". * * @param string $separator string to place between hours and minutes (":" by default) */ public function getOffsetString(string $separator = ':'): string { $second = $this->getOffset(); $symbol = $second < 0 ? '-' : '+'; $minute = abs($second) / static::SECONDS_PER_MINUTE; $hour = self::floorZeroPad($minute / static::MINUTES_PER_HOUR, 2); $minute = self::floorZeroPad(((int) $minute) % static::MINUTES_PER_HOUR, 2); return "$symbol$hour$separator$minute"; } /** * Dynamically handle calls to the class. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws BadMethodCallException */ public static function __callStatic(string $method, array $parameters): mixed { if (!static::hasMacro($method)) { foreach (static::getGenericMacros() as $callback) { try { return static::executeStaticCallable($callback, $method, ...$parameters); } catch (BadMethodCallException) { continue; } } if (static::isStrictModeEnabled()) { throw new UnknownMethodException(\sprintf('%s::%s', static::class, $method)); } return null; } return static::executeStaticCallable(static::getMacro($method), ...$parameters); } /** * Set specified unit to new given value. * * @param string $unit year, month, day, hour, minute, second or microsecond * @param Month|int $value new value for given unit */ public function setUnit(string $unit, Month|int|float|null $value = null): static { if (\is_float($value)) { $int = (int) $value; if ((float) $int !== $value) { throw new InvalidArgumentException( "$unit cannot be changed to float value $value, integer expected", ); } $value = $int; } $unit = static::singularUnit($unit); $value = self::monthToInt($value, $unit); $dateUnits = ['year', 'month', 'day']; if (\in_array($unit, $dateUnits)) { return $this->setDate(...array_map( fn ($name) => (int) ($name === $unit ? $value : $this->$name), $dateUnits, )); } $units = ['hour', 'minute', 'second', 'micro']; if ($unit === 'millisecond' || $unit === 'milli') { $value *= 1000; $unit = 'micro'; } elseif ($unit === 'microsecond') { $unit = 'micro'; } return $this->setTime(...array_map( fn ($name) => (int) ($name === $unit ? $value : $this->$name), $units, )); } /** * Returns standardized singular of a given singular/plural unit name (in English). */ public static function singularUnit(string $unit): string { $unit = rtrim(mb_strtolower($unit), 's'); return match ($unit) { 'centurie' => 'century', 'millennia' => 'millennium', default => $unit, }; } /** * Returns standardized plural of a given singular/plural unit name (in English). */ public static function pluralUnit(string $unit): string { $unit = rtrim(strtolower($unit), 's'); return match ($unit) { 'century' => 'centuries', 'millennium', 'millennia' => 'millennia', default => "{$unit}s", }; } public static function sleep(int|float $seconds): void { if (static::hasTestNow()) { static::setTestNow(static::getTestNow()->avoidMutation()->addSeconds($seconds)); return; } (new NativeClock('UTC'))->sleep($seconds); } /** * Dynamically handle calls to the class. * * @param string $method magic method name called * @param array $parameters parameters list * * @throws UnknownMethodException|BadMethodCallException|ReflectionException|Throwable */ public function __call(string $method, array $parameters): mixed { $unit = rtrim($method, 's'); return $this->callDiffAlias($unit, $parameters) ?? $this->callHumanDiffAlias($unit, $parameters) ?? $this->callRoundMethod($unit, $parameters) ?? $this->callIsMethod($unit, $parameters) ?? $this->callModifierMethod($unit, $parameters) ?? $this->callPeriodMethod($method, $parameters) ?? $this->callGetOrSetMethod($method, $parameters) ?? $this->callMacroMethod($method, $parameters); } /** * Return the Carbon instance passed through, a now instance in the same timezone * if null given or parse the input if string given. */ protected function resolveCarbon(DateTimeInterface|string|null $date): self { if (!$date) { return $this->nowWithSameTz(); } if (\is_string($date)) { return $this->transmitFactory(fn () => static::parse($date, $this->getTimezone())); } return $date instanceof self ? $date : $this->transmitFactory(static fn () => static::instance($date)); } protected static function weekRotate(int $day, int $rotation): int { return (static::DAYS_PER_WEEK + $rotation % static::DAYS_PER_WEEK + $day) % static::DAYS_PER_WEEK; } protected function executeCallable(callable $macro, ...$parameters) { if ($macro instanceof Closure) { $boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class); return \call_user_func_array($boundMacro ?: $macro, $parameters); } return \call_user_func_array($macro, $parameters); } protected function executeCallableWithContext(callable $macro, ...$parameters) { return static::bindMacroContext($this, function () use (&$macro, &$parameters) { return $this->executeCallable($macro, ...$parameters); }); } protected function getAllGenericMacros(): Generator { yield from $this->localGenericMacros ?? []; yield from $this->transmitFactory(static fn () => static::getGenericMacros()); } protected static function getGenericMacros(): Generator { foreach ((FactoryImmutable::getInstance()->getSettings()['genericMacros'] ?? []) as $list) { foreach ($list as $macro) { yield $macro; } } } protected static function executeStaticCallable(callable $macro, ...$parameters) { return static::bindMacroContext(null, function () use (&$macro, &$parameters) { if ($macro instanceof Closure) { $boundMacro = @Closure::bind($macro, null, static::class); return \call_user_func_array($boundMacro ?: $macro, $parameters); } return \call_user_func_array($macro, $parameters); }); } protected function getTranslatedFormByRegExp($baseKey, $keySuffix, $context, $subKey, $defaultValue) { $key = $baseKey.$keySuffix; $standaloneKey = $key.'_standalone'; $baseTranslation = $this->getTranslationMessage($key); if ($baseTranslation instanceof Closure) { return $baseTranslation($this, $context, $subKey) ?: $defaultValue; } if ( $this->getTranslationMessage("$standaloneKey.$subKey") && (!$context || (($regExp = $this->getTranslationMessage($baseKey.'_regexp')) && !preg_match($regExp, $context))) ) { $key = $standaloneKey; } return $this->getTranslationMessage("$key.$subKey", null, $defaultValue); } private function callGetOrSetMethod(string $method, array $parameters): mixed { if (preg_match('/^([a-z]{2,})(In|Of)([A-Z][a-z]+)$/', $method)) { $localStrictModeEnabled = $this->localStrictModeEnabled; $this->localStrictModeEnabled = true; try { return $this->callGetOrSet($method, $parameters[0] ?? null); } catch (UnknownGetterException|UnknownSetterException|ImmutableException) { // continue to macro } finally { $this->localStrictModeEnabled = $localStrictModeEnabled; } } return null; } private function callGetOrSet(string $name, mixed $value): mixed { if ($value !== null) { if (\is_string($value) || \is_int($value) || \is_float($value) || $value instanceof DateTimeZone || $value instanceof Month) { return $this->set($name, $value); } return null; } return $this->get($name); } private function getUTCUnit(string $unit): ?string { if (str_starts_with($unit, 'Real')) { return substr($unit, 4); } if (str_starts_with($unit, 'UTC')) { return substr($unit, 3); } return null; } private function callDiffAlias(string $method, array $parameters): mixed { if (preg_match('/^(diff|floatDiff)In(Real|UTC|Utc)?(.+)$/', $method, $match)) { $mode = strtoupper($match[2] ?? ''); $betterMethod = $match[1] === 'floatDiff' ? str_replace('floatDiff', 'diff', $method) : null; if ($mode === 'REAL') { $mode = 'UTC'; $betterMethod = str_replace($match[2], 'UTC', $betterMethod ?? $method); } if ($betterMethod) { @trigger_error( "Use the method $betterMethod instead to make it more explicit about what it does.\n". 'On next major version, "float" prefix will be removed (as all diff are now returning floating numbers)'. ' and "Real" methods will be removed in favor of "UTC" because what it actually does is to convert both'. ' dates to UTC timezone before comparison, while by default it does it only if both dates don\'t have'. ' exactly the same timezone (Note: 2 timezones with the same offset but different names are considered'. " different as it's not safe to assume they will always have the same offset).", \E_USER_DEPRECATED, ); } $unit = self::pluralUnit($match[3]); $diffMethod = 'diffIn'.ucfirst($unit); if (\in_array($unit, ['days', 'weeks', 'months', 'quarters', 'years'])) { $parameters['utc'] = ($mode === 'UTC'); } if (method_exists($this, $diffMethod)) { return $this->$diffMethod(...$parameters); } } return null; } private function callHumanDiffAlias(string $method, array $parameters): ?string { $diffSizes = [ // @mode diffForHumans 'short' => true, // @mode diffForHumans 'long' => false, ]; $diffSyntaxModes = [ // @call diffForHumans 'Absolute' => CarbonInterface::DIFF_ABSOLUTE, // @call diffForHumans 'Relative' => CarbonInterface::DIFF_RELATIVE_AUTO, // @call diffForHumans 'RelativeToNow' => CarbonInterface::DIFF_RELATIVE_TO_NOW, // @call diffForHumans 'RelativeToOther' => CarbonInterface::DIFF_RELATIVE_TO_OTHER, ]; $sizePattern = implode('|', array_keys($diffSizes)); $syntaxPattern = implode('|', array_keys($diffSyntaxModes)); if (preg_match("/^(?<size>$sizePattern)(?<syntax>$syntaxPattern)DiffForHuman$/", $method, $match)) { $dates = array_filter($parameters, function ($parameter) { return $parameter instanceof DateTimeInterface; }); $other = null; if (\count($dates)) { $key = key($dates); $other = current($dates); array_splice($parameters, $key, 1); } return $this->diffForHumans($other, $diffSyntaxModes[$match['syntax']], $diffSizes[$match['size']], ...$parameters); } return null; } private function callIsMethod(string $unit, array $parameters): ?bool { if (!str_starts_with($unit, 'is')) { return null; } $word = substr($unit, 2); if (\in_array($word, static::$days, true)) { return $this->isDayOfWeek($word); } return match ($word) { // @call is Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.) 'Utc', 'UTC' => $this->utc, // @call is Check if the current instance has non-UTC timezone. 'Local' => $this->local, // @call is Check if the current instance is a valid date. 'Valid' => $this->year !== 0, // @call is Check if the current instance is in a daylight saving time. 'DST' => $this->dst, default => $this->callComparatorMethod($word, $parameters), }; } private function callComparatorMethod(string $unit, array $parameters): ?bool { $start = substr($unit, 0, 4); $factor = -1; if ($start === 'Last') { $start = 'Next'; $factor = 1; } if ($start === 'Next') { $lowerUnit = strtolower(substr($unit, 4)); if (static::isModifiableUnit($lowerUnit)) { return $this->avoidMutation()->addUnit($lowerUnit, $factor, false)->isSameUnit($lowerUnit, ...($parameters ?: ['now'])); } } if ($start === 'Same') { try { return $this->isSameUnit(strtolower(substr($unit, 4)), ...$parameters); } catch (BadComparisonUnitException) { // Try next } } if (str_starts_with($unit, 'Current')) { try { return $this->isCurrentUnit(strtolower(substr($unit, 7))); } catch (BadComparisonUnitException | BadMethodCallException) { // Try next } } return null; } private function callModifierMethod(string $unit, array $parameters): ?static { $action = substr($unit, 0, 3); $overflow = null; if ($action === 'set') { $unit = strtolower(substr($unit, 3)); } if (\in_array($unit, static::$units, true)) { return $this->setUnit($unit, ...$parameters); } if ($action === 'add' || $action === 'sub') { $unit = substr($unit, 3); $utcUnit = $this->getUTCUnit($unit); if ($utcUnit) { $unit = static::singularUnit($utcUnit); return $this->{"{$action}UTCUnit"}($unit, ...$parameters); } if (preg_match('/^(Month|Quarter|Year|Decade|Century|Centurie|Millennium|Millennia)s?(No|With|Without|WithNo)Overflow$/', $unit, $match)) { $unit = $match[1]; $overflow = $match[2] === 'With'; } $unit = static::singularUnit($unit); } if (static::isModifiableUnit($unit)) { return $this->{"{$action}Unit"}($unit, $this->getMagicParameter($parameters, 0, 'value', 1), $overflow); } return null; } private function callPeriodMethod(string $method, array $parameters): ?CarbonPeriod { if (str_ends_with($method, 'Until')) { try { $unit = static::singularUnit(substr($method, 0, -5)); return $this->range( $this->getMagicParameter($parameters, 0, 'endDate', $this), $this->getMagicParameter($parameters, 1, 'factor', 1), $unit ); } catch (InvalidArgumentException) { // Try macros } } return null; } private function callMacroMethod(string $method, array $parameters): mixed { return static::bindMacroContext($this, function () use (&$method, &$parameters) { $macro = $this->getLocalMacro($method); if (!$macro) { foreach ($this->getAllGenericMacros() as $callback) { try { return $this->executeCallable($callback, $method, ...$parameters); } catch (BadMethodCallException) { continue; } } if ($this->isLocalStrictModeEnabled()) { throw new UnknownMethodException($method); } return null; } return $this->executeCallable($macro, ...$parameters); }); } private static function floorZeroPad(int|float $value, int $length): string { return str_pad((string) floor($value), $length, '0', STR_PAD_LEFT); } /** * @template T of CarbonInterface * * @param T $date * * @return T */ private function mutateIfMutable(CarbonInterface $date): CarbonInterface { return $this instanceof DateTimeImmutable ? $date : $this->modify('@'.$date->rawFormat('U.u'))->setTimezone($date->getTimezone()); } }
PHP
{ "end_line": 2445, "name": "translatedFormat", "signature": "public function translatedFormat(string $format): string", "start_line": 2374 }
{ "class_name": "Date", "class_signature": "trait Date", "namespace": "Carbon\\Traits" }
diffInYears
Carbon/src/Carbon/Traits/Difference.php
public function diffInYears($date = null, bool $absolute = false, bool $utc = false): float { $start = $this; $end = $this->resolveCarbon($date); if ($utc) { $start = $start->avoidMutation()->utc(); $end = $end->avoidMutation()->utc(); } $ascending = ($start <= $end); $sign = $absolute || $ascending ? 1 : -1; if (!$ascending) { [$start, $end] = [$end, $start]; } $yearsDiff = (int) $start->diff($end, $absolute)->format('%r%y'); /** @var Carbon|CarbonImmutable $floorEnd */ $floorEnd = $start->avoidMutation()->addYears($yearsDiff); if ($floorEnd >= $end) { return $sign * $yearsDiff; } /** @var Carbon|CarbonImmutable $ceilEnd */ $ceilEnd = $start->avoidMutation()->addYears($yearsDiff + 1); $daysToFloor = $floorEnd->diffInDays($end); $daysToCeil = $end->diffInDays($ceilEnd); return $sign * ($yearsDiff + $daysToFloor / ($daysToCeil + $daysToFloor)); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Carbon\Exceptions\UnknownUnitException; use Carbon\Unit; use Closure; use DateInterval; use DateTimeInterface; /** * Trait Difference. * * Depends on the following methods: * * @method bool lessThan($date) * @method static copy() * @method static resolveCarbon($date = null) */ trait Difference { /** * Get the difference as a DateInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return DateInterval */ public function diffAsDateInterval($date = null, bool $absolute = false): DateInterval { $other = $this->resolveCarbon($date); // Work-around for https://bugs.php.net/bug.php?id=81458 // It was initially introduced for https://bugs.php.net/bug.php?id=80998 // The very specific case of 80998 was fixed in PHP 8.1beta3, but it introduced 81458 // So we still need to keep this for now if ($other->tz !== $this->tz) { $other = $other->avoidMutation()->setTimezone($this->tz); } return parent::diff($other, $absolute); } /** * Get the difference as a CarbonInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return CarbonInterval */ public function diffAsCarbonInterval($date = null, bool $absolute = false, array $skip = []): CarbonInterval { return CarbonInterval::diff($this, $this->resolveCarbon($date), $absolute, $skip) ->setLocalTranslator($this->getLocalTranslator()); } /** * @alias diffAsCarbonInterval * * Get the difference as a DateInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return CarbonInterval */ public function diff($date = null, bool $absolute = false, array $skip = []): CarbonInterval { return $this->diffAsCarbonInterval($date, $absolute, $skip); } /** * @param Unit|string $unit microsecond, millisecond, second, minute, * hour, day, week, month, quarter, year, * century, millennium * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInUnit(Unit|string $unit, $date = null, bool $absolute = false, bool $utc = false): float { $unit = static::pluralUnit($unit instanceof Unit ? $unit->value : rtrim($unit, 'z')); $method = 'diffIn'.$unit; if (!method_exists($this, $method)) { throw new UnknownUnitException($unit); } return $this->$method($date, $absolute, $utc); } /** * Get the difference in years * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInYears($date = null, bool $absolute = false, bool $utc = false): float { $start = $this; $end = $this->resolveCarbon($date); if ($utc) { $start = $start->avoidMutation()->utc(); $end = $end->avoidMutation()->utc(); } $ascending = ($start <= $end); $sign = $absolute || $ascending ? 1 : -1; if (!$ascending) { [$start, $end] = [$end, $start]; } $yearsDiff = (int) $start->diff($end, $absolute)->format('%r%y'); /** @var Carbon|CarbonImmutable $floorEnd */ $floorEnd = $start->avoidMutation()->addYears($yearsDiff); if ($floorEnd >= $end) { return $sign * $yearsDiff; } /** @var Carbon|CarbonImmutable $ceilEnd */ $ceilEnd = $start->avoidMutation()->addYears($yearsDiff + 1); $daysToFloor = $floorEnd->diffInDays($end); $daysToCeil = $end->diffInDays($ceilEnd); return $sign * ($yearsDiff + $daysToFloor / ($daysToCeil + $daysToFloor)); } /** * Get the difference in quarters. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInQuarters($date = null, bool $absolute = false, bool $utc = false): float { return $this->diffInMonths($date, $absolute, $utc) / static::MONTHS_PER_QUARTER; } /** * Get the difference in months. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInMonths($date = null, bool $absolute = false, bool $utc = false): float { $start = $this; $end = $this->resolveCarbon($date); // Compare using UTC if ($utc || ($end->timezoneName !== $start->timezoneName)) { $start = $start->avoidMutation()->utc(); $end = $end->avoidMutation()->utc(); } [$yearStart, $monthStart, $dayStart] = explode('-', $start->format('Y-m-dHisu')); [$yearEnd, $monthEnd, $dayEnd] = explode('-', $end->format('Y-m-dHisu')); $monthsDiff = (((int) $yearEnd) - ((int) $yearStart)) * static::MONTHS_PER_YEAR + ((int) $monthEnd) - ((int) $monthStart); if ($monthsDiff > 0) { $monthsDiff -= ($dayStart > $dayEnd ? 1 : 0); } elseif ($monthsDiff < 0) { $monthsDiff += ($dayStart < $dayEnd ? 1 : 0); } $ascending = ($start <= $end); $sign = $absolute || $ascending ? 1 : -1; $monthsDiff = abs($monthsDiff); if (!$ascending) { [$start, $end] = [$end, $start]; } /** @var Carbon|CarbonImmutable $floorEnd */ $floorEnd = $start->avoidMutation()->addMonths($monthsDiff); if ($floorEnd >= $end) { return $sign * $monthsDiff; } /** @var Carbon|CarbonImmutable $ceilEnd */ $ceilEnd = $start->avoidMutation()->addMonths($monthsDiff + 1); $daysToFloor = $floorEnd->diffInDays($end); $daysToCeil = $end->diffInDays($ceilEnd); return $sign * ($monthsDiff + $daysToFloor / ($daysToCeil + $daysToFloor)); } /** * Get the difference in weeks. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInWeeks($date = null, bool $absolute = false, bool $utc = false): float { return $this->diffInDays($date, $absolute, $utc) / static::DAYS_PER_WEEK; } /** * Get the difference in days. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInDays($date = null, bool $absolute = false, bool $utc = false): float { $date = $this->resolveCarbon($date); $current = $this; // Compare using UTC if ($utc || ($date->timezoneName !== $current->timezoneName)) { $date = $date->avoidMutation()->utc(); $current = $current->avoidMutation()->utc(); } $negative = ($date < $current); [$start, $end] = $negative ? [$date, $current] : [$current, $date]; $interval = $start->diffAsDateInterval($end); $daysA = $this->getIntervalDayDiff($interval); $floorEnd = $start->avoidMutation()->addDays($daysA); $daysB = $daysA + ($floorEnd <= $end ? 1 : -1); $ceilEnd = $start->avoidMutation()->addDays($daysB); $microsecondsBetween = $floorEnd->diffInMicroseconds($ceilEnd); $microsecondsToEnd = $floorEnd->diffInMicroseconds($end); return ($negative && !$absolute ? -1 : 1) * ($daysA * ($microsecondsBetween - $microsecondsToEnd) + $daysB * $microsecondsToEnd) / $microsecondsBetween; } /** * Get the difference in days using a filter closure. * * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInDaysFiltered(Closure $callback, $date = null, bool $absolute = false): int { return $this->diffFiltered(CarbonInterval::day(), $callback, $date, $absolute); } /** * Get the difference in hours using a filter closure. * * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInHoursFiltered(Closure $callback, $date = null, bool $absolute = false): int { return $this->diffFiltered(CarbonInterval::hour(), $callback, $date, $absolute); } /** * Get the difference by the given interval using a filter closure. * * @param CarbonInterval $ci An interval to traverse by * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffFiltered(CarbonInterval $ci, Closure $callback, $date = null, bool $absolute = false): int { $start = $this; $end = $this->resolveCarbon($date); $inverse = false; if ($end < $start) { $start = $end; $end = $this; $inverse = true; } $options = CarbonPeriod::EXCLUDE_END_DATE | ($this->isMutable() ? 0 : CarbonPeriod::IMMUTABLE); $diff = $ci->toPeriod($start, $end, $options)->filter($callback)->count(); return $inverse && !$absolute ? -$diff : $diff; } /** * Get the difference in weekdays. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInWeekdays($date = null, bool $absolute = false): int { return $this->diffInDaysFiltered( static fn (CarbonInterface $date) => $date->isWeekday(), $this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')), $absolute, ); } /** * Get the difference in weekend days using a filter. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInWeekendDays($date = null, bool $absolute = false): int { return $this->diffInDaysFiltered( static fn (CarbonInterface $date) => $date->isWeekend(), $this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')), $absolute, ); } /** * Get the difference in hours. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInHours($date = null, bool $absolute = false): float { return $this->diffInMinutes($date, $absolute) / static::MINUTES_PER_HOUR; } /** * Get the difference in minutes. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMinutes($date = null, bool $absolute = false): float { return $this->diffInSeconds($date, $absolute) / static::SECONDS_PER_MINUTE; } /** * Get the difference in seconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInSeconds($date = null, bool $absolute = false): float { return $this->diffInMilliseconds($date, $absolute) / static::MILLISECONDS_PER_SECOND; } /** * Get the difference in microseconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMicroseconds($date = null, bool $absolute = false): float { /** @var CarbonInterface $date */ $date = $this->resolveCarbon($date); $value = ($date->timestamp - $this->timestamp) * static::MICROSECONDS_PER_SECOND + $date->micro - $this->micro; return $absolute ? abs($value) : $value; } /** * Get the difference in milliseconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMilliseconds($date = null, bool $absolute = false): float { return $this->diffInMicroseconds($date, $absolute) / static::MICROSECONDS_PER_MILLISECOND; } /** * The number of seconds since midnight. * * @return float */ public function secondsSinceMidnight(): float { return $this->diffInSeconds($this->copy()->startOfDay(), true); } /** * The number of seconds until 23:59:59. * * @return float */ public function secondsUntilEndOfDay(): float { return $this->diffInSeconds($this->copy()->endOfDay(), true); } /** * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). * * @example * ``` * echo Carbon::tomorrow()->diffForHumans() . "\n"; * echo Carbon::tomorrow()->diffForHumans(['parts' => 2]) . "\n"; * echo Carbon::tomorrow()->diffForHumans(['parts' => 3, 'join' => true]) . "\n"; * echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday()) . "\n"; * echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday(), ['short' => true]) . "\n"; * ``` * * @param Carbon|DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'other' entry (see above) * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options */ public function diffForHumans($other = null, $syntax = null, $short = false, $parts = 1, $options = null): string { /* @var CarbonInterface $this */ if (\is_array($other)) { $other['syntax'] = \array_key_exists('syntax', $other) ? $other['syntax'] : $syntax; $syntax = $other; $other = $syntax['other'] ?? null; } $intSyntax = &$syntax; if (\is_array($syntax)) { $syntax['syntax'] = $syntax['syntax'] ?? null; $intSyntax = &$syntax['syntax']; } $intSyntax = (int) ($intSyntax ?? static::DIFF_RELATIVE_AUTO); $intSyntax = $intSyntax === static::DIFF_RELATIVE_AUTO && $other === null ? static::DIFF_RELATIVE_TO_NOW : $intSyntax; $parts = min(7, max(1, (int) $parts)); $skip = \is_array($syntax) ? ($syntax['skip'] ?? []) : []; $options ??= $this->localHumanDiffOptions ?? $this->transmitFactory( static fn () => static::getHumanDiffOptions(), ); return $this->diff($other, skip: (array) $skip)->forHumans($syntax, (bool) $short, $parts, $options); } /** * @alias diffForHumans * * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function from($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->diffForHumans($other, $syntax, $short, $parts, $options); } /** * @alias diffForHumans * * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). */ public function since($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->diffForHumans($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given (or now if null given) to current instance. * * When comparing a value in the past to default now: * 1 hour from now * 5 months from now * * When comparing a value in the future to default now: * 1 hour ago * 5 months ago * * When comparing a value in the past to another value: * 1 hour after * 5 months after * * When comparing a value in the future to another value: * 1 hour before * 5 months before * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function to($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { if (!$syntax && !$other) { $syntax = CarbonInterface::DIFF_RELATIVE_TO_NOW; } return $this->resolveCarbon($other)->diffForHumans($this, $syntax, $short, $parts, $options); } /** * @alias to * * Get the difference in a human readable format in the current locale from an other * instance given (or now if null given) to current instance. * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function until($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->to($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from current * instance to now. * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function fromNow($syntax = null, $short = false, $parts = 1, $options = null) { $other = null; if ($syntax instanceof DateTimeInterface) { [$other, $syntax, $short, $parts, $options] = array_pad(\func_get_args(), 5, null); } return $this->from($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given to now * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single part) * @param int $options human diff options * * @return string */ public function toNow($syntax = null, $short = false, $parts = 1, $options = null) { return $this->to(null, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given to now * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single part) * @param int $options human diff options * * @return string */ public function ago($syntax = null, $short = false, $parts = 1, $options = null) { $other = null; if ($syntax instanceof DateTimeInterface) { [$other, $syntax, $short, $parts, $options] = array_pad(\func_get_args(), 5, null); } return $this->from($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human-readable format in the current locale from current instance to another * instance given (or now if null given). * * @return string */ public function timespan($other = null, $timezone = null): string { if (\is_string($other)) { $other = $this->transmitFactory(static fn () => static::parse($other, $timezone)); } return $this->diffForHumans($other, [ 'join' => ', ', 'syntax' => CarbonInterface::DIFF_ABSOLUTE, 'parts' => INF, ]); } /** * Returns either day of week + time (e.g. "Last Friday at 3:30 PM") if reference time is within 7 days, * or a calendar date (e.g. "10/29/2017") otherwise. * * Language, date and time formats will change according to the current locale. * * @param Carbon|\DateTimeInterface|string|null $referenceTime * @param array $formats * * @return string */ public function calendar($referenceTime = null, array $formats = []) { /** @var CarbonInterface $current */ $current = $this->avoidMutation()->startOfDay(); /** @var CarbonInterface $other */ $other = $this->resolveCarbon($referenceTime)->avoidMutation()->setTimezone($this->getTimezone())->startOfDay(); $diff = $other->diffInDays($current, false); $format = $diff <= -static::DAYS_PER_WEEK ? 'sameElse' : ( $diff < -1 ? 'lastWeek' : ( $diff < 0 ? 'lastDay' : ( $diff < 1 ? 'sameDay' : ( $diff < 2 ? 'nextDay' : ( $diff < static::DAYS_PER_WEEK ? 'nextWeek' : 'sameElse' ) ) ) ) ); $format = array_merge($this->getCalendarFormats(), $formats)[$format]; if ($format instanceof Closure) { $format = $format($current, $other) ?? ''; } return $this->isoFormat((string) $format); } private function getIntervalDayDiff(DateInterval $interval): int { return (int) $interval->format('%r%a'); } }
PHP
{ "end_line": 159, "name": "diffInYears", "signature": "public function diffInYears($date = null, bool $absolute = false, bool $utc = false): float", "start_line": 127 }
{ "class_name": "Difference", "class_signature": "trait Difference", "namespace": "Carbon\\Traits" }
diffInMonths
Carbon/src/Carbon/Traits/Difference.php
public function diffInMonths($date = null, bool $absolute = false, bool $utc = false): float { $start = $this; $end = $this->resolveCarbon($date); // Compare using UTC if ($utc || ($end->timezoneName !== $start->timezoneName)) { $start = $start->avoidMutation()->utc(); $end = $end->avoidMutation()->utc(); } [$yearStart, $monthStart, $dayStart] = explode('-', $start->format('Y-m-dHisu')); [$yearEnd, $monthEnd, $dayEnd] = explode('-', $end->format('Y-m-dHisu')); $monthsDiff = (((int) $yearEnd) - ((int) $yearStart)) * static::MONTHS_PER_YEAR + ((int) $monthEnd) - ((int) $monthStart); if ($monthsDiff > 0) { $monthsDiff -= ($dayStart > $dayEnd ? 1 : 0); } elseif ($monthsDiff < 0) { $monthsDiff += ($dayStart < $dayEnd ? 1 : 0); } $ascending = ($start <= $end); $sign = $absolute || $ascending ? 1 : -1; $monthsDiff = abs($monthsDiff); if (!$ascending) { [$start, $end] = [$end, $start]; } /** @var Carbon|CarbonImmutable $floorEnd */ $floorEnd = $start->avoidMutation()->addMonths($monthsDiff); if ($floorEnd >= $end) { return $sign * $monthsDiff; } /** @var Carbon|CarbonImmutable $ceilEnd */ $ceilEnd = $start->avoidMutation()->addMonths($monthsDiff + 1); $daysToFloor = $floorEnd->diffInDays($end); $daysToCeil = $end->diffInDays($ceilEnd); return $sign * ($monthsDiff + $daysToFloor / ($daysToCeil + $daysToFloor)); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Carbon\Exceptions\UnknownUnitException; use Carbon\Unit; use Closure; use DateInterval; use DateTimeInterface; /** * Trait Difference. * * Depends on the following methods: * * @method bool lessThan($date) * @method static copy() * @method static resolveCarbon($date = null) */ trait Difference { /** * Get the difference as a DateInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return DateInterval */ public function diffAsDateInterval($date = null, bool $absolute = false): DateInterval { $other = $this->resolveCarbon($date); // Work-around for https://bugs.php.net/bug.php?id=81458 // It was initially introduced for https://bugs.php.net/bug.php?id=80998 // The very specific case of 80998 was fixed in PHP 8.1beta3, but it introduced 81458 // So we still need to keep this for now if ($other->tz !== $this->tz) { $other = $other->avoidMutation()->setTimezone($this->tz); } return parent::diff($other, $absolute); } /** * Get the difference as a CarbonInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return CarbonInterval */ public function diffAsCarbonInterval($date = null, bool $absolute = false, array $skip = []): CarbonInterval { return CarbonInterval::diff($this, $this->resolveCarbon($date), $absolute, $skip) ->setLocalTranslator($this->getLocalTranslator()); } /** * @alias diffAsCarbonInterval * * Get the difference as a DateInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return CarbonInterval */ public function diff($date = null, bool $absolute = false, array $skip = []): CarbonInterval { return $this->diffAsCarbonInterval($date, $absolute, $skip); } /** * @param Unit|string $unit microsecond, millisecond, second, minute, * hour, day, week, month, quarter, year, * century, millennium * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInUnit(Unit|string $unit, $date = null, bool $absolute = false, bool $utc = false): float { $unit = static::pluralUnit($unit instanceof Unit ? $unit->value : rtrim($unit, 'z')); $method = 'diffIn'.$unit; if (!method_exists($this, $method)) { throw new UnknownUnitException($unit); } return $this->$method($date, $absolute, $utc); } /** * Get the difference in years * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInYears($date = null, bool $absolute = false, bool $utc = false): float { $start = $this; $end = $this->resolveCarbon($date); if ($utc) { $start = $start->avoidMutation()->utc(); $end = $end->avoidMutation()->utc(); } $ascending = ($start <= $end); $sign = $absolute || $ascending ? 1 : -1; if (!$ascending) { [$start, $end] = [$end, $start]; } $yearsDiff = (int) $start->diff($end, $absolute)->format('%r%y'); /** @var Carbon|CarbonImmutable $floorEnd */ $floorEnd = $start->avoidMutation()->addYears($yearsDiff); if ($floorEnd >= $end) { return $sign * $yearsDiff; } /** @var Carbon|CarbonImmutable $ceilEnd */ $ceilEnd = $start->avoidMutation()->addYears($yearsDiff + 1); $daysToFloor = $floorEnd->diffInDays($end); $daysToCeil = $end->diffInDays($ceilEnd); return $sign * ($yearsDiff + $daysToFloor / ($daysToCeil + $daysToFloor)); } /** * Get the difference in quarters. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInQuarters($date = null, bool $absolute = false, bool $utc = false): float { return $this->diffInMonths($date, $absolute, $utc) / static::MONTHS_PER_QUARTER; } /** * Get the difference in months. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInMonths($date = null, bool $absolute = false, bool $utc = false): float { $start = $this; $end = $this->resolveCarbon($date); // Compare using UTC if ($utc || ($end->timezoneName !== $start->timezoneName)) { $start = $start->avoidMutation()->utc(); $end = $end->avoidMutation()->utc(); } [$yearStart, $monthStart, $dayStart] = explode('-', $start->format('Y-m-dHisu')); [$yearEnd, $monthEnd, $dayEnd] = explode('-', $end->format('Y-m-dHisu')); $monthsDiff = (((int) $yearEnd) - ((int) $yearStart)) * static::MONTHS_PER_YEAR + ((int) $monthEnd) - ((int) $monthStart); if ($monthsDiff > 0) { $monthsDiff -= ($dayStart > $dayEnd ? 1 : 0); } elseif ($monthsDiff < 0) { $monthsDiff += ($dayStart < $dayEnd ? 1 : 0); } $ascending = ($start <= $end); $sign = $absolute || $ascending ? 1 : -1; $monthsDiff = abs($monthsDiff); if (!$ascending) { [$start, $end] = [$end, $start]; } /** @var Carbon|CarbonImmutable $floorEnd */ $floorEnd = $start->avoidMutation()->addMonths($monthsDiff); if ($floorEnd >= $end) { return $sign * $monthsDiff; } /** @var Carbon|CarbonImmutable $ceilEnd */ $ceilEnd = $start->avoidMutation()->addMonths($monthsDiff + 1); $daysToFloor = $floorEnd->diffInDays($end); $daysToCeil = $end->diffInDays($ceilEnd); return $sign * ($monthsDiff + $daysToFloor / ($daysToCeil + $daysToFloor)); } /** * Get the difference in weeks. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInWeeks($date = null, bool $absolute = false, bool $utc = false): float { return $this->diffInDays($date, $absolute, $utc) / static::DAYS_PER_WEEK; } /** * Get the difference in days. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInDays($date = null, bool $absolute = false, bool $utc = false): float { $date = $this->resolveCarbon($date); $current = $this; // Compare using UTC if ($utc || ($date->timezoneName !== $current->timezoneName)) { $date = $date->avoidMutation()->utc(); $current = $current->avoidMutation()->utc(); } $negative = ($date < $current); [$start, $end] = $negative ? [$date, $current] : [$current, $date]; $interval = $start->diffAsDateInterval($end); $daysA = $this->getIntervalDayDiff($interval); $floorEnd = $start->avoidMutation()->addDays($daysA); $daysB = $daysA + ($floorEnd <= $end ? 1 : -1); $ceilEnd = $start->avoidMutation()->addDays($daysB); $microsecondsBetween = $floorEnd->diffInMicroseconds($ceilEnd); $microsecondsToEnd = $floorEnd->diffInMicroseconds($end); return ($negative && !$absolute ? -1 : 1) * ($daysA * ($microsecondsBetween - $microsecondsToEnd) + $daysB * $microsecondsToEnd) / $microsecondsBetween; } /** * Get the difference in days using a filter closure. * * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInDaysFiltered(Closure $callback, $date = null, bool $absolute = false): int { return $this->diffFiltered(CarbonInterval::day(), $callback, $date, $absolute); } /** * Get the difference in hours using a filter closure. * * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInHoursFiltered(Closure $callback, $date = null, bool $absolute = false): int { return $this->diffFiltered(CarbonInterval::hour(), $callback, $date, $absolute); } /** * Get the difference by the given interval using a filter closure. * * @param CarbonInterval $ci An interval to traverse by * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffFiltered(CarbonInterval $ci, Closure $callback, $date = null, bool $absolute = false): int { $start = $this; $end = $this->resolveCarbon($date); $inverse = false; if ($end < $start) { $start = $end; $end = $this; $inverse = true; } $options = CarbonPeriod::EXCLUDE_END_DATE | ($this->isMutable() ? 0 : CarbonPeriod::IMMUTABLE); $diff = $ci->toPeriod($start, $end, $options)->filter($callback)->count(); return $inverse && !$absolute ? -$diff : $diff; } /** * Get the difference in weekdays. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInWeekdays($date = null, bool $absolute = false): int { return $this->diffInDaysFiltered( static fn (CarbonInterface $date) => $date->isWeekday(), $this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')), $absolute, ); } /** * Get the difference in weekend days using a filter. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInWeekendDays($date = null, bool $absolute = false): int { return $this->diffInDaysFiltered( static fn (CarbonInterface $date) => $date->isWeekend(), $this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')), $absolute, ); } /** * Get the difference in hours. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInHours($date = null, bool $absolute = false): float { return $this->diffInMinutes($date, $absolute) / static::MINUTES_PER_HOUR; } /** * Get the difference in minutes. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMinutes($date = null, bool $absolute = false): float { return $this->diffInSeconds($date, $absolute) / static::SECONDS_PER_MINUTE; } /** * Get the difference in seconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInSeconds($date = null, bool $absolute = false): float { return $this->diffInMilliseconds($date, $absolute) / static::MILLISECONDS_PER_SECOND; } /** * Get the difference in microseconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMicroseconds($date = null, bool $absolute = false): float { /** @var CarbonInterface $date */ $date = $this->resolveCarbon($date); $value = ($date->timestamp - $this->timestamp) * static::MICROSECONDS_PER_SECOND + $date->micro - $this->micro; return $absolute ? abs($value) : $value; } /** * Get the difference in milliseconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMilliseconds($date = null, bool $absolute = false): float { return $this->diffInMicroseconds($date, $absolute) / static::MICROSECONDS_PER_MILLISECOND; } /** * The number of seconds since midnight. * * @return float */ public function secondsSinceMidnight(): float { return $this->diffInSeconds($this->copy()->startOfDay(), true); } /** * The number of seconds until 23:59:59. * * @return float */ public function secondsUntilEndOfDay(): float { return $this->diffInSeconds($this->copy()->endOfDay(), true); } /** * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). * * @example * ``` * echo Carbon::tomorrow()->diffForHumans() . "\n"; * echo Carbon::tomorrow()->diffForHumans(['parts' => 2]) . "\n"; * echo Carbon::tomorrow()->diffForHumans(['parts' => 3, 'join' => true]) . "\n"; * echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday()) . "\n"; * echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday(), ['short' => true]) . "\n"; * ``` * * @param Carbon|DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'other' entry (see above) * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options */ public function diffForHumans($other = null, $syntax = null, $short = false, $parts = 1, $options = null): string { /* @var CarbonInterface $this */ if (\is_array($other)) { $other['syntax'] = \array_key_exists('syntax', $other) ? $other['syntax'] : $syntax; $syntax = $other; $other = $syntax['other'] ?? null; } $intSyntax = &$syntax; if (\is_array($syntax)) { $syntax['syntax'] = $syntax['syntax'] ?? null; $intSyntax = &$syntax['syntax']; } $intSyntax = (int) ($intSyntax ?? static::DIFF_RELATIVE_AUTO); $intSyntax = $intSyntax === static::DIFF_RELATIVE_AUTO && $other === null ? static::DIFF_RELATIVE_TO_NOW : $intSyntax; $parts = min(7, max(1, (int) $parts)); $skip = \is_array($syntax) ? ($syntax['skip'] ?? []) : []; $options ??= $this->localHumanDiffOptions ?? $this->transmitFactory( static fn () => static::getHumanDiffOptions(), ); return $this->diff($other, skip: (array) $skip)->forHumans($syntax, (bool) $short, $parts, $options); } /** * @alias diffForHumans * * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function from($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->diffForHumans($other, $syntax, $short, $parts, $options); } /** * @alias diffForHumans * * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). */ public function since($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->diffForHumans($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given (or now if null given) to current instance. * * When comparing a value in the past to default now: * 1 hour from now * 5 months from now * * When comparing a value in the future to default now: * 1 hour ago * 5 months ago * * When comparing a value in the past to another value: * 1 hour after * 5 months after * * When comparing a value in the future to another value: * 1 hour before * 5 months before * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function to($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { if (!$syntax && !$other) { $syntax = CarbonInterface::DIFF_RELATIVE_TO_NOW; } return $this->resolveCarbon($other)->diffForHumans($this, $syntax, $short, $parts, $options); } /** * @alias to * * Get the difference in a human readable format in the current locale from an other * instance given (or now if null given) to current instance. * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function until($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->to($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from current * instance to now. * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function fromNow($syntax = null, $short = false, $parts = 1, $options = null) { $other = null; if ($syntax instanceof DateTimeInterface) { [$other, $syntax, $short, $parts, $options] = array_pad(\func_get_args(), 5, null); } return $this->from($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given to now * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single part) * @param int $options human diff options * * @return string */ public function toNow($syntax = null, $short = false, $parts = 1, $options = null) { return $this->to(null, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given to now * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single part) * @param int $options human diff options * * @return string */ public function ago($syntax = null, $short = false, $parts = 1, $options = null) { $other = null; if ($syntax instanceof DateTimeInterface) { [$other, $syntax, $short, $parts, $options] = array_pad(\func_get_args(), 5, null); } return $this->from($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human-readable format in the current locale from current instance to another * instance given (or now if null given). * * @return string */ public function timespan($other = null, $timezone = null): string { if (\is_string($other)) { $other = $this->transmitFactory(static fn () => static::parse($other, $timezone)); } return $this->diffForHumans($other, [ 'join' => ', ', 'syntax' => CarbonInterface::DIFF_ABSOLUTE, 'parts' => INF, ]); } /** * Returns either day of week + time (e.g. "Last Friday at 3:30 PM") if reference time is within 7 days, * or a calendar date (e.g. "10/29/2017") otherwise. * * Language, date and time formats will change according to the current locale. * * @param Carbon|\DateTimeInterface|string|null $referenceTime * @param array $formats * * @return string */ public function calendar($referenceTime = null, array $formats = []) { /** @var CarbonInterface $current */ $current = $this->avoidMutation()->startOfDay(); /** @var CarbonInterface $other */ $other = $this->resolveCarbon($referenceTime)->avoidMutation()->setTimezone($this->getTimezone())->startOfDay(); $diff = $other->diffInDays($current, false); $format = $diff <= -static::DAYS_PER_WEEK ? 'sameElse' : ( $diff < -1 ? 'lastWeek' : ( $diff < 0 ? 'lastDay' : ( $diff < 1 ? 'sameDay' : ( $diff < 2 ? 'nextDay' : ( $diff < static::DAYS_PER_WEEK ? 'nextWeek' : 'sameElse' ) ) ) ) ); $format = array_merge($this->getCalendarFormats(), $formats)[$format]; if ($format instanceof Closure) { $format = $format($current, $other) ?? ''; } return $this->isoFormat((string) $format); } private function getIntervalDayDiff(DateInterval $interval): int { return (int) $interval->format('%r%a'); } }
PHP
{ "end_line": 229, "name": "diffInMonths", "signature": "public function diffInMonths($date = null, bool $absolute = false, bool $utc = false): float", "start_line": 184 }
{ "class_name": "Difference", "class_signature": "trait Difference", "namespace": "Carbon\\Traits" }
diffInDays
Carbon/src/Carbon/Traits/Difference.php
public function diffInDays($date = null, bool $absolute = false, bool $utc = false): float { $date = $this->resolveCarbon($date); $current = $this; // Compare using UTC if ($utc || ($date->timezoneName !== $current->timezoneName)) { $date = $date->avoidMutation()->utc(); $current = $current->avoidMutation()->utc(); } $negative = ($date < $current); [$start, $end] = $negative ? [$date, $current] : [$current, $date]; $interval = $start->diffAsDateInterval($end); $daysA = $this->getIntervalDayDiff($interval); $floorEnd = $start->avoidMutation()->addDays($daysA); $daysB = $daysA + ($floorEnd <= $end ? 1 : -1); $ceilEnd = $start->avoidMutation()->addDays($daysB); $microsecondsBetween = $floorEnd->diffInMicroseconds($ceilEnd); $microsecondsToEnd = $floorEnd->diffInMicroseconds($end); return ($negative && !$absolute ? -1 : 1) * ($daysA * ($microsecondsBetween - $microsecondsToEnd) + $daysB * $microsecondsToEnd) / $microsecondsBetween; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Carbon\Exceptions\UnknownUnitException; use Carbon\Unit; use Closure; use DateInterval; use DateTimeInterface; /** * Trait Difference. * * Depends on the following methods: * * @method bool lessThan($date) * @method static copy() * @method static resolveCarbon($date = null) */ trait Difference { /** * Get the difference as a DateInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return DateInterval */ public function diffAsDateInterval($date = null, bool $absolute = false): DateInterval { $other = $this->resolveCarbon($date); // Work-around for https://bugs.php.net/bug.php?id=81458 // It was initially introduced for https://bugs.php.net/bug.php?id=80998 // The very specific case of 80998 was fixed in PHP 8.1beta3, but it introduced 81458 // So we still need to keep this for now if ($other->tz !== $this->tz) { $other = $other->avoidMutation()->setTimezone($this->tz); } return parent::diff($other, $absolute); } /** * Get the difference as a CarbonInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return CarbonInterval */ public function diffAsCarbonInterval($date = null, bool $absolute = false, array $skip = []): CarbonInterval { return CarbonInterval::diff($this, $this->resolveCarbon($date), $absolute, $skip) ->setLocalTranslator($this->getLocalTranslator()); } /** * @alias diffAsCarbonInterval * * Get the difference as a DateInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return CarbonInterval */ public function diff($date = null, bool $absolute = false, array $skip = []): CarbonInterval { return $this->diffAsCarbonInterval($date, $absolute, $skip); } /** * @param Unit|string $unit microsecond, millisecond, second, minute, * hour, day, week, month, quarter, year, * century, millennium * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInUnit(Unit|string $unit, $date = null, bool $absolute = false, bool $utc = false): float { $unit = static::pluralUnit($unit instanceof Unit ? $unit->value : rtrim($unit, 'z')); $method = 'diffIn'.$unit; if (!method_exists($this, $method)) { throw new UnknownUnitException($unit); } return $this->$method($date, $absolute, $utc); } /** * Get the difference in years * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInYears($date = null, bool $absolute = false, bool $utc = false): float { $start = $this; $end = $this->resolveCarbon($date); if ($utc) { $start = $start->avoidMutation()->utc(); $end = $end->avoidMutation()->utc(); } $ascending = ($start <= $end); $sign = $absolute || $ascending ? 1 : -1; if (!$ascending) { [$start, $end] = [$end, $start]; } $yearsDiff = (int) $start->diff($end, $absolute)->format('%r%y'); /** @var Carbon|CarbonImmutable $floorEnd */ $floorEnd = $start->avoidMutation()->addYears($yearsDiff); if ($floorEnd >= $end) { return $sign * $yearsDiff; } /** @var Carbon|CarbonImmutable $ceilEnd */ $ceilEnd = $start->avoidMutation()->addYears($yearsDiff + 1); $daysToFloor = $floorEnd->diffInDays($end); $daysToCeil = $end->diffInDays($ceilEnd); return $sign * ($yearsDiff + $daysToFloor / ($daysToCeil + $daysToFloor)); } /** * Get the difference in quarters. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInQuarters($date = null, bool $absolute = false, bool $utc = false): float { return $this->diffInMonths($date, $absolute, $utc) / static::MONTHS_PER_QUARTER; } /** * Get the difference in months. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInMonths($date = null, bool $absolute = false, bool $utc = false): float { $start = $this; $end = $this->resolveCarbon($date); // Compare using UTC if ($utc || ($end->timezoneName !== $start->timezoneName)) { $start = $start->avoidMutation()->utc(); $end = $end->avoidMutation()->utc(); } [$yearStart, $monthStart, $dayStart] = explode('-', $start->format('Y-m-dHisu')); [$yearEnd, $monthEnd, $dayEnd] = explode('-', $end->format('Y-m-dHisu')); $monthsDiff = (((int) $yearEnd) - ((int) $yearStart)) * static::MONTHS_PER_YEAR + ((int) $monthEnd) - ((int) $monthStart); if ($monthsDiff > 0) { $monthsDiff -= ($dayStart > $dayEnd ? 1 : 0); } elseif ($monthsDiff < 0) { $monthsDiff += ($dayStart < $dayEnd ? 1 : 0); } $ascending = ($start <= $end); $sign = $absolute || $ascending ? 1 : -1; $monthsDiff = abs($monthsDiff); if (!$ascending) { [$start, $end] = [$end, $start]; } /** @var Carbon|CarbonImmutable $floorEnd */ $floorEnd = $start->avoidMutation()->addMonths($monthsDiff); if ($floorEnd >= $end) { return $sign * $monthsDiff; } /** @var Carbon|CarbonImmutable $ceilEnd */ $ceilEnd = $start->avoidMutation()->addMonths($monthsDiff + 1); $daysToFloor = $floorEnd->diffInDays($end); $daysToCeil = $end->diffInDays($ceilEnd); return $sign * ($monthsDiff + $daysToFloor / ($daysToCeil + $daysToFloor)); } /** * Get the difference in weeks. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInWeeks($date = null, bool $absolute = false, bool $utc = false): float { return $this->diffInDays($date, $absolute, $utc) / static::DAYS_PER_WEEK; } /** * Get the difference in days. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInDays($date = null, bool $absolute = false, bool $utc = false): float { $date = $this->resolveCarbon($date); $current = $this; // Compare using UTC if ($utc || ($date->timezoneName !== $current->timezoneName)) { $date = $date->avoidMutation()->utc(); $current = $current->avoidMutation()->utc(); } $negative = ($date < $current); [$start, $end] = $negative ? [$date, $current] : [$current, $date]; $interval = $start->diffAsDateInterval($end); $daysA = $this->getIntervalDayDiff($interval); $floorEnd = $start->avoidMutation()->addDays($daysA); $daysB = $daysA + ($floorEnd <= $end ? 1 : -1); $ceilEnd = $start->avoidMutation()->addDays($daysB); $microsecondsBetween = $floorEnd->diffInMicroseconds($ceilEnd); $microsecondsToEnd = $floorEnd->diffInMicroseconds($end); return ($negative && !$absolute ? -1 : 1) * ($daysA * ($microsecondsBetween - $microsecondsToEnd) + $daysB * $microsecondsToEnd) / $microsecondsBetween; } /** * Get the difference in days using a filter closure. * * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInDaysFiltered(Closure $callback, $date = null, bool $absolute = false): int { return $this->diffFiltered(CarbonInterval::day(), $callback, $date, $absolute); } /** * Get the difference in hours using a filter closure. * * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInHoursFiltered(Closure $callback, $date = null, bool $absolute = false): int { return $this->diffFiltered(CarbonInterval::hour(), $callback, $date, $absolute); } /** * Get the difference by the given interval using a filter closure. * * @param CarbonInterval $ci An interval to traverse by * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffFiltered(CarbonInterval $ci, Closure $callback, $date = null, bool $absolute = false): int { $start = $this; $end = $this->resolveCarbon($date); $inverse = false; if ($end < $start) { $start = $end; $end = $this; $inverse = true; } $options = CarbonPeriod::EXCLUDE_END_DATE | ($this->isMutable() ? 0 : CarbonPeriod::IMMUTABLE); $diff = $ci->toPeriod($start, $end, $options)->filter($callback)->count(); return $inverse && !$absolute ? -$diff : $diff; } /** * Get the difference in weekdays. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInWeekdays($date = null, bool $absolute = false): int { return $this->diffInDaysFiltered( static fn (CarbonInterface $date) => $date->isWeekday(), $this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')), $absolute, ); } /** * Get the difference in weekend days using a filter. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInWeekendDays($date = null, bool $absolute = false): int { return $this->diffInDaysFiltered( static fn (CarbonInterface $date) => $date->isWeekend(), $this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')), $absolute, ); } /** * Get the difference in hours. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInHours($date = null, bool $absolute = false): float { return $this->diffInMinutes($date, $absolute) / static::MINUTES_PER_HOUR; } /** * Get the difference in minutes. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMinutes($date = null, bool $absolute = false): float { return $this->diffInSeconds($date, $absolute) / static::SECONDS_PER_MINUTE; } /** * Get the difference in seconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInSeconds($date = null, bool $absolute = false): float { return $this->diffInMilliseconds($date, $absolute) / static::MILLISECONDS_PER_SECOND; } /** * Get the difference in microseconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMicroseconds($date = null, bool $absolute = false): float { /** @var CarbonInterface $date */ $date = $this->resolveCarbon($date); $value = ($date->timestamp - $this->timestamp) * static::MICROSECONDS_PER_SECOND + $date->micro - $this->micro; return $absolute ? abs($value) : $value; } /** * Get the difference in milliseconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMilliseconds($date = null, bool $absolute = false): float { return $this->diffInMicroseconds($date, $absolute) / static::MICROSECONDS_PER_MILLISECOND; } /** * The number of seconds since midnight. * * @return float */ public function secondsSinceMidnight(): float { return $this->diffInSeconds($this->copy()->startOfDay(), true); } /** * The number of seconds until 23:59:59. * * @return float */ public function secondsUntilEndOfDay(): float { return $this->diffInSeconds($this->copy()->endOfDay(), true); } /** * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). * * @example * ``` * echo Carbon::tomorrow()->diffForHumans() . "\n"; * echo Carbon::tomorrow()->diffForHumans(['parts' => 2]) . "\n"; * echo Carbon::tomorrow()->diffForHumans(['parts' => 3, 'join' => true]) . "\n"; * echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday()) . "\n"; * echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday(), ['short' => true]) . "\n"; * ``` * * @param Carbon|DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'other' entry (see above) * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options */ public function diffForHumans($other = null, $syntax = null, $short = false, $parts = 1, $options = null): string { /* @var CarbonInterface $this */ if (\is_array($other)) { $other['syntax'] = \array_key_exists('syntax', $other) ? $other['syntax'] : $syntax; $syntax = $other; $other = $syntax['other'] ?? null; } $intSyntax = &$syntax; if (\is_array($syntax)) { $syntax['syntax'] = $syntax['syntax'] ?? null; $intSyntax = &$syntax['syntax']; } $intSyntax = (int) ($intSyntax ?? static::DIFF_RELATIVE_AUTO); $intSyntax = $intSyntax === static::DIFF_RELATIVE_AUTO && $other === null ? static::DIFF_RELATIVE_TO_NOW : $intSyntax; $parts = min(7, max(1, (int) $parts)); $skip = \is_array($syntax) ? ($syntax['skip'] ?? []) : []; $options ??= $this->localHumanDiffOptions ?? $this->transmitFactory( static fn () => static::getHumanDiffOptions(), ); return $this->diff($other, skip: (array) $skip)->forHumans($syntax, (bool) $short, $parts, $options); } /** * @alias diffForHumans * * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function from($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->diffForHumans($other, $syntax, $short, $parts, $options); } /** * @alias diffForHumans * * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). */ public function since($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->diffForHumans($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given (or now if null given) to current instance. * * When comparing a value in the past to default now: * 1 hour from now * 5 months from now * * When comparing a value in the future to default now: * 1 hour ago * 5 months ago * * When comparing a value in the past to another value: * 1 hour after * 5 months after * * When comparing a value in the future to another value: * 1 hour before * 5 months before * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function to($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { if (!$syntax && !$other) { $syntax = CarbonInterface::DIFF_RELATIVE_TO_NOW; } return $this->resolveCarbon($other)->diffForHumans($this, $syntax, $short, $parts, $options); } /** * @alias to * * Get the difference in a human readable format in the current locale from an other * instance given (or now if null given) to current instance. * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function until($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->to($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from current * instance to now. * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function fromNow($syntax = null, $short = false, $parts = 1, $options = null) { $other = null; if ($syntax instanceof DateTimeInterface) { [$other, $syntax, $short, $parts, $options] = array_pad(\func_get_args(), 5, null); } return $this->from($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given to now * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single part) * @param int $options human diff options * * @return string */ public function toNow($syntax = null, $short = false, $parts = 1, $options = null) { return $this->to(null, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given to now * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single part) * @param int $options human diff options * * @return string */ public function ago($syntax = null, $short = false, $parts = 1, $options = null) { $other = null; if ($syntax instanceof DateTimeInterface) { [$other, $syntax, $short, $parts, $options] = array_pad(\func_get_args(), 5, null); } return $this->from($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human-readable format in the current locale from current instance to another * instance given (or now if null given). * * @return string */ public function timespan($other = null, $timezone = null): string { if (\is_string($other)) { $other = $this->transmitFactory(static fn () => static::parse($other, $timezone)); } return $this->diffForHumans($other, [ 'join' => ', ', 'syntax' => CarbonInterface::DIFF_ABSOLUTE, 'parts' => INF, ]); } /** * Returns either day of week + time (e.g. "Last Friday at 3:30 PM") if reference time is within 7 days, * or a calendar date (e.g. "10/29/2017") otherwise. * * Language, date and time formats will change according to the current locale. * * @param Carbon|\DateTimeInterface|string|null $referenceTime * @param array $formats * * @return string */ public function calendar($referenceTime = null, array $formats = []) { /** @var CarbonInterface $current */ $current = $this->avoidMutation()->startOfDay(); /** @var CarbonInterface $other */ $other = $this->resolveCarbon($referenceTime)->avoidMutation()->setTimezone($this->getTimezone())->startOfDay(); $diff = $other->diffInDays($current, false); $format = $diff <= -static::DAYS_PER_WEEK ? 'sameElse' : ( $diff < -1 ? 'lastWeek' : ( $diff < 0 ? 'lastDay' : ( $diff < 1 ? 'sameDay' : ( $diff < 2 ? 'nextDay' : ( $diff < static::DAYS_PER_WEEK ? 'nextWeek' : 'sameElse' ) ) ) ) ); $format = array_merge($this->getCalendarFormats(), $formats)[$format]; if ($format instanceof Closure) { $format = $format($current, $other) ?? ''; } return $this->isoFormat((string) $format); } private function getIntervalDayDiff(DateInterval $interval): int { return (int) $interval->format('%r%a'); } }
PHP
{ "end_line": 278, "name": "diffInDays", "signature": "public function diffInDays($date = null, bool $absolute = false, bool $utc = false): float", "start_line": 254 }
{ "class_name": "Difference", "class_signature": "trait Difference", "namespace": "Carbon\\Traits" }
diffFiltered
Carbon/src/Carbon/Traits/Difference.php
public function diffFiltered(CarbonInterval $ci, Closure $callback, $date = null, bool $absolute = false): int { $start = $this; $end = $this->resolveCarbon($date); $inverse = false; if ($end < $start) { $start = $end; $end = $this; $inverse = true; } $options = CarbonPeriod::EXCLUDE_END_DATE | ($this->isMutable() ? 0 : CarbonPeriod::IMMUTABLE); $diff = $ci->toPeriod($start, $end, $options)->filter($callback)->count(); return $inverse && !$absolute ? -$diff : $diff; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Carbon\Exceptions\UnknownUnitException; use Carbon\Unit; use Closure; use DateInterval; use DateTimeInterface; /** * Trait Difference. * * Depends on the following methods: * * @method bool lessThan($date) * @method static copy() * @method static resolveCarbon($date = null) */ trait Difference { /** * Get the difference as a DateInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return DateInterval */ public function diffAsDateInterval($date = null, bool $absolute = false): DateInterval { $other = $this->resolveCarbon($date); // Work-around for https://bugs.php.net/bug.php?id=81458 // It was initially introduced for https://bugs.php.net/bug.php?id=80998 // The very specific case of 80998 was fixed in PHP 8.1beta3, but it introduced 81458 // So we still need to keep this for now if ($other->tz !== $this->tz) { $other = $other->avoidMutation()->setTimezone($this->tz); } return parent::diff($other, $absolute); } /** * Get the difference as a CarbonInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return CarbonInterval */ public function diffAsCarbonInterval($date = null, bool $absolute = false, array $skip = []): CarbonInterval { return CarbonInterval::diff($this, $this->resolveCarbon($date), $absolute, $skip) ->setLocalTranslator($this->getLocalTranslator()); } /** * @alias diffAsCarbonInterval * * Get the difference as a DateInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return CarbonInterval */ public function diff($date = null, bool $absolute = false, array $skip = []): CarbonInterval { return $this->diffAsCarbonInterval($date, $absolute, $skip); } /** * @param Unit|string $unit microsecond, millisecond, second, minute, * hour, day, week, month, quarter, year, * century, millennium * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInUnit(Unit|string $unit, $date = null, bool $absolute = false, bool $utc = false): float { $unit = static::pluralUnit($unit instanceof Unit ? $unit->value : rtrim($unit, 'z')); $method = 'diffIn'.$unit; if (!method_exists($this, $method)) { throw new UnknownUnitException($unit); } return $this->$method($date, $absolute, $utc); } /** * Get the difference in years * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInYears($date = null, bool $absolute = false, bool $utc = false): float { $start = $this; $end = $this->resolveCarbon($date); if ($utc) { $start = $start->avoidMutation()->utc(); $end = $end->avoidMutation()->utc(); } $ascending = ($start <= $end); $sign = $absolute || $ascending ? 1 : -1; if (!$ascending) { [$start, $end] = [$end, $start]; } $yearsDiff = (int) $start->diff($end, $absolute)->format('%r%y'); /** @var Carbon|CarbonImmutable $floorEnd */ $floorEnd = $start->avoidMutation()->addYears($yearsDiff); if ($floorEnd >= $end) { return $sign * $yearsDiff; } /** @var Carbon|CarbonImmutable $ceilEnd */ $ceilEnd = $start->avoidMutation()->addYears($yearsDiff + 1); $daysToFloor = $floorEnd->diffInDays($end); $daysToCeil = $end->diffInDays($ceilEnd); return $sign * ($yearsDiff + $daysToFloor / ($daysToCeil + $daysToFloor)); } /** * Get the difference in quarters. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInQuarters($date = null, bool $absolute = false, bool $utc = false): float { return $this->diffInMonths($date, $absolute, $utc) / static::MONTHS_PER_QUARTER; } /** * Get the difference in months. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInMonths($date = null, bool $absolute = false, bool $utc = false): float { $start = $this; $end = $this->resolveCarbon($date); // Compare using UTC if ($utc || ($end->timezoneName !== $start->timezoneName)) { $start = $start->avoidMutation()->utc(); $end = $end->avoidMutation()->utc(); } [$yearStart, $monthStart, $dayStart] = explode('-', $start->format('Y-m-dHisu')); [$yearEnd, $monthEnd, $dayEnd] = explode('-', $end->format('Y-m-dHisu')); $monthsDiff = (((int) $yearEnd) - ((int) $yearStart)) * static::MONTHS_PER_YEAR + ((int) $monthEnd) - ((int) $monthStart); if ($monthsDiff > 0) { $monthsDiff -= ($dayStart > $dayEnd ? 1 : 0); } elseif ($monthsDiff < 0) { $monthsDiff += ($dayStart < $dayEnd ? 1 : 0); } $ascending = ($start <= $end); $sign = $absolute || $ascending ? 1 : -1; $monthsDiff = abs($monthsDiff); if (!$ascending) { [$start, $end] = [$end, $start]; } /** @var Carbon|CarbonImmutable $floorEnd */ $floorEnd = $start->avoidMutation()->addMonths($monthsDiff); if ($floorEnd >= $end) { return $sign * $monthsDiff; } /** @var Carbon|CarbonImmutable $ceilEnd */ $ceilEnd = $start->avoidMutation()->addMonths($monthsDiff + 1); $daysToFloor = $floorEnd->diffInDays($end); $daysToCeil = $end->diffInDays($ceilEnd); return $sign * ($monthsDiff + $daysToFloor / ($daysToCeil + $daysToFloor)); } /** * Get the difference in weeks. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInWeeks($date = null, bool $absolute = false, bool $utc = false): float { return $this->diffInDays($date, $absolute, $utc) / static::DAYS_PER_WEEK; } /** * Get the difference in days. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInDays($date = null, bool $absolute = false, bool $utc = false): float { $date = $this->resolveCarbon($date); $current = $this; // Compare using UTC if ($utc || ($date->timezoneName !== $current->timezoneName)) { $date = $date->avoidMutation()->utc(); $current = $current->avoidMutation()->utc(); } $negative = ($date < $current); [$start, $end] = $negative ? [$date, $current] : [$current, $date]; $interval = $start->diffAsDateInterval($end); $daysA = $this->getIntervalDayDiff($interval); $floorEnd = $start->avoidMutation()->addDays($daysA); $daysB = $daysA + ($floorEnd <= $end ? 1 : -1); $ceilEnd = $start->avoidMutation()->addDays($daysB); $microsecondsBetween = $floorEnd->diffInMicroseconds($ceilEnd); $microsecondsToEnd = $floorEnd->diffInMicroseconds($end); return ($negative && !$absolute ? -1 : 1) * ($daysA * ($microsecondsBetween - $microsecondsToEnd) + $daysB * $microsecondsToEnd) / $microsecondsBetween; } /** * Get the difference in days using a filter closure. * * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInDaysFiltered(Closure $callback, $date = null, bool $absolute = false): int { return $this->diffFiltered(CarbonInterval::day(), $callback, $date, $absolute); } /** * Get the difference in hours using a filter closure. * * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInHoursFiltered(Closure $callback, $date = null, bool $absolute = false): int { return $this->diffFiltered(CarbonInterval::hour(), $callback, $date, $absolute); } /** * Get the difference by the given interval using a filter closure. * * @param CarbonInterval $ci An interval to traverse by * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffFiltered(CarbonInterval $ci, Closure $callback, $date = null, bool $absolute = false): int { $start = $this; $end = $this->resolveCarbon($date); $inverse = false; if ($end < $start) { $start = $end; $end = $this; $inverse = true; } $options = CarbonPeriod::EXCLUDE_END_DATE | ($this->isMutable() ? 0 : CarbonPeriod::IMMUTABLE); $diff = $ci->toPeriod($start, $end, $options)->filter($callback)->count(); return $inverse && !$absolute ? -$diff : $diff; } /** * Get the difference in weekdays. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInWeekdays($date = null, bool $absolute = false): int { return $this->diffInDaysFiltered( static fn (CarbonInterface $date) => $date->isWeekday(), $this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')), $absolute, ); } /** * Get the difference in weekend days using a filter. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInWeekendDays($date = null, bool $absolute = false): int { return $this->diffInDaysFiltered( static fn (CarbonInterface $date) => $date->isWeekend(), $this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')), $absolute, ); } /** * Get the difference in hours. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInHours($date = null, bool $absolute = false): float { return $this->diffInMinutes($date, $absolute) / static::MINUTES_PER_HOUR; } /** * Get the difference in minutes. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMinutes($date = null, bool $absolute = false): float { return $this->diffInSeconds($date, $absolute) / static::SECONDS_PER_MINUTE; } /** * Get the difference in seconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInSeconds($date = null, bool $absolute = false): float { return $this->diffInMilliseconds($date, $absolute) / static::MILLISECONDS_PER_SECOND; } /** * Get the difference in microseconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMicroseconds($date = null, bool $absolute = false): float { /** @var CarbonInterface $date */ $date = $this->resolveCarbon($date); $value = ($date->timestamp - $this->timestamp) * static::MICROSECONDS_PER_SECOND + $date->micro - $this->micro; return $absolute ? abs($value) : $value; } /** * Get the difference in milliseconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMilliseconds($date = null, bool $absolute = false): float { return $this->diffInMicroseconds($date, $absolute) / static::MICROSECONDS_PER_MILLISECOND; } /** * The number of seconds since midnight. * * @return float */ public function secondsSinceMidnight(): float { return $this->diffInSeconds($this->copy()->startOfDay(), true); } /** * The number of seconds until 23:59:59. * * @return float */ public function secondsUntilEndOfDay(): float { return $this->diffInSeconds($this->copy()->endOfDay(), true); } /** * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). * * @example * ``` * echo Carbon::tomorrow()->diffForHumans() . "\n"; * echo Carbon::tomorrow()->diffForHumans(['parts' => 2]) . "\n"; * echo Carbon::tomorrow()->diffForHumans(['parts' => 3, 'join' => true]) . "\n"; * echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday()) . "\n"; * echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday(), ['short' => true]) . "\n"; * ``` * * @param Carbon|DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'other' entry (see above) * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options */ public function diffForHumans($other = null, $syntax = null, $short = false, $parts = 1, $options = null): string { /* @var CarbonInterface $this */ if (\is_array($other)) { $other['syntax'] = \array_key_exists('syntax', $other) ? $other['syntax'] : $syntax; $syntax = $other; $other = $syntax['other'] ?? null; } $intSyntax = &$syntax; if (\is_array($syntax)) { $syntax['syntax'] = $syntax['syntax'] ?? null; $intSyntax = &$syntax['syntax']; } $intSyntax = (int) ($intSyntax ?? static::DIFF_RELATIVE_AUTO); $intSyntax = $intSyntax === static::DIFF_RELATIVE_AUTO && $other === null ? static::DIFF_RELATIVE_TO_NOW : $intSyntax; $parts = min(7, max(1, (int) $parts)); $skip = \is_array($syntax) ? ($syntax['skip'] ?? []) : []; $options ??= $this->localHumanDiffOptions ?? $this->transmitFactory( static fn () => static::getHumanDiffOptions(), ); return $this->diff($other, skip: (array) $skip)->forHumans($syntax, (bool) $short, $parts, $options); } /** * @alias diffForHumans * * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function from($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->diffForHumans($other, $syntax, $short, $parts, $options); } /** * @alias diffForHumans * * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). */ public function since($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->diffForHumans($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given (or now if null given) to current instance. * * When comparing a value in the past to default now: * 1 hour from now * 5 months from now * * When comparing a value in the future to default now: * 1 hour ago * 5 months ago * * When comparing a value in the past to another value: * 1 hour after * 5 months after * * When comparing a value in the future to another value: * 1 hour before * 5 months before * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function to($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { if (!$syntax && !$other) { $syntax = CarbonInterface::DIFF_RELATIVE_TO_NOW; } return $this->resolveCarbon($other)->diffForHumans($this, $syntax, $short, $parts, $options); } /** * @alias to * * Get the difference in a human readable format in the current locale from an other * instance given (or now if null given) to current instance. * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function until($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->to($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from current * instance to now. * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function fromNow($syntax = null, $short = false, $parts = 1, $options = null) { $other = null; if ($syntax instanceof DateTimeInterface) { [$other, $syntax, $short, $parts, $options] = array_pad(\func_get_args(), 5, null); } return $this->from($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given to now * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single part) * @param int $options human diff options * * @return string */ public function toNow($syntax = null, $short = false, $parts = 1, $options = null) { return $this->to(null, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given to now * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single part) * @param int $options human diff options * * @return string */ public function ago($syntax = null, $short = false, $parts = 1, $options = null) { $other = null; if ($syntax instanceof DateTimeInterface) { [$other, $syntax, $short, $parts, $options] = array_pad(\func_get_args(), 5, null); } return $this->from($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human-readable format in the current locale from current instance to another * instance given (or now if null given). * * @return string */ public function timespan($other = null, $timezone = null): string { if (\is_string($other)) { $other = $this->transmitFactory(static fn () => static::parse($other, $timezone)); } return $this->diffForHumans($other, [ 'join' => ', ', 'syntax' => CarbonInterface::DIFF_ABSOLUTE, 'parts' => INF, ]); } /** * Returns either day of week + time (e.g. "Last Friday at 3:30 PM") if reference time is within 7 days, * or a calendar date (e.g. "10/29/2017") otherwise. * * Language, date and time formats will change according to the current locale. * * @param Carbon|\DateTimeInterface|string|null $referenceTime * @param array $formats * * @return string */ public function calendar($referenceTime = null, array $formats = []) { /** @var CarbonInterface $current */ $current = $this->avoidMutation()->startOfDay(); /** @var CarbonInterface $other */ $other = $this->resolveCarbon($referenceTime)->avoidMutation()->setTimezone($this->getTimezone())->startOfDay(); $diff = $other->diffInDays($current, false); $format = $diff <= -static::DAYS_PER_WEEK ? 'sameElse' : ( $diff < -1 ? 'lastWeek' : ( $diff < 0 ? 'lastDay' : ( $diff < 1 ? 'sameDay' : ( $diff < 2 ? 'nextDay' : ( $diff < static::DAYS_PER_WEEK ? 'nextWeek' : 'sameElse' ) ) ) ) ); $format = array_merge($this->getCalendarFormats(), $formats)[$format]; if ($format instanceof Closure) { $format = $format($current, $other) ?? ''; } return $this->isoFormat((string) $format); } private function getIntervalDayDiff(DateInterval $interval): int { return (int) $interval->format('%r%a'); } }
PHP
{ "end_line": 334, "name": "diffFiltered", "signature": "public function diffFiltered(CarbonInterval $ci, Closure $callback, $date = null, bool $absolute = false): int", "start_line": 318 }
{ "class_name": "Difference", "class_signature": "trait Difference", "namespace": "Carbon\\Traits" }
diffForHumans
Carbon/src/Carbon/Traits/Difference.php
public function diffForHumans($other = null, $syntax = null, $short = false, $parts = 1, $options = null): string { /* @var CarbonInterface $this */ if (\is_array($other)) { $other['syntax'] = \array_key_exists('syntax', $other) ? $other['syntax'] : $syntax; $syntax = $other; $other = $syntax['other'] ?? null; } $intSyntax = &$syntax; if (\is_array($syntax)) { $syntax['syntax'] = $syntax['syntax'] ?? null; $intSyntax = &$syntax['syntax']; } $intSyntax = (int) ($intSyntax ?? static::DIFF_RELATIVE_AUTO); $intSyntax = $intSyntax === static::DIFF_RELATIVE_AUTO && $other === null ? static::DIFF_RELATIVE_TO_NOW : $intSyntax; $parts = min(7, max(1, (int) $parts)); $skip = \is_array($syntax) ? ($syntax['skip'] ?? []) : []; $options ??= $this->localHumanDiffOptions ?? $this->transmitFactory( static fn () => static::getHumanDiffOptions(), ); return $this->diff($other, skip: (array) $skip)->forHumans($syntax, (bool) $short, $parts, $options); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Carbon\Exceptions\UnknownUnitException; use Carbon\Unit; use Closure; use DateInterval; use DateTimeInterface; /** * Trait Difference. * * Depends on the following methods: * * @method bool lessThan($date) * @method static copy() * @method static resolveCarbon($date = null) */ trait Difference { /** * Get the difference as a DateInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return DateInterval */ public function diffAsDateInterval($date = null, bool $absolute = false): DateInterval { $other = $this->resolveCarbon($date); // Work-around for https://bugs.php.net/bug.php?id=81458 // It was initially introduced for https://bugs.php.net/bug.php?id=80998 // The very specific case of 80998 was fixed in PHP 8.1beta3, but it introduced 81458 // So we still need to keep this for now if ($other->tz !== $this->tz) { $other = $other->avoidMutation()->setTimezone($this->tz); } return parent::diff($other, $absolute); } /** * Get the difference as a CarbonInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return CarbonInterval */ public function diffAsCarbonInterval($date = null, bool $absolute = false, array $skip = []): CarbonInterval { return CarbonInterval::diff($this, $this->resolveCarbon($date), $absolute, $skip) ->setLocalTranslator($this->getLocalTranslator()); } /** * @alias diffAsCarbonInterval * * Get the difference as a DateInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return CarbonInterval */ public function diff($date = null, bool $absolute = false, array $skip = []): CarbonInterval { return $this->diffAsCarbonInterval($date, $absolute, $skip); } /** * @param Unit|string $unit microsecond, millisecond, second, minute, * hour, day, week, month, quarter, year, * century, millennium * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInUnit(Unit|string $unit, $date = null, bool $absolute = false, bool $utc = false): float { $unit = static::pluralUnit($unit instanceof Unit ? $unit->value : rtrim($unit, 'z')); $method = 'diffIn'.$unit; if (!method_exists($this, $method)) { throw new UnknownUnitException($unit); } return $this->$method($date, $absolute, $utc); } /** * Get the difference in years * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInYears($date = null, bool $absolute = false, bool $utc = false): float { $start = $this; $end = $this->resolveCarbon($date); if ($utc) { $start = $start->avoidMutation()->utc(); $end = $end->avoidMutation()->utc(); } $ascending = ($start <= $end); $sign = $absolute || $ascending ? 1 : -1; if (!$ascending) { [$start, $end] = [$end, $start]; } $yearsDiff = (int) $start->diff($end, $absolute)->format('%r%y'); /** @var Carbon|CarbonImmutable $floorEnd */ $floorEnd = $start->avoidMutation()->addYears($yearsDiff); if ($floorEnd >= $end) { return $sign * $yearsDiff; } /** @var Carbon|CarbonImmutable $ceilEnd */ $ceilEnd = $start->avoidMutation()->addYears($yearsDiff + 1); $daysToFloor = $floorEnd->diffInDays($end); $daysToCeil = $end->diffInDays($ceilEnd); return $sign * ($yearsDiff + $daysToFloor / ($daysToCeil + $daysToFloor)); } /** * Get the difference in quarters. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInQuarters($date = null, bool $absolute = false, bool $utc = false): float { return $this->diffInMonths($date, $absolute, $utc) / static::MONTHS_PER_QUARTER; } /** * Get the difference in months. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInMonths($date = null, bool $absolute = false, bool $utc = false): float { $start = $this; $end = $this->resolveCarbon($date); // Compare using UTC if ($utc || ($end->timezoneName !== $start->timezoneName)) { $start = $start->avoidMutation()->utc(); $end = $end->avoidMutation()->utc(); } [$yearStart, $monthStart, $dayStart] = explode('-', $start->format('Y-m-dHisu')); [$yearEnd, $monthEnd, $dayEnd] = explode('-', $end->format('Y-m-dHisu')); $monthsDiff = (((int) $yearEnd) - ((int) $yearStart)) * static::MONTHS_PER_YEAR + ((int) $monthEnd) - ((int) $monthStart); if ($monthsDiff > 0) { $monthsDiff -= ($dayStart > $dayEnd ? 1 : 0); } elseif ($monthsDiff < 0) { $monthsDiff += ($dayStart < $dayEnd ? 1 : 0); } $ascending = ($start <= $end); $sign = $absolute || $ascending ? 1 : -1; $monthsDiff = abs($monthsDiff); if (!$ascending) { [$start, $end] = [$end, $start]; } /** @var Carbon|CarbonImmutable $floorEnd */ $floorEnd = $start->avoidMutation()->addMonths($monthsDiff); if ($floorEnd >= $end) { return $sign * $monthsDiff; } /** @var Carbon|CarbonImmutable $ceilEnd */ $ceilEnd = $start->avoidMutation()->addMonths($monthsDiff + 1); $daysToFloor = $floorEnd->diffInDays($end); $daysToCeil = $end->diffInDays($ceilEnd); return $sign * ($monthsDiff + $daysToFloor / ($daysToCeil + $daysToFloor)); } /** * Get the difference in weeks. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInWeeks($date = null, bool $absolute = false, bool $utc = false): float { return $this->diffInDays($date, $absolute, $utc) / static::DAYS_PER_WEEK; } /** * Get the difference in days. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInDays($date = null, bool $absolute = false, bool $utc = false): float { $date = $this->resolveCarbon($date); $current = $this; // Compare using UTC if ($utc || ($date->timezoneName !== $current->timezoneName)) { $date = $date->avoidMutation()->utc(); $current = $current->avoidMutation()->utc(); } $negative = ($date < $current); [$start, $end] = $negative ? [$date, $current] : [$current, $date]; $interval = $start->diffAsDateInterval($end); $daysA = $this->getIntervalDayDiff($interval); $floorEnd = $start->avoidMutation()->addDays($daysA); $daysB = $daysA + ($floorEnd <= $end ? 1 : -1); $ceilEnd = $start->avoidMutation()->addDays($daysB); $microsecondsBetween = $floorEnd->diffInMicroseconds($ceilEnd); $microsecondsToEnd = $floorEnd->diffInMicroseconds($end); return ($negative && !$absolute ? -1 : 1) * ($daysA * ($microsecondsBetween - $microsecondsToEnd) + $daysB * $microsecondsToEnd) / $microsecondsBetween; } /** * Get the difference in days using a filter closure. * * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInDaysFiltered(Closure $callback, $date = null, bool $absolute = false): int { return $this->diffFiltered(CarbonInterval::day(), $callback, $date, $absolute); } /** * Get the difference in hours using a filter closure. * * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInHoursFiltered(Closure $callback, $date = null, bool $absolute = false): int { return $this->diffFiltered(CarbonInterval::hour(), $callback, $date, $absolute); } /** * Get the difference by the given interval using a filter closure. * * @param CarbonInterval $ci An interval to traverse by * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffFiltered(CarbonInterval $ci, Closure $callback, $date = null, bool $absolute = false): int { $start = $this; $end = $this->resolveCarbon($date); $inverse = false; if ($end < $start) { $start = $end; $end = $this; $inverse = true; } $options = CarbonPeriod::EXCLUDE_END_DATE | ($this->isMutable() ? 0 : CarbonPeriod::IMMUTABLE); $diff = $ci->toPeriod($start, $end, $options)->filter($callback)->count(); return $inverse && !$absolute ? -$diff : $diff; } /** * Get the difference in weekdays. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInWeekdays($date = null, bool $absolute = false): int { return $this->diffInDaysFiltered( static fn (CarbonInterface $date) => $date->isWeekday(), $this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')), $absolute, ); } /** * Get the difference in weekend days using a filter. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInWeekendDays($date = null, bool $absolute = false): int { return $this->diffInDaysFiltered( static fn (CarbonInterface $date) => $date->isWeekend(), $this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')), $absolute, ); } /** * Get the difference in hours. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInHours($date = null, bool $absolute = false): float { return $this->diffInMinutes($date, $absolute) / static::MINUTES_PER_HOUR; } /** * Get the difference in minutes. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMinutes($date = null, bool $absolute = false): float { return $this->diffInSeconds($date, $absolute) / static::SECONDS_PER_MINUTE; } /** * Get the difference in seconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInSeconds($date = null, bool $absolute = false): float { return $this->diffInMilliseconds($date, $absolute) / static::MILLISECONDS_PER_SECOND; } /** * Get the difference in microseconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMicroseconds($date = null, bool $absolute = false): float { /** @var CarbonInterface $date */ $date = $this->resolveCarbon($date); $value = ($date->timestamp - $this->timestamp) * static::MICROSECONDS_PER_SECOND + $date->micro - $this->micro; return $absolute ? abs($value) : $value; } /** * Get the difference in milliseconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMilliseconds($date = null, bool $absolute = false): float { return $this->diffInMicroseconds($date, $absolute) / static::MICROSECONDS_PER_MILLISECOND; } /** * The number of seconds since midnight. * * @return float */ public function secondsSinceMidnight(): float { return $this->diffInSeconds($this->copy()->startOfDay(), true); } /** * The number of seconds until 23:59:59. * * @return float */ public function secondsUntilEndOfDay(): float { return $this->diffInSeconds($this->copy()->endOfDay(), true); } /** * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). * * @example * ``` * echo Carbon::tomorrow()->diffForHumans() . "\n"; * echo Carbon::tomorrow()->diffForHumans(['parts' => 2]) . "\n"; * echo Carbon::tomorrow()->diffForHumans(['parts' => 3, 'join' => true]) . "\n"; * echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday()) . "\n"; * echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday(), ['short' => true]) . "\n"; * ``` * * @param Carbon|DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'other' entry (see above) * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options */ public function diffForHumans($other = null, $syntax = null, $short = false, $parts = 1, $options = null): string { /* @var CarbonInterface $this */ if (\is_array($other)) { $other['syntax'] = \array_key_exists('syntax', $other) ? $other['syntax'] : $syntax; $syntax = $other; $other = $syntax['other'] ?? null; } $intSyntax = &$syntax; if (\is_array($syntax)) { $syntax['syntax'] = $syntax['syntax'] ?? null; $intSyntax = &$syntax['syntax']; } $intSyntax = (int) ($intSyntax ?? static::DIFF_RELATIVE_AUTO); $intSyntax = $intSyntax === static::DIFF_RELATIVE_AUTO && $other === null ? static::DIFF_RELATIVE_TO_NOW : $intSyntax; $parts = min(7, max(1, (int) $parts)); $skip = \is_array($syntax) ? ($syntax['skip'] ?? []) : []; $options ??= $this->localHumanDiffOptions ?? $this->transmitFactory( static fn () => static::getHumanDiffOptions(), ); return $this->diff($other, skip: (array) $skip)->forHumans($syntax, (bool) $short, $parts, $options); } /** * @alias diffForHumans * * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function from($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->diffForHumans($other, $syntax, $short, $parts, $options); } /** * @alias diffForHumans * * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). */ public function since($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->diffForHumans($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given (or now if null given) to current instance. * * When comparing a value in the past to default now: * 1 hour from now * 5 months from now * * When comparing a value in the future to default now: * 1 hour ago * 5 months ago * * When comparing a value in the past to another value: * 1 hour after * 5 months after * * When comparing a value in the future to another value: * 1 hour before * 5 months before * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function to($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { if (!$syntax && !$other) { $syntax = CarbonInterface::DIFF_RELATIVE_TO_NOW; } return $this->resolveCarbon($other)->diffForHumans($this, $syntax, $short, $parts, $options); } /** * @alias to * * Get the difference in a human readable format in the current locale from an other * instance given (or now if null given) to current instance. * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function until($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->to($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from current * instance to now. * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function fromNow($syntax = null, $short = false, $parts = 1, $options = null) { $other = null; if ($syntax instanceof DateTimeInterface) { [$other, $syntax, $short, $parts, $options] = array_pad(\func_get_args(), 5, null); } return $this->from($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given to now * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single part) * @param int $options human diff options * * @return string */ public function toNow($syntax = null, $short = false, $parts = 1, $options = null) { return $this->to(null, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given to now * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single part) * @param int $options human diff options * * @return string */ public function ago($syntax = null, $short = false, $parts = 1, $options = null) { $other = null; if ($syntax instanceof DateTimeInterface) { [$other, $syntax, $short, $parts, $options] = array_pad(\func_get_args(), 5, null); } return $this->from($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human-readable format in the current locale from current instance to another * instance given (or now if null given). * * @return string */ public function timespan($other = null, $timezone = null): string { if (\is_string($other)) { $other = $this->transmitFactory(static fn () => static::parse($other, $timezone)); } return $this->diffForHumans($other, [ 'join' => ', ', 'syntax' => CarbonInterface::DIFF_ABSOLUTE, 'parts' => INF, ]); } /** * Returns either day of week + time (e.g. "Last Friday at 3:30 PM") if reference time is within 7 days, * or a calendar date (e.g. "10/29/2017") otherwise. * * Language, date and time formats will change according to the current locale. * * @param Carbon|\DateTimeInterface|string|null $referenceTime * @param array $formats * * @return string */ public function calendar($referenceTime = null, array $formats = []) { /** @var CarbonInterface $current */ $current = $this->avoidMutation()->startOfDay(); /** @var CarbonInterface $other */ $other = $this->resolveCarbon($referenceTime)->avoidMutation()->setTimezone($this->getTimezone())->startOfDay(); $diff = $other->diffInDays($current, false); $format = $diff <= -static::DAYS_PER_WEEK ? 'sameElse' : ( $diff < -1 ? 'lastWeek' : ( $diff < 0 ? 'lastDay' : ( $diff < 1 ? 'sameDay' : ( $diff < 2 ? 'nextDay' : ( $diff < static::DAYS_PER_WEEK ? 'nextWeek' : 'sameElse' ) ) ) ) ); $format = array_merge($this->getCalendarFormats(), $formats)[$format]; if ($format instanceof Closure) { $format = $format($current, $other) ?? ''; } return $this->isoFormat((string) $format); } private function getIntervalDayDiff(DateInterval $interval): int { return (int) $interval->format('%r%a'); } }
PHP
{ "end_line": 536, "name": "diffForHumans", "signature": "public function diffForHumans($other = null, $syntax = null, $short = false, $parts = 1, $options = null): string", "start_line": 510 }
{ "class_name": "Difference", "class_signature": "trait Difference", "namespace": "Carbon\\Traits" }
timespan
Carbon/src/Carbon/Traits/Difference.php
public function timespan($other = null, $timezone = null): string { if (\is_string($other)) { $other = $this->transmitFactory(static fn () => static::parse($other, $timezone)); } return $this->diffForHumans($other, [ 'join' => ', ', 'syntax' => CarbonInterface::DIFF_ABSOLUTE, 'parts' => INF, ]); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Carbon\Exceptions\UnknownUnitException; use Carbon\Unit; use Closure; use DateInterval; use DateTimeInterface; /** * Trait Difference. * * Depends on the following methods: * * @method bool lessThan($date) * @method static copy() * @method static resolveCarbon($date = null) */ trait Difference { /** * Get the difference as a DateInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return DateInterval */ public function diffAsDateInterval($date = null, bool $absolute = false): DateInterval { $other = $this->resolveCarbon($date); // Work-around for https://bugs.php.net/bug.php?id=81458 // It was initially introduced for https://bugs.php.net/bug.php?id=80998 // The very specific case of 80998 was fixed in PHP 8.1beta3, but it introduced 81458 // So we still need to keep this for now if ($other->tz !== $this->tz) { $other = $other->avoidMutation()->setTimezone($this->tz); } return parent::diff($other, $absolute); } /** * Get the difference as a CarbonInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return CarbonInterval */ public function diffAsCarbonInterval($date = null, bool $absolute = false, array $skip = []): CarbonInterval { return CarbonInterval::diff($this, $this->resolveCarbon($date), $absolute, $skip) ->setLocalTranslator($this->getLocalTranslator()); } /** * @alias diffAsCarbonInterval * * Get the difference as a DateInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return CarbonInterval */ public function diff($date = null, bool $absolute = false, array $skip = []): CarbonInterval { return $this->diffAsCarbonInterval($date, $absolute, $skip); } /** * @param Unit|string $unit microsecond, millisecond, second, minute, * hour, day, week, month, quarter, year, * century, millennium * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInUnit(Unit|string $unit, $date = null, bool $absolute = false, bool $utc = false): float { $unit = static::pluralUnit($unit instanceof Unit ? $unit->value : rtrim($unit, 'z')); $method = 'diffIn'.$unit; if (!method_exists($this, $method)) { throw new UnknownUnitException($unit); } return $this->$method($date, $absolute, $utc); } /** * Get the difference in years * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInYears($date = null, bool $absolute = false, bool $utc = false): float { $start = $this; $end = $this->resolveCarbon($date); if ($utc) { $start = $start->avoidMutation()->utc(); $end = $end->avoidMutation()->utc(); } $ascending = ($start <= $end); $sign = $absolute || $ascending ? 1 : -1; if (!$ascending) { [$start, $end] = [$end, $start]; } $yearsDiff = (int) $start->diff($end, $absolute)->format('%r%y'); /** @var Carbon|CarbonImmutable $floorEnd */ $floorEnd = $start->avoidMutation()->addYears($yearsDiff); if ($floorEnd >= $end) { return $sign * $yearsDiff; } /** @var Carbon|CarbonImmutable $ceilEnd */ $ceilEnd = $start->avoidMutation()->addYears($yearsDiff + 1); $daysToFloor = $floorEnd->diffInDays($end); $daysToCeil = $end->diffInDays($ceilEnd); return $sign * ($yearsDiff + $daysToFloor / ($daysToCeil + $daysToFloor)); } /** * Get the difference in quarters. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInQuarters($date = null, bool $absolute = false, bool $utc = false): float { return $this->diffInMonths($date, $absolute, $utc) / static::MONTHS_PER_QUARTER; } /** * Get the difference in months. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInMonths($date = null, bool $absolute = false, bool $utc = false): float { $start = $this; $end = $this->resolveCarbon($date); // Compare using UTC if ($utc || ($end->timezoneName !== $start->timezoneName)) { $start = $start->avoidMutation()->utc(); $end = $end->avoidMutation()->utc(); } [$yearStart, $monthStart, $dayStart] = explode('-', $start->format('Y-m-dHisu')); [$yearEnd, $monthEnd, $dayEnd] = explode('-', $end->format('Y-m-dHisu')); $monthsDiff = (((int) $yearEnd) - ((int) $yearStart)) * static::MONTHS_PER_YEAR + ((int) $monthEnd) - ((int) $monthStart); if ($monthsDiff > 0) { $monthsDiff -= ($dayStart > $dayEnd ? 1 : 0); } elseif ($monthsDiff < 0) { $monthsDiff += ($dayStart < $dayEnd ? 1 : 0); } $ascending = ($start <= $end); $sign = $absolute || $ascending ? 1 : -1; $monthsDiff = abs($monthsDiff); if (!$ascending) { [$start, $end] = [$end, $start]; } /** @var Carbon|CarbonImmutable $floorEnd */ $floorEnd = $start->avoidMutation()->addMonths($monthsDiff); if ($floorEnd >= $end) { return $sign * $monthsDiff; } /** @var Carbon|CarbonImmutable $ceilEnd */ $ceilEnd = $start->avoidMutation()->addMonths($monthsDiff + 1); $daysToFloor = $floorEnd->diffInDays($end); $daysToCeil = $end->diffInDays($ceilEnd); return $sign * ($monthsDiff + $daysToFloor / ($daysToCeil + $daysToFloor)); } /** * Get the difference in weeks. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInWeeks($date = null, bool $absolute = false, bool $utc = false): float { return $this->diffInDays($date, $absolute, $utc) / static::DAYS_PER_WEEK; } /** * Get the difference in days. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInDays($date = null, bool $absolute = false, bool $utc = false): float { $date = $this->resolveCarbon($date); $current = $this; // Compare using UTC if ($utc || ($date->timezoneName !== $current->timezoneName)) { $date = $date->avoidMutation()->utc(); $current = $current->avoidMutation()->utc(); } $negative = ($date < $current); [$start, $end] = $negative ? [$date, $current] : [$current, $date]; $interval = $start->diffAsDateInterval($end); $daysA = $this->getIntervalDayDiff($interval); $floorEnd = $start->avoidMutation()->addDays($daysA); $daysB = $daysA + ($floorEnd <= $end ? 1 : -1); $ceilEnd = $start->avoidMutation()->addDays($daysB); $microsecondsBetween = $floorEnd->diffInMicroseconds($ceilEnd); $microsecondsToEnd = $floorEnd->diffInMicroseconds($end); return ($negative && !$absolute ? -1 : 1) * ($daysA * ($microsecondsBetween - $microsecondsToEnd) + $daysB * $microsecondsToEnd) / $microsecondsBetween; } /** * Get the difference in days using a filter closure. * * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInDaysFiltered(Closure $callback, $date = null, bool $absolute = false): int { return $this->diffFiltered(CarbonInterval::day(), $callback, $date, $absolute); } /** * Get the difference in hours using a filter closure. * * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInHoursFiltered(Closure $callback, $date = null, bool $absolute = false): int { return $this->diffFiltered(CarbonInterval::hour(), $callback, $date, $absolute); } /** * Get the difference by the given interval using a filter closure. * * @param CarbonInterval $ci An interval to traverse by * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffFiltered(CarbonInterval $ci, Closure $callback, $date = null, bool $absolute = false): int { $start = $this; $end = $this->resolveCarbon($date); $inverse = false; if ($end < $start) { $start = $end; $end = $this; $inverse = true; } $options = CarbonPeriod::EXCLUDE_END_DATE | ($this->isMutable() ? 0 : CarbonPeriod::IMMUTABLE); $diff = $ci->toPeriod($start, $end, $options)->filter($callback)->count(); return $inverse && !$absolute ? -$diff : $diff; } /** * Get the difference in weekdays. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInWeekdays($date = null, bool $absolute = false): int { return $this->diffInDaysFiltered( static fn (CarbonInterface $date) => $date->isWeekday(), $this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')), $absolute, ); } /** * Get the difference in weekend days using a filter. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInWeekendDays($date = null, bool $absolute = false): int { return $this->diffInDaysFiltered( static fn (CarbonInterface $date) => $date->isWeekend(), $this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')), $absolute, ); } /** * Get the difference in hours. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInHours($date = null, bool $absolute = false): float { return $this->diffInMinutes($date, $absolute) / static::MINUTES_PER_HOUR; } /** * Get the difference in minutes. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMinutes($date = null, bool $absolute = false): float { return $this->diffInSeconds($date, $absolute) / static::SECONDS_PER_MINUTE; } /** * Get the difference in seconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInSeconds($date = null, bool $absolute = false): float { return $this->diffInMilliseconds($date, $absolute) / static::MILLISECONDS_PER_SECOND; } /** * Get the difference in microseconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMicroseconds($date = null, bool $absolute = false): float { /** @var CarbonInterface $date */ $date = $this->resolveCarbon($date); $value = ($date->timestamp - $this->timestamp) * static::MICROSECONDS_PER_SECOND + $date->micro - $this->micro; return $absolute ? abs($value) : $value; } /** * Get the difference in milliseconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMilliseconds($date = null, bool $absolute = false): float { return $this->diffInMicroseconds($date, $absolute) / static::MICROSECONDS_PER_MILLISECOND; } /** * The number of seconds since midnight. * * @return float */ public function secondsSinceMidnight(): float { return $this->diffInSeconds($this->copy()->startOfDay(), true); } /** * The number of seconds until 23:59:59. * * @return float */ public function secondsUntilEndOfDay(): float { return $this->diffInSeconds($this->copy()->endOfDay(), true); } /** * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). * * @example * ``` * echo Carbon::tomorrow()->diffForHumans() . "\n"; * echo Carbon::tomorrow()->diffForHumans(['parts' => 2]) . "\n"; * echo Carbon::tomorrow()->diffForHumans(['parts' => 3, 'join' => true]) . "\n"; * echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday()) . "\n"; * echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday(), ['short' => true]) . "\n"; * ``` * * @param Carbon|DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'other' entry (see above) * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options */ public function diffForHumans($other = null, $syntax = null, $short = false, $parts = 1, $options = null): string { /* @var CarbonInterface $this */ if (\is_array($other)) { $other['syntax'] = \array_key_exists('syntax', $other) ? $other['syntax'] : $syntax; $syntax = $other; $other = $syntax['other'] ?? null; } $intSyntax = &$syntax; if (\is_array($syntax)) { $syntax['syntax'] = $syntax['syntax'] ?? null; $intSyntax = &$syntax['syntax']; } $intSyntax = (int) ($intSyntax ?? static::DIFF_RELATIVE_AUTO); $intSyntax = $intSyntax === static::DIFF_RELATIVE_AUTO && $other === null ? static::DIFF_RELATIVE_TO_NOW : $intSyntax; $parts = min(7, max(1, (int) $parts)); $skip = \is_array($syntax) ? ($syntax['skip'] ?? []) : []; $options ??= $this->localHumanDiffOptions ?? $this->transmitFactory( static fn () => static::getHumanDiffOptions(), ); return $this->diff($other, skip: (array) $skip)->forHumans($syntax, (bool) $short, $parts, $options); } /** * @alias diffForHumans * * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function from($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->diffForHumans($other, $syntax, $short, $parts, $options); } /** * @alias diffForHumans * * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). */ public function since($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->diffForHumans($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given (or now if null given) to current instance. * * When comparing a value in the past to default now: * 1 hour from now * 5 months from now * * When comparing a value in the future to default now: * 1 hour ago * 5 months ago * * When comparing a value in the past to another value: * 1 hour after * 5 months after * * When comparing a value in the future to another value: * 1 hour before * 5 months before * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function to($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { if (!$syntax && !$other) { $syntax = CarbonInterface::DIFF_RELATIVE_TO_NOW; } return $this->resolveCarbon($other)->diffForHumans($this, $syntax, $short, $parts, $options); } /** * @alias to * * Get the difference in a human readable format in the current locale from an other * instance given (or now if null given) to current instance. * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function until($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->to($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from current * instance to now. * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function fromNow($syntax = null, $short = false, $parts = 1, $options = null) { $other = null; if ($syntax instanceof DateTimeInterface) { [$other, $syntax, $short, $parts, $options] = array_pad(\func_get_args(), 5, null); } return $this->from($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given to now * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single part) * @param int $options human diff options * * @return string */ public function toNow($syntax = null, $short = false, $parts = 1, $options = null) { return $this->to(null, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given to now * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single part) * @param int $options human diff options * * @return string */ public function ago($syntax = null, $short = false, $parts = 1, $options = null) { $other = null; if ($syntax instanceof DateTimeInterface) { [$other, $syntax, $short, $parts, $options] = array_pad(\func_get_args(), 5, null); } return $this->from($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human-readable format in the current locale from current instance to another * instance given (or now if null given). * * @return string */ public function timespan($other = null, $timezone = null): string { if (\is_string($other)) { $other = $this->transmitFactory(static fn () => static::parse($other, $timezone)); } return $this->diffForHumans($other, [ 'join' => ', ', 'syntax' => CarbonInterface::DIFF_ABSOLUTE, 'parts' => INF, ]); } /** * Returns either day of week + time (e.g. "Last Friday at 3:30 PM") if reference time is within 7 days, * or a calendar date (e.g. "10/29/2017") otherwise. * * Language, date and time formats will change according to the current locale. * * @param Carbon|\DateTimeInterface|string|null $referenceTime * @param array $formats * * @return string */ public function calendar($referenceTime = null, array $formats = []) { /** @var CarbonInterface $current */ $current = $this->avoidMutation()->startOfDay(); /** @var CarbonInterface $other */ $other = $this->resolveCarbon($referenceTime)->avoidMutation()->setTimezone($this->getTimezone())->startOfDay(); $diff = $other->diffInDays($current, false); $format = $diff <= -static::DAYS_PER_WEEK ? 'sameElse' : ( $diff < -1 ? 'lastWeek' : ( $diff < 0 ? 'lastDay' : ( $diff < 1 ? 'sameDay' : ( $diff < 2 ? 'nextDay' : ( $diff < static::DAYS_PER_WEEK ? 'nextWeek' : 'sameElse' ) ) ) ) ); $format = array_merge($this->getCalendarFormats(), $formats)[$format]; if ($format instanceof Closure) { $format = $format($current, $other) ?? ''; } return $this->isoFormat((string) $format); } private function getIntervalDayDiff(DateInterval $interval): int { return (int) $interval->format('%r%a'); } }
PHP
{ "end_line": 812, "name": "timespan", "signature": "public function timespan($other = null, $timezone = null): string", "start_line": 801 }
{ "class_name": "Difference", "class_signature": "trait Difference", "namespace": "Carbon\\Traits" }
calendar
Carbon/src/Carbon/Traits/Difference.php
public function calendar($referenceTime = null, array $formats = []) { /** @var CarbonInterface $current */ $current = $this->avoidMutation()->startOfDay(); /** @var CarbonInterface $other */ $other = $this->resolveCarbon($referenceTime)->avoidMutation()->setTimezone($this->getTimezone())->startOfDay(); $diff = $other->diffInDays($current, false); $format = $diff <= -static::DAYS_PER_WEEK ? 'sameElse' : ( $diff < -1 ? 'lastWeek' : ( $diff < 0 ? 'lastDay' : ( $diff < 1 ? 'sameDay' : ( $diff < 2 ? 'nextDay' : ( $diff < static::DAYS_PER_WEEK ? 'nextWeek' : 'sameElse' ) ) ) ) ); $format = array_merge($this->getCalendarFormats(), $formats)[$format]; if ($format instanceof Closure) { $format = $format($current, $other) ?? ''; } return $this->isoFormat((string) $format); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Carbon\CarbonInterval; use Carbon\CarbonPeriod; use Carbon\Exceptions\UnknownUnitException; use Carbon\Unit; use Closure; use DateInterval; use DateTimeInterface; /** * Trait Difference. * * Depends on the following methods: * * @method bool lessThan($date) * @method static copy() * @method static resolveCarbon($date = null) */ trait Difference { /** * Get the difference as a DateInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return DateInterval */ public function diffAsDateInterval($date = null, bool $absolute = false): DateInterval { $other = $this->resolveCarbon($date); // Work-around for https://bugs.php.net/bug.php?id=81458 // It was initially introduced for https://bugs.php.net/bug.php?id=80998 // The very specific case of 80998 was fixed in PHP 8.1beta3, but it introduced 81458 // So we still need to keep this for now if ($other->tz !== $this->tz) { $other = $other->avoidMutation()->setTimezone($this->tz); } return parent::diff($other, $absolute); } /** * Get the difference as a CarbonInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return CarbonInterval */ public function diffAsCarbonInterval($date = null, bool $absolute = false, array $skip = []): CarbonInterval { return CarbonInterval::diff($this, $this->resolveCarbon($date), $absolute, $skip) ->setLocalTranslator($this->getLocalTranslator()); } /** * @alias diffAsCarbonInterval * * Get the difference as a DateInterval instance. * Return relative interval (negative if $absolute flag is not set to true and the given date is before * current one). * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return CarbonInterval */ public function diff($date = null, bool $absolute = false, array $skip = []): CarbonInterval { return $this->diffAsCarbonInterval($date, $absolute, $skip); } /** * @param Unit|string $unit microsecond, millisecond, second, minute, * hour, day, week, month, quarter, year, * century, millennium * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInUnit(Unit|string $unit, $date = null, bool $absolute = false, bool $utc = false): float { $unit = static::pluralUnit($unit instanceof Unit ? $unit->value : rtrim($unit, 'z')); $method = 'diffIn'.$unit; if (!method_exists($this, $method)) { throw new UnknownUnitException($unit); } return $this->$method($date, $absolute, $utc); } /** * Get the difference in years * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInYears($date = null, bool $absolute = false, bool $utc = false): float { $start = $this; $end = $this->resolveCarbon($date); if ($utc) { $start = $start->avoidMutation()->utc(); $end = $end->avoidMutation()->utc(); } $ascending = ($start <= $end); $sign = $absolute || $ascending ? 1 : -1; if (!$ascending) { [$start, $end] = [$end, $start]; } $yearsDiff = (int) $start->diff($end, $absolute)->format('%r%y'); /** @var Carbon|CarbonImmutable $floorEnd */ $floorEnd = $start->avoidMutation()->addYears($yearsDiff); if ($floorEnd >= $end) { return $sign * $yearsDiff; } /** @var Carbon|CarbonImmutable $ceilEnd */ $ceilEnd = $start->avoidMutation()->addYears($yearsDiff + 1); $daysToFloor = $floorEnd->diffInDays($end); $daysToCeil = $end->diffInDays($ceilEnd); return $sign * ($yearsDiff + $daysToFloor / ($daysToCeil + $daysToFloor)); } /** * Get the difference in quarters. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInQuarters($date = null, bool $absolute = false, bool $utc = false): float { return $this->diffInMonths($date, $absolute, $utc) / static::MONTHS_PER_QUARTER; } /** * Get the difference in months. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInMonths($date = null, bool $absolute = false, bool $utc = false): float { $start = $this; $end = $this->resolveCarbon($date); // Compare using UTC if ($utc || ($end->timezoneName !== $start->timezoneName)) { $start = $start->avoidMutation()->utc(); $end = $end->avoidMutation()->utc(); } [$yearStart, $monthStart, $dayStart] = explode('-', $start->format('Y-m-dHisu')); [$yearEnd, $monthEnd, $dayEnd] = explode('-', $end->format('Y-m-dHisu')); $monthsDiff = (((int) $yearEnd) - ((int) $yearStart)) * static::MONTHS_PER_YEAR + ((int) $monthEnd) - ((int) $monthStart); if ($monthsDiff > 0) { $monthsDiff -= ($dayStart > $dayEnd ? 1 : 0); } elseif ($monthsDiff < 0) { $monthsDiff += ($dayStart < $dayEnd ? 1 : 0); } $ascending = ($start <= $end); $sign = $absolute || $ascending ? 1 : -1; $monthsDiff = abs($monthsDiff); if (!$ascending) { [$start, $end] = [$end, $start]; } /** @var Carbon|CarbonImmutable $floorEnd */ $floorEnd = $start->avoidMutation()->addMonths($monthsDiff); if ($floorEnd >= $end) { return $sign * $monthsDiff; } /** @var Carbon|CarbonImmutable $ceilEnd */ $ceilEnd = $start->avoidMutation()->addMonths($monthsDiff + 1); $daysToFloor = $floorEnd->diffInDays($end); $daysToCeil = $end->diffInDays($ceilEnd); return $sign * ($monthsDiff + $daysToFloor / ($daysToCeil + $daysToFloor)); } /** * Get the difference in weeks. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInWeeks($date = null, bool $absolute = false, bool $utc = false): float { return $this->diffInDays($date, $absolute, $utc) / static::DAYS_PER_WEEK; } /** * Get the difference in days. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * @param bool $utc Always convert dates to UTC before comparing (if not set, it will do it only if timezones are different) * * @return float */ public function diffInDays($date = null, bool $absolute = false, bool $utc = false): float { $date = $this->resolveCarbon($date); $current = $this; // Compare using UTC if ($utc || ($date->timezoneName !== $current->timezoneName)) { $date = $date->avoidMutation()->utc(); $current = $current->avoidMutation()->utc(); } $negative = ($date < $current); [$start, $end] = $negative ? [$date, $current] : [$current, $date]; $interval = $start->diffAsDateInterval($end); $daysA = $this->getIntervalDayDiff($interval); $floorEnd = $start->avoidMutation()->addDays($daysA); $daysB = $daysA + ($floorEnd <= $end ? 1 : -1); $ceilEnd = $start->avoidMutation()->addDays($daysB); $microsecondsBetween = $floorEnd->diffInMicroseconds($ceilEnd); $microsecondsToEnd = $floorEnd->diffInMicroseconds($end); return ($negative && !$absolute ? -1 : 1) * ($daysA * ($microsecondsBetween - $microsecondsToEnd) + $daysB * $microsecondsToEnd) / $microsecondsBetween; } /** * Get the difference in days using a filter closure. * * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInDaysFiltered(Closure $callback, $date = null, bool $absolute = false): int { return $this->diffFiltered(CarbonInterval::day(), $callback, $date, $absolute); } /** * Get the difference in hours using a filter closure. * * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInHoursFiltered(Closure $callback, $date = null, bool $absolute = false): int { return $this->diffFiltered(CarbonInterval::hour(), $callback, $date, $absolute); } /** * Get the difference by the given interval using a filter closure. * * @param CarbonInterval $ci An interval to traverse by * @param Closure $callback * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffFiltered(CarbonInterval $ci, Closure $callback, $date = null, bool $absolute = false): int { $start = $this; $end = $this->resolveCarbon($date); $inverse = false; if ($end < $start) { $start = $end; $end = $this; $inverse = true; } $options = CarbonPeriod::EXCLUDE_END_DATE | ($this->isMutable() ? 0 : CarbonPeriod::IMMUTABLE); $diff = $ci->toPeriod($start, $end, $options)->filter($callback)->count(); return $inverse && !$absolute ? -$diff : $diff; } /** * Get the difference in weekdays. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInWeekdays($date = null, bool $absolute = false): int { return $this->diffInDaysFiltered( static fn (CarbonInterface $date) => $date->isWeekday(), $this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')), $absolute, ); } /** * Get the difference in weekend days using a filter. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return int */ public function diffInWeekendDays($date = null, bool $absolute = false): int { return $this->diffInDaysFiltered( static fn (CarbonInterface $date) => $date->isWeekend(), $this->resolveCarbon($date)->avoidMutation()->modify($this->format('H:i:s.u')), $absolute, ); } /** * Get the difference in hours. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInHours($date = null, bool $absolute = false): float { return $this->diffInMinutes($date, $absolute) / static::MINUTES_PER_HOUR; } /** * Get the difference in minutes. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMinutes($date = null, bool $absolute = false): float { return $this->diffInSeconds($date, $absolute) / static::SECONDS_PER_MINUTE; } /** * Get the difference in seconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInSeconds($date = null, bool $absolute = false): float { return $this->diffInMilliseconds($date, $absolute) / static::MILLISECONDS_PER_SECOND; } /** * Get the difference in microseconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMicroseconds($date = null, bool $absolute = false): float { /** @var CarbonInterface $date */ $date = $this->resolveCarbon($date); $value = ($date->timestamp - $this->timestamp) * static::MICROSECONDS_PER_SECOND + $date->micro - $this->micro; return $absolute ? abs($value) : $value; } /** * Get the difference in milliseconds. * * @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date * @param bool $absolute Get the absolute of the difference * * @return float */ public function diffInMilliseconds($date = null, bool $absolute = false): float { return $this->diffInMicroseconds($date, $absolute) / static::MICROSECONDS_PER_MILLISECOND; } /** * The number of seconds since midnight. * * @return float */ public function secondsSinceMidnight(): float { return $this->diffInSeconds($this->copy()->startOfDay(), true); } /** * The number of seconds until 23:59:59. * * @return float */ public function secondsUntilEndOfDay(): float { return $this->diffInSeconds($this->copy()->endOfDay(), true); } /** * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). * * @example * ``` * echo Carbon::tomorrow()->diffForHumans() . "\n"; * echo Carbon::tomorrow()->diffForHumans(['parts' => 2]) . "\n"; * echo Carbon::tomorrow()->diffForHumans(['parts' => 3, 'join' => true]) . "\n"; * echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday()) . "\n"; * echo Carbon::tomorrow()->diffForHumans(Carbon::yesterday(), ['short' => true]) . "\n"; * ``` * * @param Carbon|DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * ⦿ 'syntax' entry (see below) * ⦿ 'short' entry (see below) * ⦿ 'parts' entry (see below) * ⦿ 'options' entry (see below) * ⦿ 'skip' entry, list of units to skip (array of strings or a single string, * ` it can be the unit name (singular or plural) or its shortcut * ` (y, m, w, d, h, min, s, ms, µs). * ⦿ 'aUnit' entry, prefer "an hour" over "1 hour" if true * ⦿ 'altNumbers' entry, use alternative numbers if available * ` (from the current language if true is passed, from the given language(s) * ` if array or string is passed) * ⦿ 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * ⦿ 'other' entry (see above) * ⦿ 'minimumUnit' entry determines the smallest unit of time to display can be long or * ` short form of the units, e.g. 'hour' or 'h' (default value: s) * ⦿ 'locale' language in which the diff should be output (has no effect if 'translator' key is set) * ⦿ 'translator' a custom translator to use to translator the output. * if int passed, it adds modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options */ public function diffForHumans($other = null, $syntax = null, $short = false, $parts = 1, $options = null): string { /* @var CarbonInterface $this */ if (\is_array($other)) { $other['syntax'] = \array_key_exists('syntax', $other) ? $other['syntax'] : $syntax; $syntax = $other; $other = $syntax['other'] ?? null; } $intSyntax = &$syntax; if (\is_array($syntax)) { $syntax['syntax'] = $syntax['syntax'] ?? null; $intSyntax = &$syntax['syntax']; } $intSyntax = (int) ($intSyntax ?? static::DIFF_RELATIVE_AUTO); $intSyntax = $intSyntax === static::DIFF_RELATIVE_AUTO && $other === null ? static::DIFF_RELATIVE_TO_NOW : $intSyntax; $parts = min(7, max(1, (int) $parts)); $skip = \is_array($syntax) ? ($syntax['skip'] ?? []) : []; $options ??= $this->localHumanDiffOptions ?? $this->transmitFactory( static fn () => static::getHumanDiffOptions(), ); return $this->diff($other, skip: (array) $skip)->forHumans($syntax, (bool) $short, $parts, $options); } /** * @alias diffForHumans * * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function from($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->diffForHumans($other, $syntax, $short, $parts, $options); } /** * @alias diffForHumans * * Get the difference in a human readable format in the current locale from current instance to an other * instance given (or now if null given). */ public function since($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->diffForHumans($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given (or now if null given) to current instance. * * When comparing a value in the past to default now: * 1 hour from now * 5 months from now * * When comparing a value in the future to default now: * 1 hour ago * 5 months ago * * When comparing a value in the past to another value: * 1 hour after * 5 months after * * When comparing a value in the future to another value: * 1 hour before * 5 months before * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function to($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { if (!$syntax && !$other) { $syntax = CarbonInterface::DIFF_RELATIVE_TO_NOW; } return $this->resolveCarbon($other)->diffForHumans($this, $syntax, $short, $parts, $options); } /** * @alias to * * Get the difference in a human readable format in the current locale from an other * instance given (or now if null given) to current instance. * * @param Carbon|\DateTimeInterface|string|array|null $other if array passed, will be used as parameters array, see $syntax below; * if null passed, now will be used as comparison reference; * if any other type, it will be converted to date and used as reference. * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * - 'other' entry (see above) * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function until($other = null, $syntax = null, $short = false, $parts = 1, $options = null) { return $this->to($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from current * instance to now. * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single unit) * @param int $options human diff options * * @return string */ public function fromNow($syntax = null, $short = false, $parts = 1, $options = null) { $other = null; if ($syntax instanceof DateTimeInterface) { [$other, $syntax, $short, $parts, $options] = array_pad(\func_get_args(), 5, null); } return $this->from($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given to now * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single part) * @param int $options human diff options * * @return string */ public function toNow($syntax = null, $short = false, $parts = 1, $options = null) { return $this->to(null, $syntax, $short, $parts, $options); } /** * Get the difference in a human readable format in the current locale from an other * instance given to now * * @param int|array $syntax if array passed, parameters will be extracted from it, the array may contains: * - 'syntax' entry (see below) * - 'short' entry (see below) * - 'parts' entry (see below) * - 'options' entry (see below) * - 'join' entry determines how to join multiple parts of the string * ` - if $join is a string, it's used as a joiner glue * ` - if $join is a callable/closure, it get the list of string and should return a string * ` - if $join is an array, the first item will be the default glue, and the second item * ` will be used instead of the glue for the last item * ` - if $join is true, it will be guessed from the locale ('list' translation file entry) * ` - if $join is missing, a space will be used as glue * if int passed, it add modifiers: * Possible values: * - CarbonInterface::DIFF_ABSOLUTE no modifiers * - CarbonInterface::DIFF_RELATIVE_TO_NOW add ago/from now modifier * - CarbonInterface::DIFF_RELATIVE_TO_OTHER add before/after modifier * Default value: CarbonInterface::DIFF_ABSOLUTE * @param bool $short displays short format of time units * @param int $parts maximum number of parts to display (default value: 1: single part) * @param int $options human diff options * * @return string */ public function ago($syntax = null, $short = false, $parts = 1, $options = null) { $other = null; if ($syntax instanceof DateTimeInterface) { [$other, $syntax, $short, $parts, $options] = array_pad(\func_get_args(), 5, null); } return $this->from($other, $syntax, $short, $parts, $options); } /** * Get the difference in a human-readable format in the current locale from current instance to another * instance given (or now if null given). * * @return string */ public function timespan($other = null, $timezone = null): string { if (\is_string($other)) { $other = $this->transmitFactory(static fn () => static::parse($other, $timezone)); } return $this->diffForHumans($other, [ 'join' => ', ', 'syntax' => CarbonInterface::DIFF_ABSOLUTE, 'parts' => INF, ]); } /** * Returns either day of week + time (e.g. "Last Friday at 3:30 PM") if reference time is within 7 days, * or a calendar date (e.g. "10/29/2017") otherwise. * * Language, date and time formats will change according to the current locale. * * @param Carbon|\DateTimeInterface|string|null $referenceTime * @param array $formats * * @return string */ public function calendar($referenceTime = null, array $formats = []) { /** @var CarbonInterface $current */ $current = $this->avoidMutation()->startOfDay(); /** @var CarbonInterface $other */ $other = $this->resolveCarbon($referenceTime)->avoidMutation()->setTimezone($this->getTimezone())->startOfDay(); $diff = $other->diffInDays($current, false); $format = $diff <= -static::DAYS_PER_WEEK ? 'sameElse' : ( $diff < -1 ? 'lastWeek' : ( $diff < 0 ? 'lastDay' : ( $diff < 1 ? 'sameDay' : ( $diff < 2 ? 'nextDay' : ( $diff < static::DAYS_PER_WEEK ? 'nextWeek' : 'sameElse' ) ) ) ) ); $format = array_merge($this->getCalendarFormats(), $formats)[$format]; if ($format instanceof Closure) { $format = $format($current, $other) ?? ''; } return $this->isoFormat((string) $format); } private function getIntervalDayDiff(DateInterval $interval): int { return (int) $interval->format('%r%a'); } }
PHP
{ "end_line": 849, "name": "calendar", "signature": "public function calendar($referenceTime = null, array $formats = [])", "start_line": 825 }
{ "class_name": "Difference", "class_signature": "trait Difference", "namespace": "Carbon\\Traits" }
convertDate
Carbon/src/Carbon/Traits/IntervalStep.php
public function convertDate(DateTimeInterface $dateTime, bool $negated = false): CarbonInterface { /** @var CarbonInterface $carbonDate */ $carbonDate = $dateTime instanceof CarbonInterface ? $dateTime : $this->resolveCarbon($dateTime); if ($this->step) { $carbonDate = Callback::parameter($this->step, $carbonDate->avoidMutation()); return $carbonDate->modify(($this->step)($carbonDate, $negated)->format('Y-m-d H:i:s.u e O')); } if ($negated) { return $carbonDate->rawSub($this); } return $carbonDate->rawAdd($this); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\Callback; use Carbon\Carbon; use Carbon\CarbonImmutable; use Carbon\CarbonInterface; use Closure; use DateTimeImmutable; use DateTimeInterface; trait IntervalStep { /** * Step to apply instead of a fixed interval to get the new date. * * @var Closure|null */ protected $step; /** * Get the dynamic step in use. * * @return Closure */ public function getStep(): ?Closure { return $this->step; } /** * Set a step to apply instead of a fixed interval to get the new date. * * Or pass null to switch to fixed interval. * * @param Closure|null $step */ public function setStep(?Closure $step): void { $this->step = $step; } /** * Take a date and apply either the step if set, or the current interval else. * * The interval/step is applied negatively (typically subtraction instead of addition) if $negated is true. * * @param DateTimeInterface $dateTime * @param bool $negated * * @return CarbonInterface */ public function convertDate(DateTimeInterface $dateTime, bool $negated = false): CarbonInterface { /** @var CarbonInterface $carbonDate */ $carbonDate = $dateTime instanceof CarbonInterface ? $dateTime : $this->resolveCarbon($dateTime); if ($this->step) { $carbonDate = Callback::parameter($this->step, $carbonDate->avoidMutation()); return $carbonDate->modify(($this->step)($carbonDate, $negated)->format('Y-m-d H:i:s.u e O')); } if ($negated) { return $carbonDate->rawSub($this); } return $carbonDate->rawAdd($this); } /** * Convert DateTimeImmutable instance to CarbonImmutable instance and DateTime instance to Carbon instance. */ private function resolveCarbon(DateTimeInterface $dateTime): Carbon|CarbonImmutable { if ($dateTime instanceof DateTimeImmutable) { return CarbonImmutable::instance($dateTime); } return Carbon::instance($dateTime); } }
PHP
{ "end_line": 81, "name": "convertDate", "signature": "public function convertDate(DateTimeInterface $dateTime, bool $negated = false): CarbonInterface", "start_line": 65 }
{ "class_name": "IntervalStep", "class_signature": "trait IntervalStep", "namespace": "Carbon\\Traits" }
translateWith
Carbon/src/Carbon/Traits/Localization.php
public static function translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null): string { $message = static::getTranslationMessageWith($translator, $key, null, $key); if ($message instanceof Closure) { return (string) $message(...array_values($parameters)); } if ($number !== null) { $parameters['%count%'] = $number; } if (isset($parameters['%count%'])) { $parameters[':count'] = $parameters['%count%']; } return (string) $translator->trans($key, $parameters); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidTypeException; use Carbon\Exceptions\NotLocaleAwareException; use Carbon\Language; use Carbon\Translator; use Carbon\TranslatorStrongTypeInterface; use Closure; use Symfony\Component\Translation\TranslatorBagInterface; use Symfony\Contracts\Translation\LocaleAwareInterface; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Localization. * * Embed default and locale translators and translation base methods. */ trait Localization { use StaticLocalization; /** * Specific translator of the current instance. */ protected ?TranslatorInterface $localTranslator = null; /** * Return true if the current instance has its own translator. */ public function hasLocalTranslator(): bool { return isset($this->localTranslator); } /** * Get the translator of the current instance or the default if none set. */ public function getLocalTranslator(): TranslatorInterface { return $this->localTranslator ?? $this->transmitFactory(static fn () => static::getTranslator()); } /** * Set the translator for the current instance. */ public function setLocalTranslator(TranslatorInterface $translator): self { $this->localTranslator = $translator; return $this; } /** * Returns raw translation message for a given key. * * @param TranslatorInterface|null $translator the translator to use * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * * @return string|Closure|null */ public static function getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null) { if (!($translator instanceof TranslatorBagInterface && $translator instanceof TranslatorInterface)) { throw new InvalidTypeException( 'Translator does not implement '.TranslatorInterface::class.' and '.TranslatorBagInterface::class.'. '. (\is_object($translator) ? \get_class($translator) : \gettype($translator)).' has been given.', ); } if (!$locale && $translator instanceof LocaleAwareInterface) { $locale = $translator->getLocale(); } $result = self::getFromCatalogue($translator, $translator->getCatalogue($locale), $key); return $result === $key ? $default : $result; } /** * Returns raw translation message for a given key. * * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * @param TranslatorInterface $translator an optional translator to use * * @return string */ public function getTranslationMessage(string $key, ?string $locale = null, ?string $default = null, $translator = null) { return static::getTranslationMessageWith($translator ?? $this->getLocalTranslator(), $key, $locale, $default); } /** * Translate using translation string or callback available. * * @param TranslatorInterface $translator an optional translator to use * @param string $key key to find * @param array $parameters replacement parameters * @param int|float|null $number number if plural * * @return string */ public static function translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null): string { $message = static::getTranslationMessageWith($translator, $key, null, $key); if ($message instanceof Closure) { return (string) $message(...array_values($parameters)); } if ($number !== null) { $parameters['%count%'] = $number; } if (isset($parameters['%count%'])) { $parameters[':count'] = $parameters['%count%']; } return (string) $translator->trans($key, $parameters); } /** * Translate using translation string or callback available. * * @param string $key key to find * @param array $parameters replacement parameters * @param string|int|float|null $number number if plural * @param TranslatorInterface|null $translator an optional translator to use * @param bool $altNumbers pass true to use alternative numbers * * @return string */ public function translate( string $key, array $parameters = [], string|int|float|null $number = null, ?TranslatorInterface $translator = null, bool $altNumbers = false, ): string { $translation = static::translateWith($translator ?? $this->getLocalTranslator(), $key, $parameters, $number); if ($number !== null && $altNumbers) { return str_replace((string) $number, $this->translateNumber((int) $number), $translation); } return $translation; } /** * Returns the alternative number for a given integer if available in the current locale. * * @param int $number * * @return string */ public function translateNumber(int $number): string { $translateKey = "alt_numbers.$number"; $symbol = $this->translate($translateKey); if ($symbol !== $translateKey) { return $symbol; } if ($number > 99 && $this->translate('alt_numbers.99') !== 'alt_numbers.99') { $start = ''; foreach ([10000, 1000, 100] as $exp) { $key = "alt_numbers_pow.$exp"; if ($number >= $exp && $number < $exp * 10 && ($pow = $this->translate($key)) !== $key) { $unit = floor($number / $exp); $number -= $unit * $exp; $start .= ($unit > 1 ? $this->translate("alt_numbers.$unit") : '').$pow; } } $result = ''; while ($number) { $chunk = $number % 100; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 100); } return "$start$result"; } if ($number > 9 && $this->translate('alt_numbers.9') !== 'alt_numbers.9') { $result = ''; while ($number) { $chunk = $number % 10; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 10); } return $result; } return (string) $number; } /** * Translate a time string from a locale to an other. * * @param string $timeString date/time/duration string to translate (may also contain English) * @param string|null $from input locale of the $timeString parameter (`Carbon::getLocale()` by default) * @param string|null $to output locale of the result returned (`"en"` by default) * @param int $mode specify what to translate with options: * - CarbonInterface::TRANSLATE_ALL (default) * - CarbonInterface::TRANSLATE_MONTHS * - CarbonInterface::TRANSLATE_DAYS * - CarbonInterface::TRANSLATE_UNITS * - CarbonInterface::TRANSLATE_MERIDIEM * You can use pipe to group: CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS * * @return string */ public static function translateTimeString( string $timeString, ?string $from = null, ?string $to = null, int $mode = CarbonInterface::TRANSLATE_ALL, ): string { // Fallback source and destination locales $from = $from ?: static::getLocale(); $to = $to ?: CarbonInterface::DEFAULT_LOCALE; if ($from === $to) { return $timeString; } // Standardize apostrophe $timeString = strtr($timeString, ['’' => "'"]); $fromTranslations = []; $toTranslations = []; foreach (['from', 'to'] as $key) { $language = $$key; $translator = Translator::get($language); $translations = $translator->getMessages(); if (!isset($translations[$language])) { return $timeString; } $translationKey = $key.'Translations'; $messages = $translations[$language]; $months = $messages['months'] ?? []; $weekdays = $messages['weekdays'] ?? []; $meridiem = $messages['meridiem'] ?? ['AM', 'PM']; if (isset($messages['ordinal_words'])) { $timeString = self::replaceOrdinalWords( $timeString, $key === 'from' ? array_flip($messages['ordinal_words']) : $messages['ordinal_words'] ); } if ($key === 'from') { foreach (['months', 'weekdays'] as $variable) { $list = $messages[$variable.'_standalone'] ?? null; if ($list) { foreach ($$variable as $index => &$name) { $name .= '|'.$list[$index]; } } } } $$translationKey = array_merge( $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($months, static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($messages['months_short'] ?? [], static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($weekdays, static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($messages['weekdays_short'] ?? [], static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DIFF ? self::translateWordsByKeys([ 'diff_now', 'diff_today', 'diff_yesterday', 'diff_tomorrow', 'diff_before_yesterday', 'diff_after_tomorrow', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_UNITS ? self::translateWordsByKeys([ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_MERIDIEM ? array_map(function ($hour) use ($meridiem) { if (\is_array($meridiem)) { return $meridiem[$hour < static::HOURS_PER_DAY / 2 ? 0 : 1]; } return $meridiem($hour, 0, false); }, range(0, 23)) : [], ); } return substr(preg_replace_callback('/(?<=[\d\s+.\/,_-])('.implode('|', $fromTranslations).')(?=[\d\s+.\/,_-])/iu', function ($match) use ($fromTranslations, $toTranslations) { [$chunk] = $match; foreach ($fromTranslations as $index => $word) { if (preg_match("/^$word\$/iu", $chunk)) { return $toTranslations[$index] ?? ''; } } return $chunk; // @codeCoverageIgnore }, " $timeString "), 1, -1); } /** * Translate a time string from the current locale (`$date->locale()`) to another one. * * @param string $timeString time string to translate * @param string|null $to output locale of the result returned ("en" by default) * * @return string */ public function translateTimeStringTo(string $timeString, ?string $to = null): string { return static::translateTimeString($timeString, $this->getTranslatorLocale(), $to); } /** * Get/set the locale for the current instance. * * @param string|null $locale * @param string ...$fallbackLocales * * @return $this|string */ public function locale(?string $locale = null, string ...$fallbackLocales): static|string { if ($locale === null) { return $this->getTranslatorLocale(); } if (!$this->localTranslator || $this->getTranslatorLocale($this->localTranslator) !== $locale) { $translator = Translator::get($locale); if (!empty($fallbackLocales)) { $translator->setFallbackLocales($fallbackLocales); foreach ($fallbackLocales as $fallbackLocale) { $messages = Translator::get($fallbackLocale)->getMessages(); if (isset($messages[$fallbackLocale])) { $translator->setMessages($fallbackLocale, $messages[$fallbackLocale]); } } } $this->localTranslator = $translator; } return $this; } /** * Get the current translator locale. * * @return string */ public static function getLocale(): string { return static::getLocaleAwareTranslator()->getLocale(); } /** * Set the current translator locale and indicate if the source locale file exists. * Pass 'auto' as locale to use the closest language to the current LC_TIME locale. * * @param string $locale locale ex. en */ public static function setLocale(string $locale): void { static::getLocaleAwareTranslator()->setLocale($locale); } /** * Set the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales * * @param string $locale */ public static function setFallbackLocale(string $locale): void { $translator = static::getTranslator(); if (method_exists($translator, 'setFallbackLocales')) { $translator->setFallbackLocales([$locale]); if ($translator instanceof Translator) { $preferredLocale = $translator->getLocale(); $translator->setMessages($preferredLocale, array_replace_recursive( $translator->getMessages()[$locale] ?? [], Translator::get($locale)->getMessages()[$locale] ?? [], $translator->getMessages($preferredLocale), )); } } } /** * Get the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales */ public static function getFallbackLocale(): ?string { $translator = static::getTranslator(); if (method_exists($translator, 'getFallbackLocales')) { return $translator->getFallbackLocales()[0] ?? null; } return null; } /** * Set the current locale to the given, execute the passed function, reset the locale to previous one, * then return the result of the closure (or null if the closure was void). * * @param string $locale locale ex. en * @param callable $func * * @return mixed */ public static function executeWithLocale(string $locale, callable $func): mixed { $currentLocale = static::getLocale(); static::setLocale($locale); $newLocale = static::getLocale(); $result = $func( $newLocale === 'en' && strtolower(substr((string) $locale, 0, 2)) !== 'en' ? false : $newLocale, static::getTranslator(), ); static::setLocale($currentLocale); return $result; } /** * Returns true if the given locale is internally supported and has short-units support. * Support is considered enabled if either year, day or hour has a short variant translated. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasShortUnits(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return ($newLocale && (($y = static::translateWith($translator, 'y')) !== 'y' && $y !== static::translateWith($translator, 'year'))) || ( ($y = static::translateWith($translator, 'd')) !== 'd' && $y !== static::translateWith($translator, 'day') ) || ( ($y = static::translateWith($translator, 'h')) !== 'h' && $y !== static::translateWith($translator, 'hour') ); }); } /** * Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffSyntax(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { if (!$newLocale) { return false; } foreach (['ago', 'from_now', 'before', 'after'] as $key) { if ($translator instanceof TranslatorBagInterface && self::getFromCatalogue($translator, $translator->getCatalogue($newLocale), $key) instanceof Closure ) { continue; } if ($translator->trans($key) === $key) { return false; } } return true; }); } /** * Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow). * Support is considered enabled if the 3 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffOneDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_now') !== 'diff_now' && $translator->trans('diff_yesterday') !== 'diff_yesterday' && $translator->trans('diff_tomorrow') !== 'diff_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow). * Support is considered enabled if the 2 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffTwoDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_before_yesterday') !== 'diff_before_yesterday' && $translator->trans('diff_after_tomorrow') !== 'diff_after_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasPeriodSyntax($locale) { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('period_recurrences') !== 'period_recurrences' && $translator->trans('period_interval') !== 'period_interval' && $translator->trans('period_start_date') !== 'period_start_date' && $translator->trans('period_end_date') !== 'period_end_date'; }); } /** * Returns the list of internally available locales and already loaded custom locales. * (It will ignore custom translator dynamic loading.) * * @return array */ public static function getAvailableLocales() { $translator = static::getLocaleAwareTranslator(); return $translator instanceof Translator ? $translator->getAvailableLocales() : [$translator->getLocale()]; } /** * Returns list of Language object for each available locale. This object allow you to get the ISO name, native * name, region and variant of the locale. * * @return Language[] */ public static function getAvailableLocalesInfo() { $languages = []; foreach (static::getAvailableLocales() as $id) { $languages[$id] = new Language($id); } return $languages; } /** * Get the locale of a given translator. * * If null or omitted, current local translator is used. * If no local translator is in use, current global translator is used. */ protected function getTranslatorLocale($translator = null): ?string { if (\func_num_args() === 0) { $translator = $this->getLocalTranslator(); } $translator = static::getLocaleAwareTranslator($translator); return $translator?->getLocale(); } /** * Throw an error if passed object is not LocaleAwareInterface. * * @param LocaleAwareInterface|null $translator * * @return LocaleAwareInterface|null */ protected static function getLocaleAwareTranslator($translator = null) { if (\func_num_args() === 0) { $translator = static::getTranslator(); } if ($translator && !($translator instanceof LocaleAwareInterface || method_exists($translator, 'getLocale'))) { throw new NotLocaleAwareException($translator); // @codeCoverageIgnore } return $translator; } /** * @param mixed $translator * @param \Symfony\Component\Translation\MessageCatalogueInterface $catalogue * * @return mixed */ private static function getFromCatalogue($translator, $catalogue, string $id, string $domain = 'messages') { return $translator instanceof TranslatorStrongTypeInterface ? $translator->getFromCatalogue($catalogue, $id, $domain) : $catalogue->get($id, $domain); // @codeCoverageIgnore } /** * Return the word cleaned from its translation codes. * * @param string $word * * @return string */ private static function cleanWordFromTranslationString($word) { $word = str_replace([':count', '%count', ':time'], '', $word); $word = strtr($word, ['’' => "'"]); $word = preg_replace( '/\{(?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?}|[\[\]](?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?[\[\]]/', '', $word, ); return trim($word); } /** * Translate a list of words. * * @param string[] $keys keys to translate. * @param string[] $messages messages bag handling translations. * @param string $key 'to' (to get the translation) or 'from' (to get the detection RegExp pattern). * * @return string[] */ private static function translateWordsByKeys($keys, $messages, $key): array { return array_map(function ($wordKey) use ($messages, $key) { $message = $key === 'from' && isset($messages[$wordKey.'_regexp']) ? $messages[$wordKey.'_regexp'] : ($messages[$wordKey] ?? null); if (!$message) { return '>>DO NOT REPLACE<<'; } $parts = explode('|', $message); return $key === 'to' ? self::cleanWordFromTranslationString(end($parts)) : '(?:'.implode('|', array_map(static::cleanWordFromTranslationString(...), $parts)).')'; }, $keys); } /** * Get an array of translations based on the current date. * * @param callable $translation * @param int $length * @param string $timeString * * @return string[] */ private static function getTranslationArray($translation, $length, $timeString): array { $filler = '>>DO NOT REPLACE<<'; if (\is_array($translation)) { return array_pad($translation, $length, $filler); } $list = []; $date = static::now(); for ($i = 0; $i < $length; $i++) { $list[] = $translation($date, $timeString, $i) ?? $filler; } return $list; } private static function replaceOrdinalWords(string $timeString, array $ordinalWords): string { return preg_replace_callback('/(?<![a-z])[a-z]+(?![a-z])/i', function (array $match) use ($ordinalWords) { return $ordinalWords[mb_strtolower($match[0])] ?? $match[0]; }, $timeString); } }
PHP
{ "end_line": 135, "name": "translateWith", "signature": "public static function translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null): string", "start_line": 120 }
{ "class_name": "Localization", "class_signature": "trait Localization", "namespace": "Carbon\\Traits" }
translate
Carbon/src/Carbon/Traits/Localization.php
public function translate( string $key, array $parameters = [], string|int|float|null $number = null, ?TranslatorInterface $translator = null, bool $altNumbers = false, ): string { $translation = static::translateWith($translator ?? $this->getLocalTranslator(), $key, $parameters, $number); if ($number !== null && $altNumbers) { return str_replace((string) $number, $this->translateNumber((int) $number), $translation); } return $translation; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidTypeException; use Carbon\Exceptions\NotLocaleAwareException; use Carbon\Language; use Carbon\Translator; use Carbon\TranslatorStrongTypeInterface; use Closure; use Symfony\Component\Translation\TranslatorBagInterface; use Symfony\Contracts\Translation\LocaleAwareInterface; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Localization. * * Embed default and locale translators and translation base methods. */ trait Localization { use StaticLocalization; /** * Specific translator of the current instance. */ protected ?TranslatorInterface $localTranslator = null; /** * Return true if the current instance has its own translator. */ public function hasLocalTranslator(): bool { return isset($this->localTranslator); } /** * Get the translator of the current instance or the default if none set. */ public function getLocalTranslator(): TranslatorInterface { return $this->localTranslator ?? $this->transmitFactory(static fn () => static::getTranslator()); } /** * Set the translator for the current instance. */ public function setLocalTranslator(TranslatorInterface $translator): self { $this->localTranslator = $translator; return $this; } /** * Returns raw translation message for a given key. * * @param TranslatorInterface|null $translator the translator to use * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * * @return string|Closure|null */ public static function getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null) { if (!($translator instanceof TranslatorBagInterface && $translator instanceof TranslatorInterface)) { throw new InvalidTypeException( 'Translator does not implement '.TranslatorInterface::class.' and '.TranslatorBagInterface::class.'. '. (\is_object($translator) ? \get_class($translator) : \gettype($translator)).' has been given.', ); } if (!$locale && $translator instanceof LocaleAwareInterface) { $locale = $translator->getLocale(); } $result = self::getFromCatalogue($translator, $translator->getCatalogue($locale), $key); return $result === $key ? $default : $result; } /** * Returns raw translation message for a given key. * * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * @param TranslatorInterface $translator an optional translator to use * * @return string */ public function getTranslationMessage(string $key, ?string $locale = null, ?string $default = null, $translator = null) { return static::getTranslationMessageWith($translator ?? $this->getLocalTranslator(), $key, $locale, $default); } /** * Translate using translation string or callback available. * * @param TranslatorInterface $translator an optional translator to use * @param string $key key to find * @param array $parameters replacement parameters * @param int|float|null $number number if plural * * @return string */ public static function translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null): string { $message = static::getTranslationMessageWith($translator, $key, null, $key); if ($message instanceof Closure) { return (string) $message(...array_values($parameters)); } if ($number !== null) { $parameters['%count%'] = $number; } if (isset($parameters['%count%'])) { $parameters[':count'] = $parameters['%count%']; } return (string) $translator->trans($key, $parameters); } /** * Translate using translation string or callback available. * * @param string $key key to find * @param array $parameters replacement parameters * @param string|int|float|null $number number if plural * @param TranslatorInterface|null $translator an optional translator to use * @param bool $altNumbers pass true to use alternative numbers * * @return string */ public function translate( string $key, array $parameters = [], string|int|float|null $number = null, ?TranslatorInterface $translator = null, bool $altNumbers = false, ): string { $translation = static::translateWith($translator ?? $this->getLocalTranslator(), $key, $parameters, $number); if ($number !== null && $altNumbers) { return str_replace((string) $number, $this->translateNumber((int) $number), $translation); } return $translation; } /** * Returns the alternative number for a given integer if available in the current locale. * * @param int $number * * @return string */ public function translateNumber(int $number): string { $translateKey = "alt_numbers.$number"; $symbol = $this->translate($translateKey); if ($symbol !== $translateKey) { return $symbol; } if ($number > 99 && $this->translate('alt_numbers.99') !== 'alt_numbers.99') { $start = ''; foreach ([10000, 1000, 100] as $exp) { $key = "alt_numbers_pow.$exp"; if ($number >= $exp && $number < $exp * 10 && ($pow = $this->translate($key)) !== $key) { $unit = floor($number / $exp); $number -= $unit * $exp; $start .= ($unit > 1 ? $this->translate("alt_numbers.$unit") : '').$pow; } } $result = ''; while ($number) { $chunk = $number % 100; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 100); } return "$start$result"; } if ($number > 9 && $this->translate('alt_numbers.9') !== 'alt_numbers.9') { $result = ''; while ($number) { $chunk = $number % 10; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 10); } return $result; } return (string) $number; } /** * Translate a time string from a locale to an other. * * @param string $timeString date/time/duration string to translate (may also contain English) * @param string|null $from input locale of the $timeString parameter (`Carbon::getLocale()` by default) * @param string|null $to output locale of the result returned (`"en"` by default) * @param int $mode specify what to translate with options: * - CarbonInterface::TRANSLATE_ALL (default) * - CarbonInterface::TRANSLATE_MONTHS * - CarbonInterface::TRANSLATE_DAYS * - CarbonInterface::TRANSLATE_UNITS * - CarbonInterface::TRANSLATE_MERIDIEM * You can use pipe to group: CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS * * @return string */ public static function translateTimeString( string $timeString, ?string $from = null, ?string $to = null, int $mode = CarbonInterface::TRANSLATE_ALL, ): string { // Fallback source and destination locales $from = $from ?: static::getLocale(); $to = $to ?: CarbonInterface::DEFAULT_LOCALE; if ($from === $to) { return $timeString; } // Standardize apostrophe $timeString = strtr($timeString, ['’' => "'"]); $fromTranslations = []; $toTranslations = []; foreach (['from', 'to'] as $key) { $language = $$key; $translator = Translator::get($language); $translations = $translator->getMessages(); if (!isset($translations[$language])) { return $timeString; } $translationKey = $key.'Translations'; $messages = $translations[$language]; $months = $messages['months'] ?? []; $weekdays = $messages['weekdays'] ?? []; $meridiem = $messages['meridiem'] ?? ['AM', 'PM']; if (isset($messages['ordinal_words'])) { $timeString = self::replaceOrdinalWords( $timeString, $key === 'from' ? array_flip($messages['ordinal_words']) : $messages['ordinal_words'] ); } if ($key === 'from') { foreach (['months', 'weekdays'] as $variable) { $list = $messages[$variable.'_standalone'] ?? null; if ($list) { foreach ($$variable as $index => &$name) { $name .= '|'.$list[$index]; } } } } $$translationKey = array_merge( $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($months, static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($messages['months_short'] ?? [], static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($weekdays, static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($messages['weekdays_short'] ?? [], static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DIFF ? self::translateWordsByKeys([ 'diff_now', 'diff_today', 'diff_yesterday', 'diff_tomorrow', 'diff_before_yesterday', 'diff_after_tomorrow', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_UNITS ? self::translateWordsByKeys([ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_MERIDIEM ? array_map(function ($hour) use ($meridiem) { if (\is_array($meridiem)) { return $meridiem[$hour < static::HOURS_PER_DAY / 2 ? 0 : 1]; } return $meridiem($hour, 0, false); }, range(0, 23)) : [], ); } return substr(preg_replace_callback('/(?<=[\d\s+.\/,_-])('.implode('|', $fromTranslations).')(?=[\d\s+.\/,_-])/iu', function ($match) use ($fromTranslations, $toTranslations) { [$chunk] = $match; foreach ($fromTranslations as $index => $word) { if (preg_match("/^$word\$/iu", $chunk)) { return $toTranslations[$index] ?? ''; } } return $chunk; // @codeCoverageIgnore }, " $timeString "), 1, -1); } /** * Translate a time string from the current locale (`$date->locale()`) to another one. * * @param string $timeString time string to translate * @param string|null $to output locale of the result returned ("en" by default) * * @return string */ public function translateTimeStringTo(string $timeString, ?string $to = null): string { return static::translateTimeString($timeString, $this->getTranslatorLocale(), $to); } /** * Get/set the locale for the current instance. * * @param string|null $locale * @param string ...$fallbackLocales * * @return $this|string */ public function locale(?string $locale = null, string ...$fallbackLocales): static|string { if ($locale === null) { return $this->getTranslatorLocale(); } if (!$this->localTranslator || $this->getTranslatorLocale($this->localTranslator) !== $locale) { $translator = Translator::get($locale); if (!empty($fallbackLocales)) { $translator->setFallbackLocales($fallbackLocales); foreach ($fallbackLocales as $fallbackLocale) { $messages = Translator::get($fallbackLocale)->getMessages(); if (isset($messages[$fallbackLocale])) { $translator->setMessages($fallbackLocale, $messages[$fallbackLocale]); } } } $this->localTranslator = $translator; } return $this; } /** * Get the current translator locale. * * @return string */ public static function getLocale(): string { return static::getLocaleAwareTranslator()->getLocale(); } /** * Set the current translator locale and indicate if the source locale file exists. * Pass 'auto' as locale to use the closest language to the current LC_TIME locale. * * @param string $locale locale ex. en */ public static function setLocale(string $locale): void { static::getLocaleAwareTranslator()->setLocale($locale); } /** * Set the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales * * @param string $locale */ public static function setFallbackLocale(string $locale): void { $translator = static::getTranslator(); if (method_exists($translator, 'setFallbackLocales')) { $translator->setFallbackLocales([$locale]); if ($translator instanceof Translator) { $preferredLocale = $translator->getLocale(); $translator->setMessages($preferredLocale, array_replace_recursive( $translator->getMessages()[$locale] ?? [], Translator::get($locale)->getMessages()[$locale] ?? [], $translator->getMessages($preferredLocale), )); } } } /** * Get the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales */ public static function getFallbackLocale(): ?string { $translator = static::getTranslator(); if (method_exists($translator, 'getFallbackLocales')) { return $translator->getFallbackLocales()[0] ?? null; } return null; } /** * Set the current locale to the given, execute the passed function, reset the locale to previous one, * then return the result of the closure (or null if the closure was void). * * @param string $locale locale ex. en * @param callable $func * * @return mixed */ public static function executeWithLocale(string $locale, callable $func): mixed { $currentLocale = static::getLocale(); static::setLocale($locale); $newLocale = static::getLocale(); $result = $func( $newLocale === 'en' && strtolower(substr((string) $locale, 0, 2)) !== 'en' ? false : $newLocale, static::getTranslator(), ); static::setLocale($currentLocale); return $result; } /** * Returns true if the given locale is internally supported and has short-units support. * Support is considered enabled if either year, day or hour has a short variant translated. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasShortUnits(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return ($newLocale && (($y = static::translateWith($translator, 'y')) !== 'y' && $y !== static::translateWith($translator, 'year'))) || ( ($y = static::translateWith($translator, 'd')) !== 'd' && $y !== static::translateWith($translator, 'day') ) || ( ($y = static::translateWith($translator, 'h')) !== 'h' && $y !== static::translateWith($translator, 'hour') ); }); } /** * Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffSyntax(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { if (!$newLocale) { return false; } foreach (['ago', 'from_now', 'before', 'after'] as $key) { if ($translator instanceof TranslatorBagInterface && self::getFromCatalogue($translator, $translator->getCatalogue($newLocale), $key) instanceof Closure ) { continue; } if ($translator->trans($key) === $key) { return false; } } return true; }); } /** * Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow). * Support is considered enabled if the 3 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffOneDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_now') !== 'diff_now' && $translator->trans('diff_yesterday') !== 'diff_yesterday' && $translator->trans('diff_tomorrow') !== 'diff_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow). * Support is considered enabled if the 2 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffTwoDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_before_yesterday') !== 'diff_before_yesterday' && $translator->trans('diff_after_tomorrow') !== 'diff_after_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasPeriodSyntax($locale) { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('period_recurrences') !== 'period_recurrences' && $translator->trans('period_interval') !== 'period_interval' && $translator->trans('period_start_date') !== 'period_start_date' && $translator->trans('period_end_date') !== 'period_end_date'; }); } /** * Returns the list of internally available locales and already loaded custom locales. * (It will ignore custom translator dynamic loading.) * * @return array */ public static function getAvailableLocales() { $translator = static::getLocaleAwareTranslator(); return $translator instanceof Translator ? $translator->getAvailableLocales() : [$translator->getLocale()]; } /** * Returns list of Language object for each available locale. This object allow you to get the ISO name, native * name, region and variant of the locale. * * @return Language[] */ public static function getAvailableLocalesInfo() { $languages = []; foreach (static::getAvailableLocales() as $id) { $languages[$id] = new Language($id); } return $languages; } /** * Get the locale of a given translator. * * If null or omitted, current local translator is used. * If no local translator is in use, current global translator is used. */ protected function getTranslatorLocale($translator = null): ?string { if (\func_num_args() === 0) { $translator = $this->getLocalTranslator(); } $translator = static::getLocaleAwareTranslator($translator); return $translator?->getLocale(); } /** * Throw an error if passed object is not LocaleAwareInterface. * * @param LocaleAwareInterface|null $translator * * @return LocaleAwareInterface|null */ protected static function getLocaleAwareTranslator($translator = null) { if (\func_num_args() === 0) { $translator = static::getTranslator(); } if ($translator && !($translator instanceof LocaleAwareInterface || method_exists($translator, 'getLocale'))) { throw new NotLocaleAwareException($translator); // @codeCoverageIgnore } return $translator; } /** * @param mixed $translator * @param \Symfony\Component\Translation\MessageCatalogueInterface $catalogue * * @return mixed */ private static function getFromCatalogue($translator, $catalogue, string $id, string $domain = 'messages') { return $translator instanceof TranslatorStrongTypeInterface ? $translator->getFromCatalogue($catalogue, $id, $domain) : $catalogue->get($id, $domain); // @codeCoverageIgnore } /** * Return the word cleaned from its translation codes. * * @param string $word * * @return string */ private static function cleanWordFromTranslationString($word) { $word = str_replace([':count', '%count', ':time'], '', $word); $word = strtr($word, ['’' => "'"]); $word = preg_replace( '/\{(?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?}|[\[\]](?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?[\[\]]/', '', $word, ); return trim($word); } /** * Translate a list of words. * * @param string[] $keys keys to translate. * @param string[] $messages messages bag handling translations. * @param string $key 'to' (to get the translation) or 'from' (to get the detection RegExp pattern). * * @return string[] */ private static function translateWordsByKeys($keys, $messages, $key): array { return array_map(function ($wordKey) use ($messages, $key) { $message = $key === 'from' && isset($messages[$wordKey.'_regexp']) ? $messages[$wordKey.'_regexp'] : ($messages[$wordKey] ?? null); if (!$message) { return '>>DO NOT REPLACE<<'; } $parts = explode('|', $message); return $key === 'to' ? self::cleanWordFromTranslationString(end($parts)) : '(?:'.implode('|', array_map(static::cleanWordFromTranslationString(...), $parts)).')'; }, $keys); } /** * Get an array of translations based on the current date. * * @param callable $translation * @param int $length * @param string $timeString * * @return string[] */ private static function getTranslationArray($translation, $length, $timeString): array { $filler = '>>DO NOT REPLACE<<'; if (\is_array($translation)) { return array_pad($translation, $length, $filler); } $list = []; $date = static::now(); for ($i = 0; $i < $length; $i++) { $list[] = $translation($date, $timeString, $i) ?? $filler; } return $list; } private static function replaceOrdinalWords(string $timeString, array $ordinalWords): string { return preg_replace_callback('/(?<![a-z])[a-z]+(?![a-z])/i', function (array $match) use ($ordinalWords) { return $ordinalWords[mb_strtolower($match[0])] ?? $match[0]; }, $timeString); } }
PHP
{ "end_line": 162, "name": "translate", "signature": "public function translate(", "start_line": 148 }
{ "class_name": "Localization", "class_signature": "trait Localization", "namespace": "Carbon\\Traits" }
translateNumber
Carbon/src/Carbon/Traits/Localization.php
public function translateNumber(int $number): string { $translateKey = "alt_numbers.$number"; $symbol = $this->translate($translateKey); if ($symbol !== $translateKey) { return $symbol; } if ($number > 99 && $this->translate('alt_numbers.99') !== 'alt_numbers.99') { $start = ''; foreach ([10000, 1000, 100] as $exp) { $key = "alt_numbers_pow.$exp"; if ($number >= $exp && $number < $exp * 10 && ($pow = $this->translate($key)) !== $key) { $unit = floor($number / $exp); $number -= $unit * $exp; $start .= ($unit > 1 ? $this->translate("alt_numbers.$unit") : '').$pow; } } $result = ''; while ($number) { $chunk = $number % 100; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 100); } return "$start$result"; } if ($number > 9 && $this->translate('alt_numbers.9') !== 'alt_numbers.9') { $result = ''; while ($number) { $chunk = $number % 10; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 10); } return $result; } return (string) $number; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidTypeException; use Carbon\Exceptions\NotLocaleAwareException; use Carbon\Language; use Carbon\Translator; use Carbon\TranslatorStrongTypeInterface; use Closure; use Symfony\Component\Translation\TranslatorBagInterface; use Symfony\Contracts\Translation\LocaleAwareInterface; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Localization. * * Embed default and locale translators and translation base methods. */ trait Localization { use StaticLocalization; /** * Specific translator of the current instance. */ protected ?TranslatorInterface $localTranslator = null; /** * Return true if the current instance has its own translator. */ public function hasLocalTranslator(): bool { return isset($this->localTranslator); } /** * Get the translator of the current instance or the default if none set. */ public function getLocalTranslator(): TranslatorInterface { return $this->localTranslator ?? $this->transmitFactory(static fn () => static::getTranslator()); } /** * Set the translator for the current instance. */ public function setLocalTranslator(TranslatorInterface $translator): self { $this->localTranslator = $translator; return $this; } /** * Returns raw translation message for a given key. * * @param TranslatorInterface|null $translator the translator to use * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * * @return string|Closure|null */ public static function getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null) { if (!($translator instanceof TranslatorBagInterface && $translator instanceof TranslatorInterface)) { throw new InvalidTypeException( 'Translator does not implement '.TranslatorInterface::class.' and '.TranslatorBagInterface::class.'. '. (\is_object($translator) ? \get_class($translator) : \gettype($translator)).' has been given.', ); } if (!$locale && $translator instanceof LocaleAwareInterface) { $locale = $translator->getLocale(); } $result = self::getFromCatalogue($translator, $translator->getCatalogue($locale), $key); return $result === $key ? $default : $result; } /** * Returns raw translation message for a given key. * * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * @param TranslatorInterface $translator an optional translator to use * * @return string */ public function getTranslationMessage(string $key, ?string $locale = null, ?string $default = null, $translator = null) { return static::getTranslationMessageWith($translator ?? $this->getLocalTranslator(), $key, $locale, $default); } /** * Translate using translation string or callback available. * * @param TranslatorInterface $translator an optional translator to use * @param string $key key to find * @param array $parameters replacement parameters * @param int|float|null $number number if plural * * @return string */ public static function translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null): string { $message = static::getTranslationMessageWith($translator, $key, null, $key); if ($message instanceof Closure) { return (string) $message(...array_values($parameters)); } if ($number !== null) { $parameters['%count%'] = $number; } if (isset($parameters['%count%'])) { $parameters[':count'] = $parameters['%count%']; } return (string) $translator->trans($key, $parameters); } /** * Translate using translation string or callback available. * * @param string $key key to find * @param array $parameters replacement parameters * @param string|int|float|null $number number if plural * @param TranslatorInterface|null $translator an optional translator to use * @param bool $altNumbers pass true to use alternative numbers * * @return string */ public function translate( string $key, array $parameters = [], string|int|float|null $number = null, ?TranslatorInterface $translator = null, bool $altNumbers = false, ): string { $translation = static::translateWith($translator ?? $this->getLocalTranslator(), $key, $parameters, $number); if ($number !== null && $altNumbers) { return str_replace((string) $number, $this->translateNumber((int) $number), $translation); } return $translation; } /** * Returns the alternative number for a given integer if available in the current locale. * * @param int $number * * @return string */ public function translateNumber(int $number): string { $translateKey = "alt_numbers.$number"; $symbol = $this->translate($translateKey); if ($symbol !== $translateKey) { return $symbol; } if ($number > 99 && $this->translate('alt_numbers.99') !== 'alt_numbers.99') { $start = ''; foreach ([10000, 1000, 100] as $exp) { $key = "alt_numbers_pow.$exp"; if ($number >= $exp && $number < $exp * 10 && ($pow = $this->translate($key)) !== $key) { $unit = floor($number / $exp); $number -= $unit * $exp; $start .= ($unit > 1 ? $this->translate("alt_numbers.$unit") : '').$pow; } } $result = ''; while ($number) { $chunk = $number % 100; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 100); } return "$start$result"; } if ($number > 9 && $this->translate('alt_numbers.9') !== 'alt_numbers.9') { $result = ''; while ($number) { $chunk = $number % 10; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 10); } return $result; } return (string) $number; } /** * Translate a time string from a locale to an other. * * @param string $timeString date/time/duration string to translate (may also contain English) * @param string|null $from input locale of the $timeString parameter (`Carbon::getLocale()` by default) * @param string|null $to output locale of the result returned (`"en"` by default) * @param int $mode specify what to translate with options: * - CarbonInterface::TRANSLATE_ALL (default) * - CarbonInterface::TRANSLATE_MONTHS * - CarbonInterface::TRANSLATE_DAYS * - CarbonInterface::TRANSLATE_UNITS * - CarbonInterface::TRANSLATE_MERIDIEM * You can use pipe to group: CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS * * @return string */ public static function translateTimeString( string $timeString, ?string $from = null, ?string $to = null, int $mode = CarbonInterface::TRANSLATE_ALL, ): string { // Fallback source and destination locales $from = $from ?: static::getLocale(); $to = $to ?: CarbonInterface::DEFAULT_LOCALE; if ($from === $to) { return $timeString; } // Standardize apostrophe $timeString = strtr($timeString, ['’' => "'"]); $fromTranslations = []; $toTranslations = []; foreach (['from', 'to'] as $key) { $language = $$key; $translator = Translator::get($language); $translations = $translator->getMessages(); if (!isset($translations[$language])) { return $timeString; } $translationKey = $key.'Translations'; $messages = $translations[$language]; $months = $messages['months'] ?? []; $weekdays = $messages['weekdays'] ?? []; $meridiem = $messages['meridiem'] ?? ['AM', 'PM']; if (isset($messages['ordinal_words'])) { $timeString = self::replaceOrdinalWords( $timeString, $key === 'from' ? array_flip($messages['ordinal_words']) : $messages['ordinal_words'] ); } if ($key === 'from') { foreach (['months', 'weekdays'] as $variable) { $list = $messages[$variable.'_standalone'] ?? null; if ($list) { foreach ($$variable as $index => &$name) { $name .= '|'.$list[$index]; } } } } $$translationKey = array_merge( $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($months, static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($messages['months_short'] ?? [], static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($weekdays, static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($messages['weekdays_short'] ?? [], static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DIFF ? self::translateWordsByKeys([ 'diff_now', 'diff_today', 'diff_yesterday', 'diff_tomorrow', 'diff_before_yesterday', 'diff_after_tomorrow', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_UNITS ? self::translateWordsByKeys([ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_MERIDIEM ? array_map(function ($hour) use ($meridiem) { if (\is_array($meridiem)) { return $meridiem[$hour < static::HOURS_PER_DAY / 2 ? 0 : 1]; } return $meridiem($hour, 0, false); }, range(0, 23)) : [], ); } return substr(preg_replace_callback('/(?<=[\d\s+.\/,_-])('.implode('|', $fromTranslations).')(?=[\d\s+.\/,_-])/iu', function ($match) use ($fromTranslations, $toTranslations) { [$chunk] = $match; foreach ($fromTranslations as $index => $word) { if (preg_match("/^$word\$/iu", $chunk)) { return $toTranslations[$index] ?? ''; } } return $chunk; // @codeCoverageIgnore }, " $timeString "), 1, -1); } /** * Translate a time string from the current locale (`$date->locale()`) to another one. * * @param string $timeString time string to translate * @param string|null $to output locale of the result returned ("en" by default) * * @return string */ public function translateTimeStringTo(string $timeString, ?string $to = null): string { return static::translateTimeString($timeString, $this->getTranslatorLocale(), $to); } /** * Get/set the locale for the current instance. * * @param string|null $locale * @param string ...$fallbackLocales * * @return $this|string */ public function locale(?string $locale = null, string ...$fallbackLocales): static|string { if ($locale === null) { return $this->getTranslatorLocale(); } if (!$this->localTranslator || $this->getTranslatorLocale($this->localTranslator) !== $locale) { $translator = Translator::get($locale); if (!empty($fallbackLocales)) { $translator->setFallbackLocales($fallbackLocales); foreach ($fallbackLocales as $fallbackLocale) { $messages = Translator::get($fallbackLocale)->getMessages(); if (isset($messages[$fallbackLocale])) { $translator->setMessages($fallbackLocale, $messages[$fallbackLocale]); } } } $this->localTranslator = $translator; } return $this; } /** * Get the current translator locale. * * @return string */ public static function getLocale(): string { return static::getLocaleAwareTranslator()->getLocale(); } /** * Set the current translator locale and indicate if the source locale file exists. * Pass 'auto' as locale to use the closest language to the current LC_TIME locale. * * @param string $locale locale ex. en */ public static function setLocale(string $locale): void { static::getLocaleAwareTranslator()->setLocale($locale); } /** * Set the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales * * @param string $locale */ public static function setFallbackLocale(string $locale): void { $translator = static::getTranslator(); if (method_exists($translator, 'setFallbackLocales')) { $translator->setFallbackLocales([$locale]); if ($translator instanceof Translator) { $preferredLocale = $translator->getLocale(); $translator->setMessages($preferredLocale, array_replace_recursive( $translator->getMessages()[$locale] ?? [], Translator::get($locale)->getMessages()[$locale] ?? [], $translator->getMessages($preferredLocale), )); } } } /** * Get the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales */ public static function getFallbackLocale(): ?string { $translator = static::getTranslator(); if (method_exists($translator, 'getFallbackLocales')) { return $translator->getFallbackLocales()[0] ?? null; } return null; } /** * Set the current locale to the given, execute the passed function, reset the locale to previous one, * then return the result of the closure (or null if the closure was void). * * @param string $locale locale ex. en * @param callable $func * * @return mixed */ public static function executeWithLocale(string $locale, callable $func): mixed { $currentLocale = static::getLocale(); static::setLocale($locale); $newLocale = static::getLocale(); $result = $func( $newLocale === 'en' && strtolower(substr((string) $locale, 0, 2)) !== 'en' ? false : $newLocale, static::getTranslator(), ); static::setLocale($currentLocale); return $result; } /** * Returns true if the given locale is internally supported and has short-units support. * Support is considered enabled if either year, day or hour has a short variant translated. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasShortUnits(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return ($newLocale && (($y = static::translateWith($translator, 'y')) !== 'y' && $y !== static::translateWith($translator, 'year'))) || ( ($y = static::translateWith($translator, 'd')) !== 'd' && $y !== static::translateWith($translator, 'day') ) || ( ($y = static::translateWith($translator, 'h')) !== 'h' && $y !== static::translateWith($translator, 'hour') ); }); } /** * Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffSyntax(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { if (!$newLocale) { return false; } foreach (['ago', 'from_now', 'before', 'after'] as $key) { if ($translator instanceof TranslatorBagInterface && self::getFromCatalogue($translator, $translator->getCatalogue($newLocale), $key) instanceof Closure ) { continue; } if ($translator->trans($key) === $key) { return false; } } return true; }); } /** * Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow). * Support is considered enabled if the 3 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffOneDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_now') !== 'diff_now' && $translator->trans('diff_yesterday') !== 'diff_yesterday' && $translator->trans('diff_tomorrow') !== 'diff_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow). * Support is considered enabled if the 2 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffTwoDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_before_yesterday') !== 'diff_before_yesterday' && $translator->trans('diff_after_tomorrow') !== 'diff_after_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasPeriodSyntax($locale) { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('period_recurrences') !== 'period_recurrences' && $translator->trans('period_interval') !== 'period_interval' && $translator->trans('period_start_date') !== 'period_start_date' && $translator->trans('period_end_date') !== 'period_end_date'; }); } /** * Returns the list of internally available locales and already loaded custom locales. * (It will ignore custom translator dynamic loading.) * * @return array */ public static function getAvailableLocales() { $translator = static::getLocaleAwareTranslator(); return $translator instanceof Translator ? $translator->getAvailableLocales() : [$translator->getLocale()]; } /** * Returns list of Language object for each available locale. This object allow you to get the ISO name, native * name, region and variant of the locale. * * @return Language[] */ public static function getAvailableLocalesInfo() { $languages = []; foreach (static::getAvailableLocales() as $id) { $languages[$id] = new Language($id); } return $languages; } /** * Get the locale of a given translator. * * If null or omitted, current local translator is used. * If no local translator is in use, current global translator is used. */ protected function getTranslatorLocale($translator = null): ?string { if (\func_num_args() === 0) { $translator = $this->getLocalTranslator(); } $translator = static::getLocaleAwareTranslator($translator); return $translator?->getLocale(); } /** * Throw an error if passed object is not LocaleAwareInterface. * * @param LocaleAwareInterface|null $translator * * @return LocaleAwareInterface|null */ protected static function getLocaleAwareTranslator($translator = null) { if (\func_num_args() === 0) { $translator = static::getTranslator(); } if ($translator && !($translator instanceof LocaleAwareInterface || method_exists($translator, 'getLocale'))) { throw new NotLocaleAwareException($translator); // @codeCoverageIgnore } return $translator; } /** * @param mixed $translator * @param \Symfony\Component\Translation\MessageCatalogueInterface $catalogue * * @return mixed */ private static function getFromCatalogue($translator, $catalogue, string $id, string $domain = 'messages') { return $translator instanceof TranslatorStrongTypeInterface ? $translator->getFromCatalogue($catalogue, $id, $domain) : $catalogue->get($id, $domain); // @codeCoverageIgnore } /** * Return the word cleaned from its translation codes. * * @param string $word * * @return string */ private static function cleanWordFromTranslationString($word) { $word = str_replace([':count', '%count', ':time'], '', $word); $word = strtr($word, ['’' => "'"]); $word = preg_replace( '/\{(?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?}|[\[\]](?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?[\[\]]/', '', $word, ); return trim($word); } /** * Translate a list of words. * * @param string[] $keys keys to translate. * @param string[] $messages messages bag handling translations. * @param string $key 'to' (to get the translation) or 'from' (to get the detection RegExp pattern). * * @return string[] */ private static function translateWordsByKeys($keys, $messages, $key): array { return array_map(function ($wordKey) use ($messages, $key) { $message = $key === 'from' && isset($messages[$wordKey.'_regexp']) ? $messages[$wordKey.'_regexp'] : ($messages[$wordKey] ?? null); if (!$message) { return '>>DO NOT REPLACE<<'; } $parts = explode('|', $message); return $key === 'to' ? self::cleanWordFromTranslationString(end($parts)) : '(?:'.implode('|', array_map(static::cleanWordFromTranslationString(...), $parts)).')'; }, $keys); } /** * Get an array of translations based on the current date. * * @param callable $translation * @param int $length * @param string $timeString * * @return string[] */ private static function getTranslationArray($translation, $length, $timeString): array { $filler = '>>DO NOT REPLACE<<'; if (\is_array($translation)) { return array_pad($translation, $length, $filler); } $list = []; $date = static::now(); for ($i = 0; $i < $length; $i++) { $list[] = $translation($date, $timeString, $i) ?? $filler; } return $list; } private static function replaceOrdinalWords(string $timeString, array $ordinalWords): string { return preg_replace_callback('/(?<![a-z])[a-z]+(?![a-z])/i', function (array $match) use ($ordinalWords) { return $ordinalWords[mb_strtolower($match[0])] ?? $match[0]; }, $timeString); } }
PHP
{ "end_line": 212, "name": "translateNumber", "signature": "public function translateNumber(int $number): string", "start_line": 171 }
{ "class_name": "Localization", "class_signature": "trait Localization", "namespace": "Carbon\\Traits" }
translateTimeString
Carbon/src/Carbon/Traits/Localization.php
public static function translateTimeString( string $timeString, ?string $from = null, ?string $to = null, int $mode = CarbonInterface::TRANSLATE_ALL, ): string { // Fallback source and destination locales $from = $from ?: static::getLocale(); $to = $to ?: CarbonInterface::DEFAULT_LOCALE; if ($from === $to) { return $timeString; } // Standardize apostrophe $timeString = strtr($timeString, ['’' => "'"]); $fromTranslations = []; $toTranslations = []; foreach (['from', 'to'] as $key) { $language = $$key; $translator = Translator::get($language); $translations = $translator->getMessages(); if (!isset($translations[$language])) { return $timeString; } $translationKey = $key.'Translations'; $messages = $translations[$language]; $months = $messages['months'] ?? []; $weekdays = $messages['weekdays'] ?? []; $meridiem = $messages['meridiem'] ?? ['AM', 'PM']; if (isset($messages['ordinal_words'])) { $timeString = self::replaceOrdinalWords( $timeString, $key === 'from' ? array_flip($messages['ordinal_words']) : $messages['ordinal_words'] ); } if ($key === 'from') { foreach (['months', 'weekdays'] as $variable) { $list = $messages[$variable.'_standalone'] ?? null; if ($list) { foreach ($$variable as $index => &$name) { $name .= '|'.$list[$index]; } } } } $$translationKey = array_merge( $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($months, static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($messages['months_short'] ?? [], static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($weekdays, static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($messages['weekdays_short'] ?? [], static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DIFF ? self::translateWordsByKeys([ 'diff_now', 'diff_today', 'diff_yesterday', 'diff_tomorrow', 'diff_before_yesterday', 'diff_after_tomorrow', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_UNITS ? self::translateWordsByKeys([ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_MERIDIEM ? array_map(function ($hour) use ($meridiem) { if (\is_array($meridiem)) { return $meridiem[$hour < static::HOURS_PER_DAY / 2 ? 0 : 1]; } return $meridiem($hour, 0, false); }, range(0, 23)) : [], ); } return substr(preg_replace_callback('/(?<=[\d\s+.\/,_-])('.implode('|', $fromTranslations).')(?=[\d\s+.\/,_-])/iu', function ($match) use ($fromTranslations, $toTranslations) { [$chunk] = $match; foreach ($fromTranslations as $index => $word) { if (preg_match("/^$word\$/iu", $chunk)) { return $toTranslations[$index] ?? ''; } } return $chunk; // @codeCoverageIgnore }, " $timeString "), 1, -1); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidTypeException; use Carbon\Exceptions\NotLocaleAwareException; use Carbon\Language; use Carbon\Translator; use Carbon\TranslatorStrongTypeInterface; use Closure; use Symfony\Component\Translation\TranslatorBagInterface; use Symfony\Contracts\Translation\LocaleAwareInterface; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Localization. * * Embed default and locale translators and translation base methods. */ trait Localization { use StaticLocalization; /** * Specific translator of the current instance. */ protected ?TranslatorInterface $localTranslator = null; /** * Return true if the current instance has its own translator. */ public function hasLocalTranslator(): bool { return isset($this->localTranslator); } /** * Get the translator of the current instance or the default if none set. */ public function getLocalTranslator(): TranslatorInterface { return $this->localTranslator ?? $this->transmitFactory(static fn () => static::getTranslator()); } /** * Set the translator for the current instance. */ public function setLocalTranslator(TranslatorInterface $translator): self { $this->localTranslator = $translator; return $this; } /** * Returns raw translation message for a given key. * * @param TranslatorInterface|null $translator the translator to use * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * * @return string|Closure|null */ public static function getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null) { if (!($translator instanceof TranslatorBagInterface && $translator instanceof TranslatorInterface)) { throw new InvalidTypeException( 'Translator does not implement '.TranslatorInterface::class.' and '.TranslatorBagInterface::class.'. '. (\is_object($translator) ? \get_class($translator) : \gettype($translator)).' has been given.', ); } if (!$locale && $translator instanceof LocaleAwareInterface) { $locale = $translator->getLocale(); } $result = self::getFromCatalogue($translator, $translator->getCatalogue($locale), $key); return $result === $key ? $default : $result; } /** * Returns raw translation message for a given key. * * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * @param TranslatorInterface $translator an optional translator to use * * @return string */ public function getTranslationMessage(string $key, ?string $locale = null, ?string $default = null, $translator = null) { return static::getTranslationMessageWith($translator ?? $this->getLocalTranslator(), $key, $locale, $default); } /** * Translate using translation string or callback available. * * @param TranslatorInterface $translator an optional translator to use * @param string $key key to find * @param array $parameters replacement parameters * @param int|float|null $number number if plural * * @return string */ public static function translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null): string { $message = static::getTranslationMessageWith($translator, $key, null, $key); if ($message instanceof Closure) { return (string) $message(...array_values($parameters)); } if ($number !== null) { $parameters['%count%'] = $number; } if (isset($parameters['%count%'])) { $parameters[':count'] = $parameters['%count%']; } return (string) $translator->trans($key, $parameters); } /** * Translate using translation string or callback available. * * @param string $key key to find * @param array $parameters replacement parameters * @param string|int|float|null $number number if plural * @param TranslatorInterface|null $translator an optional translator to use * @param bool $altNumbers pass true to use alternative numbers * * @return string */ public function translate( string $key, array $parameters = [], string|int|float|null $number = null, ?TranslatorInterface $translator = null, bool $altNumbers = false, ): string { $translation = static::translateWith($translator ?? $this->getLocalTranslator(), $key, $parameters, $number); if ($number !== null && $altNumbers) { return str_replace((string) $number, $this->translateNumber((int) $number), $translation); } return $translation; } /** * Returns the alternative number for a given integer if available in the current locale. * * @param int $number * * @return string */ public function translateNumber(int $number): string { $translateKey = "alt_numbers.$number"; $symbol = $this->translate($translateKey); if ($symbol !== $translateKey) { return $symbol; } if ($number > 99 && $this->translate('alt_numbers.99') !== 'alt_numbers.99') { $start = ''; foreach ([10000, 1000, 100] as $exp) { $key = "alt_numbers_pow.$exp"; if ($number >= $exp && $number < $exp * 10 && ($pow = $this->translate($key)) !== $key) { $unit = floor($number / $exp); $number -= $unit * $exp; $start .= ($unit > 1 ? $this->translate("alt_numbers.$unit") : '').$pow; } } $result = ''; while ($number) { $chunk = $number % 100; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 100); } return "$start$result"; } if ($number > 9 && $this->translate('alt_numbers.9') !== 'alt_numbers.9') { $result = ''; while ($number) { $chunk = $number % 10; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 10); } return $result; } return (string) $number; } /** * Translate a time string from a locale to an other. * * @param string $timeString date/time/duration string to translate (may also contain English) * @param string|null $from input locale of the $timeString parameter (`Carbon::getLocale()` by default) * @param string|null $to output locale of the result returned (`"en"` by default) * @param int $mode specify what to translate with options: * - CarbonInterface::TRANSLATE_ALL (default) * - CarbonInterface::TRANSLATE_MONTHS * - CarbonInterface::TRANSLATE_DAYS * - CarbonInterface::TRANSLATE_UNITS * - CarbonInterface::TRANSLATE_MERIDIEM * You can use pipe to group: CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS * * @return string */ public static function translateTimeString( string $timeString, ?string $from = null, ?string $to = null, int $mode = CarbonInterface::TRANSLATE_ALL, ): string { // Fallback source and destination locales $from = $from ?: static::getLocale(); $to = $to ?: CarbonInterface::DEFAULT_LOCALE; if ($from === $to) { return $timeString; } // Standardize apostrophe $timeString = strtr($timeString, ['’' => "'"]); $fromTranslations = []; $toTranslations = []; foreach (['from', 'to'] as $key) { $language = $$key; $translator = Translator::get($language); $translations = $translator->getMessages(); if (!isset($translations[$language])) { return $timeString; } $translationKey = $key.'Translations'; $messages = $translations[$language]; $months = $messages['months'] ?? []; $weekdays = $messages['weekdays'] ?? []; $meridiem = $messages['meridiem'] ?? ['AM', 'PM']; if (isset($messages['ordinal_words'])) { $timeString = self::replaceOrdinalWords( $timeString, $key === 'from' ? array_flip($messages['ordinal_words']) : $messages['ordinal_words'] ); } if ($key === 'from') { foreach (['months', 'weekdays'] as $variable) { $list = $messages[$variable.'_standalone'] ?? null; if ($list) { foreach ($$variable as $index => &$name) { $name .= '|'.$list[$index]; } } } } $$translationKey = array_merge( $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($months, static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($messages['months_short'] ?? [], static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($weekdays, static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($messages['weekdays_short'] ?? [], static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DIFF ? self::translateWordsByKeys([ 'diff_now', 'diff_today', 'diff_yesterday', 'diff_tomorrow', 'diff_before_yesterday', 'diff_after_tomorrow', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_UNITS ? self::translateWordsByKeys([ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_MERIDIEM ? array_map(function ($hour) use ($meridiem) { if (\is_array($meridiem)) { return $meridiem[$hour < static::HOURS_PER_DAY / 2 ? 0 : 1]; } return $meridiem($hour, 0, false); }, range(0, 23)) : [], ); } return substr(preg_replace_callback('/(?<=[\d\s+.\/,_-])('.implode('|', $fromTranslations).')(?=[\d\s+.\/,_-])/iu', function ($match) use ($fromTranslations, $toTranslations) { [$chunk] = $match; foreach ($fromTranslations as $index => $word) { if (preg_match("/^$word\$/iu", $chunk)) { return $toTranslations[$index] ?? ''; } } return $chunk; // @codeCoverageIgnore }, " $timeString "), 1, -1); } /** * Translate a time string from the current locale (`$date->locale()`) to another one. * * @param string $timeString time string to translate * @param string|null $to output locale of the result returned ("en" by default) * * @return string */ public function translateTimeStringTo(string $timeString, ?string $to = null): string { return static::translateTimeString($timeString, $this->getTranslatorLocale(), $to); } /** * Get/set the locale for the current instance. * * @param string|null $locale * @param string ...$fallbackLocales * * @return $this|string */ public function locale(?string $locale = null, string ...$fallbackLocales): static|string { if ($locale === null) { return $this->getTranslatorLocale(); } if (!$this->localTranslator || $this->getTranslatorLocale($this->localTranslator) !== $locale) { $translator = Translator::get($locale); if (!empty($fallbackLocales)) { $translator->setFallbackLocales($fallbackLocales); foreach ($fallbackLocales as $fallbackLocale) { $messages = Translator::get($fallbackLocale)->getMessages(); if (isset($messages[$fallbackLocale])) { $translator->setMessages($fallbackLocale, $messages[$fallbackLocale]); } } } $this->localTranslator = $translator; } return $this; } /** * Get the current translator locale. * * @return string */ public static function getLocale(): string { return static::getLocaleAwareTranslator()->getLocale(); } /** * Set the current translator locale and indicate if the source locale file exists. * Pass 'auto' as locale to use the closest language to the current LC_TIME locale. * * @param string $locale locale ex. en */ public static function setLocale(string $locale): void { static::getLocaleAwareTranslator()->setLocale($locale); } /** * Set the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales * * @param string $locale */ public static function setFallbackLocale(string $locale): void { $translator = static::getTranslator(); if (method_exists($translator, 'setFallbackLocales')) { $translator->setFallbackLocales([$locale]); if ($translator instanceof Translator) { $preferredLocale = $translator->getLocale(); $translator->setMessages($preferredLocale, array_replace_recursive( $translator->getMessages()[$locale] ?? [], Translator::get($locale)->getMessages()[$locale] ?? [], $translator->getMessages($preferredLocale), )); } } } /** * Get the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales */ public static function getFallbackLocale(): ?string { $translator = static::getTranslator(); if (method_exists($translator, 'getFallbackLocales')) { return $translator->getFallbackLocales()[0] ?? null; } return null; } /** * Set the current locale to the given, execute the passed function, reset the locale to previous one, * then return the result of the closure (or null if the closure was void). * * @param string $locale locale ex. en * @param callable $func * * @return mixed */ public static function executeWithLocale(string $locale, callable $func): mixed { $currentLocale = static::getLocale(); static::setLocale($locale); $newLocale = static::getLocale(); $result = $func( $newLocale === 'en' && strtolower(substr((string) $locale, 0, 2)) !== 'en' ? false : $newLocale, static::getTranslator(), ); static::setLocale($currentLocale); return $result; } /** * Returns true if the given locale is internally supported and has short-units support. * Support is considered enabled if either year, day or hour has a short variant translated. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasShortUnits(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return ($newLocale && (($y = static::translateWith($translator, 'y')) !== 'y' && $y !== static::translateWith($translator, 'year'))) || ( ($y = static::translateWith($translator, 'd')) !== 'd' && $y !== static::translateWith($translator, 'day') ) || ( ($y = static::translateWith($translator, 'h')) !== 'h' && $y !== static::translateWith($translator, 'hour') ); }); } /** * Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffSyntax(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { if (!$newLocale) { return false; } foreach (['ago', 'from_now', 'before', 'after'] as $key) { if ($translator instanceof TranslatorBagInterface && self::getFromCatalogue($translator, $translator->getCatalogue($newLocale), $key) instanceof Closure ) { continue; } if ($translator->trans($key) === $key) { return false; } } return true; }); } /** * Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow). * Support is considered enabled if the 3 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffOneDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_now') !== 'diff_now' && $translator->trans('diff_yesterday') !== 'diff_yesterday' && $translator->trans('diff_tomorrow') !== 'diff_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow). * Support is considered enabled if the 2 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffTwoDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_before_yesterday') !== 'diff_before_yesterday' && $translator->trans('diff_after_tomorrow') !== 'diff_after_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasPeriodSyntax($locale) { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('period_recurrences') !== 'period_recurrences' && $translator->trans('period_interval') !== 'period_interval' && $translator->trans('period_start_date') !== 'period_start_date' && $translator->trans('period_end_date') !== 'period_end_date'; }); } /** * Returns the list of internally available locales and already loaded custom locales. * (It will ignore custom translator dynamic loading.) * * @return array */ public static function getAvailableLocales() { $translator = static::getLocaleAwareTranslator(); return $translator instanceof Translator ? $translator->getAvailableLocales() : [$translator->getLocale()]; } /** * Returns list of Language object for each available locale. This object allow you to get the ISO name, native * name, region and variant of the locale. * * @return Language[] */ public static function getAvailableLocalesInfo() { $languages = []; foreach (static::getAvailableLocales() as $id) { $languages[$id] = new Language($id); } return $languages; } /** * Get the locale of a given translator. * * If null or omitted, current local translator is used. * If no local translator is in use, current global translator is used. */ protected function getTranslatorLocale($translator = null): ?string { if (\func_num_args() === 0) { $translator = $this->getLocalTranslator(); } $translator = static::getLocaleAwareTranslator($translator); return $translator?->getLocale(); } /** * Throw an error if passed object is not LocaleAwareInterface. * * @param LocaleAwareInterface|null $translator * * @return LocaleAwareInterface|null */ protected static function getLocaleAwareTranslator($translator = null) { if (\func_num_args() === 0) { $translator = static::getTranslator(); } if ($translator && !($translator instanceof LocaleAwareInterface || method_exists($translator, 'getLocale'))) { throw new NotLocaleAwareException($translator); // @codeCoverageIgnore } return $translator; } /** * @param mixed $translator * @param \Symfony\Component\Translation\MessageCatalogueInterface $catalogue * * @return mixed */ private static function getFromCatalogue($translator, $catalogue, string $id, string $domain = 'messages') { return $translator instanceof TranslatorStrongTypeInterface ? $translator->getFromCatalogue($catalogue, $id, $domain) : $catalogue->get($id, $domain); // @codeCoverageIgnore } /** * Return the word cleaned from its translation codes. * * @param string $word * * @return string */ private static function cleanWordFromTranslationString($word) { $word = str_replace([':count', '%count', ':time'], '', $word); $word = strtr($word, ['’' => "'"]); $word = preg_replace( '/\{(?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?}|[\[\]](?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?[\[\]]/', '', $word, ); return trim($word); } /** * Translate a list of words. * * @param string[] $keys keys to translate. * @param string[] $messages messages bag handling translations. * @param string $key 'to' (to get the translation) or 'from' (to get the detection RegExp pattern). * * @return string[] */ private static function translateWordsByKeys($keys, $messages, $key): array { return array_map(function ($wordKey) use ($messages, $key) { $message = $key === 'from' && isset($messages[$wordKey.'_regexp']) ? $messages[$wordKey.'_regexp'] : ($messages[$wordKey] ?? null); if (!$message) { return '>>DO NOT REPLACE<<'; } $parts = explode('|', $message); return $key === 'to' ? self::cleanWordFromTranslationString(end($parts)) : '(?:'.implode('|', array_map(static::cleanWordFromTranslationString(...), $parts)).')'; }, $keys); } /** * Get an array of translations based on the current date. * * @param callable $translation * @param int $length * @param string $timeString * * @return string[] */ private static function getTranslationArray($translation, $length, $timeString): array { $filler = '>>DO NOT REPLACE<<'; if (\is_array($translation)) { return array_pad($translation, $length, $filler); } $list = []; $date = static::now(); for ($i = 0; $i < $length; $i++) { $list[] = $translation($date, $timeString, $i) ?? $filler; } return $list; } private static function replaceOrdinalWords(string $timeString, array $ordinalWords): string { return preg_replace_callback('/(?<![a-z])[a-z]+(?![a-z])/i', function (array $match) use ($ordinalWords) { return $ordinalWords[mb_strtolower($match[0])] ?? $match[0]; }, $timeString); } }
PHP
{ "end_line": 327, "name": "translateTimeString", "signature": "public static function translateTimeString(", "start_line": 230 }
{ "class_name": "Localization", "class_signature": "trait Localization", "namespace": "Carbon\\Traits" }
locale
Carbon/src/Carbon/Traits/Localization.php
public function locale(?string $locale = null, string ...$fallbackLocales): static|string { if ($locale === null) { return $this->getTranslatorLocale(); } if (!$this->localTranslator || $this->getTranslatorLocale($this->localTranslator) !== $locale) { $translator = Translator::get($locale); if (!empty($fallbackLocales)) { $translator->setFallbackLocales($fallbackLocales); foreach ($fallbackLocales as $fallbackLocale) { $messages = Translator::get($fallbackLocale)->getMessages(); if (isset($messages[$fallbackLocale])) { $translator->setMessages($fallbackLocale, $messages[$fallbackLocale]); } } } $this->localTranslator = $translator; } return $this; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidTypeException; use Carbon\Exceptions\NotLocaleAwareException; use Carbon\Language; use Carbon\Translator; use Carbon\TranslatorStrongTypeInterface; use Closure; use Symfony\Component\Translation\TranslatorBagInterface; use Symfony\Contracts\Translation\LocaleAwareInterface; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Localization. * * Embed default and locale translators and translation base methods. */ trait Localization { use StaticLocalization; /** * Specific translator of the current instance. */ protected ?TranslatorInterface $localTranslator = null; /** * Return true if the current instance has its own translator. */ public function hasLocalTranslator(): bool { return isset($this->localTranslator); } /** * Get the translator of the current instance or the default if none set. */ public function getLocalTranslator(): TranslatorInterface { return $this->localTranslator ?? $this->transmitFactory(static fn () => static::getTranslator()); } /** * Set the translator for the current instance. */ public function setLocalTranslator(TranslatorInterface $translator): self { $this->localTranslator = $translator; return $this; } /** * Returns raw translation message for a given key. * * @param TranslatorInterface|null $translator the translator to use * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * * @return string|Closure|null */ public static function getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null) { if (!($translator instanceof TranslatorBagInterface && $translator instanceof TranslatorInterface)) { throw new InvalidTypeException( 'Translator does not implement '.TranslatorInterface::class.' and '.TranslatorBagInterface::class.'. '. (\is_object($translator) ? \get_class($translator) : \gettype($translator)).' has been given.', ); } if (!$locale && $translator instanceof LocaleAwareInterface) { $locale = $translator->getLocale(); } $result = self::getFromCatalogue($translator, $translator->getCatalogue($locale), $key); return $result === $key ? $default : $result; } /** * Returns raw translation message for a given key. * * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * @param TranslatorInterface $translator an optional translator to use * * @return string */ public function getTranslationMessage(string $key, ?string $locale = null, ?string $default = null, $translator = null) { return static::getTranslationMessageWith($translator ?? $this->getLocalTranslator(), $key, $locale, $default); } /** * Translate using translation string or callback available. * * @param TranslatorInterface $translator an optional translator to use * @param string $key key to find * @param array $parameters replacement parameters * @param int|float|null $number number if plural * * @return string */ public static function translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null): string { $message = static::getTranslationMessageWith($translator, $key, null, $key); if ($message instanceof Closure) { return (string) $message(...array_values($parameters)); } if ($number !== null) { $parameters['%count%'] = $number; } if (isset($parameters['%count%'])) { $parameters[':count'] = $parameters['%count%']; } return (string) $translator->trans($key, $parameters); } /** * Translate using translation string or callback available. * * @param string $key key to find * @param array $parameters replacement parameters * @param string|int|float|null $number number if plural * @param TranslatorInterface|null $translator an optional translator to use * @param bool $altNumbers pass true to use alternative numbers * * @return string */ public function translate( string $key, array $parameters = [], string|int|float|null $number = null, ?TranslatorInterface $translator = null, bool $altNumbers = false, ): string { $translation = static::translateWith($translator ?? $this->getLocalTranslator(), $key, $parameters, $number); if ($number !== null && $altNumbers) { return str_replace((string) $number, $this->translateNumber((int) $number), $translation); } return $translation; } /** * Returns the alternative number for a given integer if available in the current locale. * * @param int $number * * @return string */ public function translateNumber(int $number): string { $translateKey = "alt_numbers.$number"; $symbol = $this->translate($translateKey); if ($symbol !== $translateKey) { return $symbol; } if ($number > 99 && $this->translate('alt_numbers.99') !== 'alt_numbers.99') { $start = ''; foreach ([10000, 1000, 100] as $exp) { $key = "alt_numbers_pow.$exp"; if ($number >= $exp && $number < $exp * 10 && ($pow = $this->translate($key)) !== $key) { $unit = floor($number / $exp); $number -= $unit * $exp; $start .= ($unit > 1 ? $this->translate("alt_numbers.$unit") : '').$pow; } } $result = ''; while ($number) { $chunk = $number % 100; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 100); } return "$start$result"; } if ($number > 9 && $this->translate('alt_numbers.9') !== 'alt_numbers.9') { $result = ''; while ($number) { $chunk = $number % 10; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 10); } return $result; } return (string) $number; } /** * Translate a time string from a locale to an other. * * @param string $timeString date/time/duration string to translate (may also contain English) * @param string|null $from input locale of the $timeString parameter (`Carbon::getLocale()` by default) * @param string|null $to output locale of the result returned (`"en"` by default) * @param int $mode specify what to translate with options: * - CarbonInterface::TRANSLATE_ALL (default) * - CarbonInterface::TRANSLATE_MONTHS * - CarbonInterface::TRANSLATE_DAYS * - CarbonInterface::TRANSLATE_UNITS * - CarbonInterface::TRANSLATE_MERIDIEM * You can use pipe to group: CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS * * @return string */ public static function translateTimeString( string $timeString, ?string $from = null, ?string $to = null, int $mode = CarbonInterface::TRANSLATE_ALL, ): string { // Fallback source and destination locales $from = $from ?: static::getLocale(); $to = $to ?: CarbonInterface::DEFAULT_LOCALE; if ($from === $to) { return $timeString; } // Standardize apostrophe $timeString = strtr($timeString, ['’' => "'"]); $fromTranslations = []; $toTranslations = []; foreach (['from', 'to'] as $key) { $language = $$key; $translator = Translator::get($language); $translations = $translator->getMessages(); if (!isset($translations[$language])) { return $timeString; } $translationKey = $key.'Translations'; $messages = $translations[$language]; $months = $messages['months'] ?? []; $weekdays = $messages['weekdays'] ?? []; $meridiem = $messages['meridiem'] ?? ['AM', 'PM']; if (isset($messages['ordinal_words'])) { $timeString = self::replaceOrdinalWords( $timeString, $key === 'from' ? array_flip($messages['ordinal_words']) : $messages['ordinal_words'] ); } if ($key === 'from') { foreach (['months', 'weekdays'] as $variable) { $list = $messages[$variable.'_standalone'] ?? null; if ($list) { foreach ($$variable as $index => &$name) { $name .= '|'.$list[$index]; } } } } $$translationKey = array_merge( $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($months, static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($messages['months_short'] ?? [], static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($weekdays, static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($messages['weekdays_short'] ?? [], static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DIFF ? self::translateWordsByKeys([ 'diff_now', 'diff_today', 'diff_yesterday', 'diff_tomorrow', 'diff_before_yesterday', 'diff_after_tomorrow', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_UNITS ? self::translateWordsByKeys([ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_MERIDIEM ? array_map(function ($hour) use ($meridiem) { if (\is_array($meridiem)) { return $meridiem[$hour < static::HOURS_PER_DAY / 2 ? 0 : 1]; } return $meridiem($hour, 0, false); }, range(0, 23)) : [], ); } return substr(preg_replace_callback('/(?<=[\d\s+.\/,_-])('.implode('|', $fromTranslations).')(?=[\d\s+.\/,_-])/iu', function ($match) use ($fromTranslations, $toTranslations) { [$chunk] = $match; foreach ($fromTranslations as $index => $word) { if (preg_match("/^$word\$/iu", $chunk)) { return $toTranslations[$index] ?? ''; } } return $chunk; // @codeCoverageIgnore }, " $timeString "), 1, -1); } /** * Translate a time string from the current locale (`$date->locale()`) to another one. * * @param string $timeString time string to translate * @param string|null $to output locale of the result returned ("en" by default) * * @return string */ public function translateTimeStringTo(string $timeString, ?string $to = null): string { return static::translateTimeString($timeString, $this->getTranslatorLocale(), $to); } /** * Get/set the locale for the current instance. * * @param string|null $locale * @param string ...$fallbackLocales * * @return $this|string */ public function locale(?string $locale = null, string ...$fallbackLocales): static|string { if ($locale === null) { return $this->getTranslatorLocale(); } if (!$this->localTranslator || $this->getTranslatorLocale($this->localTranslator) !== $locale) { $translator = Translator::get($locale); if (!empty($fallbackLocales)) { $translator->setFallbackLocales($fallbackLocales); foreach ($fallbackLocales as $fallbackLocale) { $messages = Translator::get($fallbackLocale)->getMessages(); if (isset($messages[$fallbackLocale])) { $translator->setMessages($fallbackLocale, $messages[$fallbackLocale]); } } } $this->localTranslator = $translator; } return $this; } /** * Get the current translator locale. * * @return string */ public static function getLocale(): string { return static::getLocaleAwareTranslator()->getLocale(); } /** * Set the current translator locale and indicate if the source locale file exists. * Pass 'auto' as locale to use the closest language to the current LC_TIME locale. * * @param string $locale locale ex. en */ public static function setLocale(string $locale): void { static::getLocaleAwareTranslator()->setLocale($locale); } /** * Set the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales * * @param string $locale */ public static function setFallbackLocale(string $locale): void { $translator = static::getTranslator(); if (method_exists($translator, 'setFallbackLocales')) { $translator->setFallbackLocales([$locale]); if ($translator instanceof Translator) { $preferredLocale = $translator->getLocale(); $translator->setMessages($preferredLocale, array_replace_recursive( $translator->getMessages()[$locale] ?? [], Translator::get($locale)->getMessages()[$locale] ?? [], $translator->getMessages($preferredLocale), )); } } } /** * Get the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales */ public static function getFallbackLocale(): ?string { $translator = static::getTranslator(); if (method_exists($translator, 'getFallbackLocales')) { return $translator->getFallbackLocales()[0] ?? null; } return null; } /** * Set the current locale to the given, execute the passed function, reset the locale to previous one, * then return the result of the closure (or null if the closure was void). * * @param string $locale locale ex. en * @param callable $func * * @return mixed */ public static function executeWithLocale(string $locale, callable $func): mixed { $currentLocale = static::getLocale(); static::setLocale($locale); $newLocale = static::getLocale(); $result = $func( $newLocale === 'en' && strtolower(substr((string) $locale, 0, 2)) !== 'en' ? false : $newLocale, static::getTranslator(), ); static::setLocale($currentLocale); return $result; } /** * Returns true if the given locale is internally supported and has short-units support. * Support is considered enabled if either year, day or hour has a short variant translated. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasShortUnits(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return ($newLocale && (($y = static::translateWith($translator, 'y')) !== 'y' && $y !== static::translateWith($translator, 'year'))) || ( ($y = static::translateWith($translator, 'd')) !== 'd' && $y !== static::translateWith($translator, 'day') ) || ( ($y = static::translateWith($translator, 'h')) !== 'h' && $y !== static::translateWith($translator, 'hour') ); }); } /** * Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffSyntax(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { if (!$newLocale) { return false; } foreach (['ago', 'from_now', 'before', 'after'] as $key) { if ($translator instanceof TranslatorBagInterface && self::getFromCatalogue($translator, $translator->getCatalogue($newLocale), $key) instanceof Closure ) { continue; } if ($translator->trans($key) === $key) { return false; } } return true; }); } /** * Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow). * Support is considered enabled if the 3 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffOneDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_now') !== 'diff_now' && $translator->trans('diff_yesterday') !== 'diff_yesterday' && $translator->trans('diff_tomorrow') !== 'diff_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow). * Support is considered enabled if the 2 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffTwoDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_before_yesterday') !== 'diff_before_yesterday' && $translator->trans('diff_after_tomorrow') !== 'diff_after_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasPeriodSyntax($locale) { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('period_recurrences') !== 'period_recurrences' && $translator->trans('period_interval') !== 'period_interval' && $translator->trans('period_start_date') !== 'period_start_date' && $translator->trans('period_end_date') !== 'period_end_date'; }); } /** * Returns the list of internally available locales and already loaded custom locales. * (It will ignore custom translator dynamic loading.) * * @return array */ public static function getAvailableLocales() { $translator = static::getLocaleAwareTranslator(); return $translator instanceof Translator ? $translator->getAvailableLocales() : [$translator->getLocale()]; } /** * Returns list of Language object for each available locale. This object allow you to get the ISO name, native * name, region and variant of the locale. * * @return Language[] */ public static function getAvailableLocalesInfo() { $languages = []; foreach (static::getAvailableLocales() as $id) { $languages[$id] = new Language($id); } return $languages; } /** * Get the locale of a given translator. * * If null or omitted, current local translator is used. * If no local translator is in use, current global translator is used. */ protected function getTranslatorLocale($translator = null): ?string { if (\func_num_args() === 0) { $translator = $this->getLocalTranslator(); } $translator = static::getLocaleAwareTranslator($translator); return $translator?->getLocale(); } /** * Throw an error if passed object is not LocaleAwareInterface. * * @param LocaleAwareInterface|null $translator * * @return LocaleAwareInterface|null */ protected static function getLocaleAwareTranslator($translator = null) { if (\func_num_args() === 0) { $translator = static::getTranslator(); } if ($translator && !($translator instanceof LocaleAwareInterface || method_exists($translator, 'getLocale'))) { throw new NotLocaleAwareException($translator); // @codeCoverageIgnore } return $translator; } /** * @param mixed $translator * @param \Symfony\Component\Translation\MessageCatalogueInterface $catalogue * * @return mixed */ private static function getFromCatalogue($translator, $catalogue, string $id, string $domain = 'messages') { return $translator instanceof TranslatorStrongTypeInterface ? $translator->getFromCatalogue($catalogue, $id, $domain) : $catalogue->get($id, $domain); // @codeCoverageIgnore } /** * Return the word cleaned from its translation codes. * * @param string $word * * @return string */ private static function cleanWordFromTranslationString($word) { $word = str_replace([':count', '%count', ':time'], '', $word); $word = strtr($word, ['’' => "'"]); $word = preg_replace( '/\{(?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?}|[\[\]](?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?[\[\]]/', '', $word, ); return trim($word); } /** * Translate a list of words. * * @param string[] $keys keys to translate. * @param string[] $messages messages bag handling translations. * @param string $key 'to' (to get the translation) or 'from' (to get the detection RegExp pattern). * * @return string[] */ private static function translateWordsByKeys($keys, $messages, $key): array { return array_map(function ($wordKey) use ($messages, $key) { $message = $key === 'from' && isset($messages[$wordKey.'_regexp']) ? $messages[$wordKey.'_regexp'] : ($messages[$wordKey] ?? null); if (!$message) { return '>>DO NOT REPLACE<<'; } $parts = explode('|', $message); return $key === 'to' ? self::cleanWordFromTranslationString(end($parts)) : '(?:'.implode('|', array_map(static::cleanWordFromTranslationString(...), $parts)).')'; }, $keys); } /** * Get an array of translations based on the current date. * * @param callable $translation * @param int $length * @param string $timeString * * @return string[] */ private static function getTranslationArray($translation, $length, $timeString): array { $filler = '>>DO NOT REPLACE<<'; if (\is_array($translation)) { return array_pad($translation, $length, $filler); } $list = []; $date = static::now(); for ($i = 0; $i < $length; $i++) { $list[] = $translation($date, $timeString, $i) ?? $filler; } return $list; } private static function replaceOrdinalWords(string $timeString, array $ordinalWords): string { return preg_replace_callback('/(?<![a-z])[a-z]+(?![a-z])/i', function (array $match) use ($ordinalWords) { return $ordinalWords[mb_strtolower($match[0])] ?? $match[0]; }, $timeString); } }
PHP
{ "end_line": 375, "name": "locale", "signature": "public function locale(?string $locale = null, string ...$fallbackLocales): static|string", "start_line": 350 }
{ "class_name": "Localization", "class_signature": "trait Localization", "namespace": "Carbon\\Traits" }
executeWithLocale
Carbon/src/Carbon/Traits/Localization.php
public static function executeWithLocale(string $locale, callable $func): mixed { $currentLocale = static::getLocale(); static::setLocale($locale); $newLocale = static::getLocale(); $result = $func( $newLocale === 'en' && strtolower(substr((string) $locale, 0, 2)) !== 'en' ? false : $newLocale, static::getTranslator(), ); static::setLocale($currentLocale); return $result; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidTypeException; use Carbon\Exceptions\NotLocaleAwareException; use Carbon\Language; use Carbon\Translator; use Carbon\TranslatorStrongTypeInterface; use Closure; use Symfony\Component\Translation\TranslatorBagInterface; use Symfony\Contracts\Translation\LocaleAwareInterface; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Localization. * * Embed default and locale translators and translation base methods. */ trait Localization { use StaticLocalization; /** * Specific translator of the current instance. */ protected ?TranslatorInterface $localTranslator = null; /** * Return true if the current instance has its own translator. */ public function hasLocalTranslator(): bool { return isset($this->localTranslator); } /** * Get the translator of the current instance or the default if none set. */ public function getLocalTranslator(): TranslatorInterface { return $this->localTranslator ?? $this->transmitFactory(static fn () => static::getTranslator()); } /** * Set the translator for the current instance. */ public function setLocalTranslator(TranslatorInterface $translator): self { $this->localTranslator = $translator; return $this; } /** * Returns raw translation message for a given key. * * @param TranslatorInterface|null $translator the translator to use * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * * @return string|Closure|null */ public static function getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null) { if (!($translator instanceof TranslatorBagInterface && $translator instanceof TranslatorInterface)) { throw new InvalidTypeException( 'Translator does not implement '.TranslatorInterface::class.' and '.TranslatorBagInterface::class.'. '. (\is_object($translator) ? \get_class($translator) : \gettype($translator)).' has been given.', ); } if (!$locale && $translator instanceof LocaleAwareInterface) { $locale = $translator->getLocale(); } $result = self::getFromCatalogue($translator, $translator->getCatalogue($locale), $key); return $result === $key ? $default : $result; } /** * Returns raw translation message for a given key. * * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * @param TranslatorInterface $translator an optional translator to use * * @return string */ public function getTranslationMessage(string $key, ?string $locale = null, ?string $default = null, $translator = null) { return static::getTranslationMessageWith($translator ?? $this->getLocalTranslator(), $key, $locale, $default); } /** * Translate using translation string or callback available. * * @param TranslatorInterface $translator an optional translator to use * @param string $key key to find * @param array $parameters replacement parameters * @param int|float|null $number number if plural * * @return string */ public static function translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null): string { $message = static::getTranslationMessageWith($translator, $key, null, $key); if ($message instanceof Closure) { return (string) $message(...array_values($parameters)); } if ($number !== null) { $parameters['%count%'] = $number; } if (isset($parameters['%count%'])) { $parameters[':count'] = $parameters['%count%']; } return (string) $translator->trans($key, $parameters); } /** * Translate using translation string or callback available. * * @param string $key key to find * @param array $parameters replacement parameters * @param string|int|float|null $number number if plural * @param TranslatorInterface|null $translator an optional translator to use * @param bool $altNumbers pass true to use alternative numbers * * @return string */ public function translate( string $key, array $parameters = [], string|int|float|null $number = null, ?TranslatorInterface $translator = null, bool $altNumbers = false, ): string { $translation = static::translateWith($translator ?? $this->getLocalTranslator(), $key, $parameters, $number); if ($number !== null && $altNumbers) { return str_replace((string) $number, $this->translateNumber((int) $number), $translation); } return $translation; } /** * Returns the alternative number for a given integer if available in the current locale. * * @param int $number * * @return string */ public function translateNumber(int $number): string { $translateKey = "alt_numbers.$number"; $symbol = $this->translate($translateKey); if ($symbol !== $translateKey) { return $symbol; } if ($number > 99 && $this->translate('alt_numbers.99') !== 'alt_numbers.99') { $start = ''; foreach ([10000, 1000, 100] as $exp) { $key = "alt_numbers_pow.$exp"; if ($number >= $exp && $number < $exp * 10 && ($pow = $this->translate($key)) !== $key) { $unit = floor($number / $exp); $number -= $unit * $exp; $start .= ($unit > 1 ? $this->translate("alt_numbers.$unit") : '').$pow; } } $result = ''; while ($number) { $chunk = $number % 100; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 100); } return "$start$result"; } if ($number > 9 && $this->translate('alt_numbers.9') !== 'alt_numbers.9') { $result = ''; while ($number) { $chunk = $number % 10; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 10); } return $result; } return (string) $number; } /** * Translate a time string from a locale to an other. * * @param string $timeString date/time/duration string to translate (may also contain English) * @param string|null $from input locale of the $timeString parameter (`Carbon::getLocale()` by default) * @param string|null $to output locale of the result returned (`"en"` by default) * @param int $mode specify what to translate with options: * - CarbonInterface::TRANSLATE_ALL (default) * - CarbonInterface::TRANSLATE_MONTHS * - CarbonInterface::TRANSLATE_DAYS * - CarbonInterface::TRANSLATE_UNITS * - CarbonInterface::TRANSLATE_MERIDIEM * You can use pipe to group: CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS * * @return string */ public static function translateTimeString( string $timeString, ?string $from = null, ?string $to = null, int $mode = CarbonInterface::TRANSLATE_ALL, ): string { // Fallback source and destination locales $from = $from ?: static::getLocale(); $to = $to ?: CarbonInterface::DEFAULT_LOCALE; if ($from === $to) { return $timeString; } // Standardize apostrophe $timeString = strtr($timeString, ['’' => "'"]); $fromTranslations = []; $toTranslations = []; foreach (['from', 'to'] as $key) { $language = $$key; $translator = Translator::get($language); $translations = $translator->getMessages(); if (!isset($translations[$language])) { return $timeString; } $translationKey = $key.'Translations'; $messages = $translations[$language]; $months = $messages['months'] ?? []; $weekdays = $messages['weekdays'] ?? []; $meridiem = $messages['meridiem'] ?? ['AM', 'PM']; if (isset($messages['ordinal_words'])) { $timeString = self::replaceOrdinalWords( $timeString, $key === 'from' ? array_flip($messages['ordinal_words']) : $messages['ordinal_words'] ); } if ($key === 'from') { foreach (['months', 'weekdays'] as $variable) { $list = $messages[$variable.'_standalone'] ?? null; if ($list) { foreach ($$variable as $index => &$name) { $name .= '|'.$list[$index]; } } } } $$translationKey = array_merge( $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($months, static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($messages['months_short'] ?? [], static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($weekdays, static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($messages['weekdays_short'] ?? [], static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DIFF ? self::translateWordsByKeys([ 'diff_now', 'diff_today', 'diff_yesterday', 'diff_tomorrow', 'diff_before_yesterday', 'diff_after_tomorrow', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_UNITS ? self::translateWordsByKeys([ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_MERIDIEM ? array_map(function ($hour) use ($meridiem) { if (\is_array($meridiem)) { return $meridiem[$hour < static::HOURS_PER_DAY / 2 ? 0 : 1]; } return $meridiem($hour, 0, false); }, range(0, 23)) : [], ); } return substr(preg_replace_callback('/(?<=[\d\s+.\/,_-])('.implode('|', $fromTranslations).')(?=[\d\s+.\/,_-])/iu', function ($match) use ($fromTranslations, $toTranslations) { [$chunk] = $match; foreach ($fromTranslations as $index => $word) { if (preg_match("/^$word\$/iu", $chunk)) { return $toTranslations[$index] ?? ''; } } return $chunk; // @codeCoverageIgnore }, " $timeString "), 1, -1); } /** * Translate a time string from the current locale (`$date->locale()`) to another one. * * @param string $timeString time string to translate * @param string|null $to output locale of the result returned ("en" by default) * * @return string */ public function translateTimeStringTo(string $timeString, ?string $to = null): string { return static::translateTimeString($timeString, $this->getTranslatorLocale(), $to); } /** * Get/set the locale for the current instance. * * @param string|null $locale * @param string ...$fallbackLocales * * @return $this|string */ public function locale(?string $locale = null, string ...$fallbackLocales): static|string { if ($locale === null) { return $this->getTranslatorLocale(); } if (!$this->localTranslator || $this->getTranslatorLocale($this->localTranslator) !== $locale) { $translator = Translator::get($locale); if (!empty($fallbackLocales)) { $translator->setFallbackLocales($fallbackLocales); foreach ($fallbackLocales as $fallbackLocale) { $messages = Translator::get($fallbackLocale)->getMessages(); if (isset($messages[$fallbackLocale])) { $translator->setMessages($fallbackLocale, $messages[$fallbackLocale]); } } } $this->localTranslator = $translator; } return $this; } /** * Get the current translator locale. * * @return string */ public static function getLocale(): string { return static::getLocaleAwareTranslator()->getLocale(); } /** * Set the current translator locale and indicate if the source locale file exists. * Pass 'auto' as locale to use the closest language to the current LC_TIME locale. * * @param string $locale locale ex. en */ public static function setLocale(string $locale): void { static::getLocaleAwareTranslator()->setLocale($locale); } /** * Set the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales * * @param string $locale */ public static function setFallbackLocale(string $locale): void { $translator = static::getTranslator(); if (method_exists($translator, 'setFallbackLocales')) { $translator->setFallbackLocales([$locale]); if ($translator instanceof Translator) { $preferredLocale = $translator->getLocale(); $translator->setMessages($preferredLocale, array_replace_recursive( $translator->getMessages()[$locale] ?? [], Translator::get($locale)->getMessages()[$locale] ?? [], $translator->getMessages($preferredLocale), )); } } } /** * Get the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales */ public static function getFallbackLocale(): ?string { $translator = static::getTranslator(); if (method_exists($translator, 'getFallbackLocales')) { return $translator->getFallbackLocales()[0] ?? null; } return null; } /** * Set the current locale to the given, execute the passed function, reset the locale to previous one, * then return the result of the closure (or null if the closure was void). * * @param string $locale locale ex. en * @param callable $func * * @return mixed */ public static function executeWithLocale(string $locale, callable $func): mixed { $currentLocale = static::getLocale(); static::setLocale($locale); $newLocale = static::getLocale(); $result = $func( $newLocale === 'en' && strtolower(substr((string) $locale, 0, 2)) !== 'en' ? false : $newLocale, static::getTranslator(), ); static::setLocale($currentLocale); return $result; } /** * Returns true if the given locale is internally supported and has short-units support. * Support is considered enabled if either year, day or hour has a short variant translated. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasShortUnits(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return ($newLocale && (($y = static::translateWith($translator, 'y')) !== 'y' && $y !== static::translateWith($translator, 'year'))) || ( ($y = static::translateWith($translator, 'd')) !== 'd' && $y !== static::translateWith($translator, 'day') ) || ( ($y = static::translateWith($translator, 'h')) !== 'h' && $y !== static::translateWith($translator, 'hour') ); }); } /** * Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffSyntax(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { if (!$newLocale) { return false; } foreach (['ago', 'from_now', 'before', 'after'] as $key) { if ($translator instanceof TranslatorBagInterface && self::getFromCatalogue($translator, $translator->getCatalogue($newLocale), $key) instanceof Closure ) { continue; } if ($translator->trans($key) === $key) { return false; } } return true; }); } /** * Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow). * Support is considered enabled if the 3 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffOneDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_now') !== 'diff_now' && $translator->trans('diff_yesterday') !== 'diff_yesterday' && $translator->trans('diff_tomorrow') !== 'diff_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow). * Support is considered enabled if the 2 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffTwoDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_before_yesterday') !== 'diff_before_yesterday' && $translator->trans('diff_after_tomorrow') !== 'diff_after_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasPeriodSyntax($locale) { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('period_recurrences') !== 'period_recurrences' && $translator->trans('period_interval') !== 'period_interval' && $translator->trans('period_start_date') !== 'period_start_date' && $translator->trans('period_end_date') !== 'period_end_date'; }); } /** * Returns the list of internally available locales and already loaded custom locales. * (It will ignore custom translator dynamic loading.) * * @return array */ public static function getAvailableLocales() { $translator = static::getLocaleAwareTranslator(); return $translator instanceof Translator ? $translator->getAvailableLocales() : [$translator->getLocale()]; } /** * Returns list of Language object for each available locale. This object allow you to get the ISO name, native * name, region and variant of the locale. * * @return Language[] */ public static function getAvailableLocalesInfo() { $languages = []; foreach (static::getAvailableLocales() as $id) { $languages[$id] = new Language($id); } return $languages; } /** * Get the locale of a given translator. * * If null or omitted, current local translator is used. * If no local translator is in use, current global translator is used. */ protected function getTranslatorLocale($translator = null): ?string { if (\func_num_args() === 0) { $translator = $this->getLocalTranslator(); } $translator = static::getLocaleAwareTranslator($translator); return $translator?->getLocale(); } /** * Throw an error if passed object is not LocaleAwareInterface. * * @param LocaleAwareInterface|null $translator * * @return LocaleAwareInterface|null */ protected static function getLocaleAwareTranslator($translator = null) { if (\func_num_args() === 0) { $translator = static::getTranslator(); } if ($translator && !($translator instanceof LocaleAwareInterface || method_exists($translator, 'getLocale'))) { throw new NotLocaleAwareException($translator); // @codeCoverageIgnore } return $translator; } /** * @param mixed $translator * @param \Symfony\Component\Translation\MessageCatalogueInterface $catalogue * * @return mixed */ private static function getFromCatalogue($translator, $catalogue, string $id, string $domain = 'messages') { return $translator instanceof TranslatorStrongTypeInterface ? $translator->getFromCatalogue($catalogue, $id, $domain) : $catalogue->get($id, $domain); // @codeCoverageIgnore } /** * Return the word cleaned from its translation codes. * * @param string $word * * @return string */ private static function cleanWordFromTranslationString($word) { $word = str_replace([':count', '%count', ':time'], '', $word); $word = strtr($word, ['’' => "'"]); $word = preg_replace( '/\{(?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?}|[\[\]](?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?[\[\]]/', '', $word, ); return trim($word); } /** * Translate a list of words. * * @param string[] $keys keys to translate. * @param string[] $messages messages bag handling translations. * @param string $key 'to' (to get the translation) or 'from' (to get the detection RegExp pattern). * * @return string[] */ private static function translateWordsByKeys($keys, $messages, $key): array { return array_map(function ($wordKey) use ($messages, $key) { $message = $key === 'from' && isset($messages[$wordKey.'_regexp']) ? $messages[$wordKey.'_regexp'] : ($messages[$wordKey] ?? null); if (!$message) { return '>>DO NOT REPLACE<<'; } $parts = explode('|', $message); return $key === 'to' ? self::cleanWordFromTranslationString(end($parts)) : '(?:'.implode('|', array_map(static::cleanWordFromTranslationString(...), $parts)).')'; }, $keys); } /** * Get an array of translations based on the current date. * * @param callable $translation * @param int $length * @param string $timeString * * @return string[] */ private static function getTranslationArray($translation, $length, $timeString): array { $filler = '>>DO NOT REPLACE<<'; if (\is_array($translation)) { return array_pad($translation, $length, $filler); } $list = []; $date = static::now(); for ($i = 0; $i < $length; $i++) { $list[] = $translation($date, $timeString, $i) ?? $filler; } return $list; } private static function replaceOrdinalWords(string $timeString, array $ordinalWords): string { return preg_replace_callback('/(?<![a-z])[a-z]+(?![a-z])/i', function (array $match) use ($ordinalWords) { return $ordinalWords[mb_strtolower($match[0])] ?? $match[0]; }, $timeString); } }
PHP
{ "end_line": 462, "name": "executeWithLocale", "signature": "public static function executeWithLocale(string $locale, callable $func): mixed", "start_line": 448 }
{ "class_name": "Localization", "class_signature": "trait Localization", "namespace": "Carbon\\Traits" }
localeHasShortUnits
Carbon/src/Carbon/Traits/Localization.php
public static function localeHasShortUnits(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return ($newLocale && (($y = static::translateWith($translator, 'y')) !== 'y' && $y !== static::translateWith($translator, 'year'))) || ( ($y = static::translateWith($translator, 'd')) !== 'd' && $y !== static::translateWith($translator, 'day') ) || ( ($y = static::translateWith($translator, 'h')) !== 'h' && $y !== static::translateWith($translator, 'hour') ); }); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidTypeException; use Carbon\Exceptions\NotLocaleAwareException; use Carbon\Language; use Carbon\Translator; use Carbon\TranslatorStrongTypeInterface; use Closure; use Symfony\Component\Translation\TranslatorBagInterface; use Symfony\Contracts\Translation\LocaleAwareInterface; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Localization. * * Embed default and locale translators and translation base methods. */ trait Localization { use StaticLocalization; /** * Specific translator of the current instance. */ protected ?TranslatorInterface $localTranslator = null; /** * Return true if the current instance has its own translator. */ public function hasLocalTranslator(): bool { return isset($this->localTranslator); } /** * Get the translator of the current instance or the default if none set. */ public function getLocalTranslator(): TranslatorInterface { return $this->localTranslator ?? $this->transmitFactory(static fn () => static::getTranslator()); } /** * Set the translator for the current instance. */ public function setLocalTranslator(TranslatorInterface $translator): self { $this->localTranslator = $translator; return $this; } /** * Returns raw translation message for a given key. * * @param TranslatorInterface|null $translator the translator to use * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * * @return string|Closure|null */ public static function getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null) { if (!($translator instanceof TranslatorBagInterface && $translator instanceof TranslatorInterface)) { throw new InvalidTypeException( 'Translator does not implement '.TranslatorInterface::class.' and '.TranslatorBagInterface::class.'. '. (\is_object($translator) ? \get_class($translator) : \gettype($translator)).' has been given.', ); } if (!$locale && $translator instanceof LocaleAwareInterface) { $locale = $translator->getLocale(); } $result = self::getFromCatalogue($translator, $translator->getCatalogue($locale), $key); return $result === $key ? $default : $result; } /** * Returns raw translation message for a given key. * * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * @param TranslatorInterface $translator an optional translator to use * * @return string */ public function getTranslationMessage(string $key, ?string $locale = null, ?string $default = null, $translator = null) { return static::getTranslationMessageWith($translator ?? $this->getLocalTranslator(), $key, $locale, $default); } /** * Translate using translation string or callback available. * * @param TranslatorInterface $translator an optional translator to use * @param string $key key to find * @param array $parameters replacement parameters * @param int|float|null $number number if plural * * @return string */ public static function translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null): string { $message = static::getTranslationMessageWith($translator, $key, null, $key); if ($message instanceof Closure) { return (string) $message(...array_values($parameters)); } if ($number !== null) { $parameters['%count%'] = $number; } if (isset($parameters['%count%'])) { $parameters[':count'] = $parameters['%count%']; } return (string) $translator->trans($key, $parameters); } /** * Translate using translation string or callback available. * * @param string $key key to find * @param array $parameters replacement parameters * @param string|int|float|null $number number if plural * @param TranslatorInterface|null $translator an optional translator to use * @param bool $altNumbers pass true to use alternative numbers * * @return string */ public function translate( string $key, array $parameters = [], string|int|float|null $number = null, ?TranslatorInterface $translator = null, bool $altNumbers = false, ): string { $translation = static::translateWith($translator ?? $this->getLocalTranslator(), $key, $parameters, $number); if ($number !== null && $altNumbers) { return str_replace((string) $number, $this->translateNumber((int) $number), $translation); } return $translation; } /** * Returns the alternative number for a given integer if available in the current locale. * * @param int $number * * @return string */ public function translateNumber(int $number): string { $translateKey = "alt_numbers.$number"; $symbol = $this->translate($translateKey); if ($symbol !== $translateKey) { return $symbol; } if ($number > 99 && $this->translate('alt_numbers.99') !== 'alt_numbers.99') { $start = ''; foreach ([10000, 1000, 100] as $exp) { $key = "alt_numbers_pow.$exp"; if ($number >= $exp && $number < $exp * 10 && ($pow = $this->translate($key)) !== $key) { $unit = floor($number / $exp); $number -= $unit * $exp; $start .= ($unit > 1 ? $this->translate("alt_numbers.$unit") : '').$pow; } } $result = ''; while ($number) { $chunk = $number % 100; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 100); } return "$start$result"; } if ($number > 9 && $this->translate('alt_numbers.9') !== 'alt_numbers.9') { $result = ''; while ($number) { $chunk = $number % 10; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 10); } return $result; } return (string) $number; } /** * Translate a time string from a locale to an other. * * @param string $timeString date/time/duration string to translate (may also contain English) * @param string|null $from input locale of the $timeString parameter (`Carbon::getLocale()` by default) * @param string|null $to output locale of the result returned (`"en"` by default) * @param int $mode specify what to translate with options: * - CarbonInterface::TRANSLATE_ALL (default) * - CarbonInterface::TRANSLATE_MONTHS * - CarbonInterface::TRANSLATE_DAYS * - CarbonInterface::TRANSLATE_UNITS * - CarbonInterface::TRANSLATE_MERIDIEM * You can use pipe to group: CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS * * @return string */ public static function translateTimeString( string $timeString, ?string $from = null, ?string $to = null, int $mode = CarbonInterface::TRANSLATE_ALL, ): string { // Fallback source and destination locales $from = $from ?: static::getLocale(); $to = $to ?: CarbonInterface::DEFAULT_LOCALE; if ($from === $to) { return $timeString; } // Standardize apostrophe $timeString = strtr($timeString, ['’' => "'"]); $fromTranslations = []; $toTranslations = []; foreach (['from', 'to'] as $key) { $language = $$key; $translator = Translator::get($language); $translations = $translator->getMessages(); if (!isset($translations[$language])) { return $timeString; } $translationKey = $key.'Translations'; $messages = $translations[$language]; $months = $messages['months'] ?? []; $weekdays = $messages['weekdays'] ?? []; $meridiem = $messages['meridiem'] ?? ['AM', 'PM']; if (isset($messages['ordinal_words'])) { $timeString = self::replaceOrdinalWords( $timeString, $key === 'from' ? array_flip($messages['ordinal_words']) : $messages['ordinal_words'] ); } if ($key === 'from') { foreach (['months', 'weekdays'] as $variable) { $list = $messages[$variable.'_standalone'] ?? null; if ($list) { foreach ($$variable as $index => &$name) { $name .= '|'.$list[$index]; } } } } $$translationKey = array_merge( $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($months, static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($messages['months_short'] ?? [], static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($weekdays, static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($messages['weekdays_short'] ?? [], static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DIFF ? self::translateWordsByKeys([ 'diff_now', 'diff_today', 'diff_yesterday', 'diff_tomorrow', 'diff_before_yesterday', 'diff_after_tomorrow', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_UNITS ? self::translateWordsByKeys([ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_MERIDIEM ? array_map(function ($hour) use ($meridiem) { if (\is_array($meridiem)) { return $meridiem[$hour < static::HOURS_PER_DAY / 2 ? 0 : 1]; } return $meridiem($hour, 0, false); }, range(0, 23)) : [], ); } return substr(preg_replace_callback('/(?<=[\d\s+.\/,_-])('.implode('|', $fromTranslations).')(?=[\d\s+.\/,_-])/iu', function ($match) use ($fromTranslations, $toTranslations) { [$chunk] = $match; foreach ($fromTranslations as $index => $word) { if (preg_match("/^$word\$/iu", $chunk)) { return $toTranslations[$index] ?? ''; } } return $chunk; // @codeCoverageIgnore }, " $timeString "), 1, -1); } /** * Translate a time string from the current locale (`$date->locale()`) to another one. * * @param string $timeString time string to translate * @param string|null $to output locale of the result returned ("en" by default) * * @return string */ public function translateTimeStringTo(string $timeString, ?string $to = null): string { return static::translateTimeString($timeString, $this->getTranslatorLocale(), $to); } /** * Get/set the locale for the current instance. * * @param string|null $locale * @param string ...$fallbackLocales * * @return $this|string */ public function locale(?string $locale = null, string ...$fallbackLocales): static|string { if ($locale === null) { return $this->getTranslatorLocale(); } if (!$this->localTranslator || $this->getTranslatorLocale($this->localTranslator) !== $locale) { $translator = Translator::get($locale); if (!empty($fallbackLocales)) { $translator->setFallbackLocales($fallbackLocales); foreach ($fallbackLocales as $fallbackLocale) { $messages = Translator::get($fallbackLocale)->getMessages(); if (isset($messages[$fallbackLocale])) { $translator->setMessages($fallbackLocale, $messages[$fallbackLocale]); } } } $this->localTranslator = $translator; } return $this; } /** * Get the current translator locale. * * @return string */ public static function getLocale(): string { return static::getLocaleAwareTranslator()->getLocale(); } /** * Set the current translator locale and indicate if the source locale file exists. * Pass 'auto' as locale to use the closest language to the current LC_TIME locale. * * @param string $locale locale ex. en */ public static function setLocale(string $locale): void { static::getLocaleAwareTranslator()->setLocale($locale); } /** * Set the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales * * @param string $locale */ public static function setFallbackLocale(string $locale): void { $translator = static::getTranslator(); if (method_exists($translator, 'setFallbackLocales')) { $translator->setFallbackLocales([$locale]); if ($translator instanceof Translator) { $preferredLocale = $translator->getLocale(); $translator->setMessages($preferredLocale, array_replace_recursive( $translator->getMessages()[$locale] ?? [], Translator::get($locale)->getMessages()[$locale] ?? [], $translator->getMessages($preferredLocale), )); } } } /** * Get the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales */ public static function getFallbackLocale(): ?string { $translator = static::getTranslator(); if (method_exists($translator, 'getFallbackLocales')) { return $translator->getFallbackLocales()[0] ?? null; } return null; } /** * Set the current locale to the given, execute the passed function, reset the locale to previous one, * then return the result of the closure (or null if the closure was void). * * @param string $locale locale ex. en * @param callable $func * * @return mixed */ public static function executeWithLocale(string $locale, callable $func): mixed { $currentLocale = static::getLocale(); static::setLocale($locale); $newLocale = static::getLocale(); $result = $func( $newLocale === 'en' && strtolower(substr((string) $locale, 0, 2)) !== 'en' ? false : $newLocale, static::getTranslator(), ); static::setLocale($currentLocale); return $result; } /** * Returns true if the given locale is internally supported and has short-units support. * Support is considered enabled if either year, day or hour has a short variant translated. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasShortUnits(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return ($newLocale && (($y = static::translateWith($translator, 'y')) !== 'y' && $y !== static::translateWith($translator, 'year'))) || ( ($y = static::translateWith($translator, 'd')) !== 'd' && $y !== static::translateWith($translator, 'day') ) || ( ($y = static::translateWith($translator, 'h')) !== 'h' && $y !== static::translateWith($translator, 'hour') ); }); } /** * Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffSyntax(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { if (!$newLocale) { return false; } foreach (['ago', 'from_now', 'before', 'after'] as $key) { if ($translator instanceof TranslatorBagInterface && self::getFromCatalogue($translator, $translator->getCatalogue($newLocale), $key) instanceof Closure ) { continue; } if ($translator->trans($key) === $key) { return false; } } return true; }); } /** * Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow). * Support is considered enabled if the 3 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffOneDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_now') !== 'diff_now' && $translator->trans('diff_yesterday') !== 'diff_yesterday' && $translator->trans('diff_tomorrow') !== 'diff_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow). * Support is considered enabled if the 2 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffTwoDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_before_yesterday') !== 'diff_before_yesterday' && $translator->trans('diff_after_tomorrow') !== 'diff_after_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasPeriodSyntax($locale) { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('period_recurrences') !== 'period_recurrences' && $translator->trans('period_interval') !== 'period_interval' && $translator->trans('period_start_date') !== 'period_start_date' && $translator->trans('period_end_date') !== 'period_end_date'; }); } /** * Returns the list of internally available locales and already loaded custom locales. * (It will ignore custom translator dynamic loading.) * * @return array */ public static function getAvailableLocales() { $translator = static::getLocaleAwareTranslator(); return $translator instanceof Translator ? $translator->getAvailableLocales() : [$translator->getLocale()]; } /** * Returns list of Language object for each available locale. This object allow you to get the ISO name, native * name, region and variant of the locale. * * @return Language[] */ public static function getAvailableLocalesInfo() { $languages = []; foreach (static::getAvailableLocales() as $id) { $languages[$id] = new Language($id); } return $languages; } /** * Get the locale of a given translator. * * If null or omitted, current local translator is used. * If no local translator is in use, current global translator is used. */ protected function getTranslatorLocale($translator = null): ?string { if (\func_num_args() === 0) { $translator = $this->getLocalTranslator(); } $translator = static::getLocaleAwareTranslator($translator); return $translator?->getLocale(); } /** * Throw an error if passed object is not LocaleAwareInterface. * * @param LocaleAwareInterface|null $translator * * @return LocaleAwareInterface|null */ protected static function getLocaleAwareTranslator($translator = null) { if (\func_num_args() === 0) { $translator = static::getTranslator(); } if ($translator && !($translator instanceof LocaleAwareInterface || method_exists($translator, 'getLocale'))) { throw new NotLocaleAwareException($translator); // @codeCoverageIgnore } return $translator; } /** * @param mixed $translator * @param \Symfony\Component\Translation\MessageCatalogueInterface $catalogue * * @return mixed */ private static function getFromCatalogue($translator, $catalogue, string $id, string $domain = 'messages') { return $translator instanceof TranslatorStrongTypeInterface ? $translator->getFromCatalogue($catalogue, $id, $domain) : $catalogue->get($id, $domain); // @codeCoverageIgnore } /** * Return the word cleaned from its translation codes. * * @param string $word * * @return string */ private static function cleanWordFromTranslationString($word) { $word = str_replace([':count', '%count', ':time'], '', $word); $word = strtr($word, ['’' => "'"]); $word = preg_replace( '/\{(?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?}|[\[\]](?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?[\[\]]/', '', $word, ); return trim($word); } /** * Translate a list of words. * * @param string[] $keys keys to translate. * @param string[] $messages messages bag handling translations. * @param string $key 'to' (to get the translation) or 'from' (to get the detection RegExp pattern). * * @return string[] */ private static function translateWordsByKeys($keys, $messages, $key): array { return array_map(function ($wordKey) use ($messages, $key) { $message = $key === 'from' && isset($messages[$wordKey.'_regexp']) ? $messages[$wordKey.'_regexp'] : ($messages[$wordKey] ?? null); if (!$message) { return '>>DO NOT REPLACE<<'; } $parts = explode('|', $message); return $key === 'to' ? self::cleanWordFromTranslationString(end($parts)) : '(?:'.implode('|', array_map(static::cleanWordFromTranslationString(...), $parts)).')'; }, $keys); } /** * Get an array of translations based on the current date. * * @param callable $translation * @param int $length * @param string $timeString * * @return string[] */ private static function getTranslationArray($translation, $length, $timeString): array { $filler = '>>DO NOT REPLACE<<'; if (\is_array($translation)) { return array_pad($translation, $length, $filler); } $list = []; $date = static::now(); for ($i = 0; $i < $length; $i++) { $list[] = $translation($date, $timeString, $i) ?? $filler; } return $list; } private static function replaceOrdinalWords(string $timeString, array $ordinalWords): string { return preg_replace_callback('/(?<![a-z])[a-z]+(?![a-z])/i', function (array $match) use ($ordinalWords) { return $ordinalWords[mb_strtolower($match[0])] ?? $match[0]; }, $timeString); } }
PHP
{ "end_line": 483, "name": "localeHasShortUnits", "signature": "public static function localeHasShortUnits(string $locale): bool", "start_line": 472 }
{ "class_name": "Localization", "class_signature": "trait Localization", "namespace": "Carbon\\Traits" }
localeHasDiffSyntax
Carbon/src/Carbon/Traits/Localization.php
public static function localeHasDiffSyntax(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { if (!$newLocale) { return false; } foreach (['ago', 'from_now', 'before', 'after'] as $key) { if ($translator instanceof TranslatorBagInterface && self::getFromCatalogue($translator, $translator->getCatalogue($newLocale), $key) instanceof Closure ) { continue; } if ($translator->trans($key) === $key) { return false; } } return true; }); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidTypeException; use Carbon\Exceptions\NotLocaleAwareException; use Carbon\Language; use Carbon\Translator; use Carbon\TranslatorStrongTypeInterface; use Closure; use Symfony\Component\Translation\TranslatorBagInterface; use Symfony\Contracts\Translation\LocaleAwareInterface; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Localization. * * Embed default and locale translators and translation base methods. */ trait Localization { use StaticLocalization; /** * Specific translator of the current instance. */ protected ?TranslatorInterface $localTranslator = null; /** * Return true if the current instance has its own translator. */ public function hasLocalTranslator(): bool { return isset($this->localTranslator); } /** * Get the translator of the current instance or the default if none set. */ public function getLocalTranslator(): TranslatorInterface { return $this->localTranslator ?? $this->transmitFactory(static fn () => static::getTranslator()); } /** * Set the translator for the current instance. */ public function setLocalTranslator(TranslatorInterface $translator): self { $this->localTranslator = $translator; return $this; } /** * Returns raw translation message for a given key. * * @param TranslatorInterface|null $translator the translator to use * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * * @return string|Closure|null */ public static function getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null) { if (!($translator instanceof TranslatorBagInterface && $translator instanceof TranslatorInterface)) { throw new InvalidTypeException( 'Translator does not implement '.TranslatorInterface::class.' and '.TranslatorBagInterface::class.'. '. (\is_object($translator) ? \get_class($translator) : \gettype($translator)).' has been given.', ); } if (!$locale && $translator instanceof LocaleAwareInterface) { $locale = $translator->getLocale(); } $result = self::getFromCatalogue($translator, $translator->getCatalogue($locale), $key); return $result === $key ? $default : $result; } /** * Returns raw translation message for a given key. * * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * @param TranslatorInterface $translator an optional translator to use * * @return string */ public function getTranslationMessage(string $key, ?string $locale = null, ?string $default = null, $translator = null) { return static::getTranslationMessageWith($translator ?? $this->getLocalTranslator(), $key, $locale, $default); } /** * Translate using translation string or callback available. * * @param TranslatorInterface $translator an optional translator to use * @param string $key key to find * @param array $parameters replacement parameters * @param int|float|null $number number if plural * * @return string */ public static function translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null): string { $message = static::getTranslationMessageWith($translator, $key, null, $key); if ($message instanceof Closure) { return (string) $message(...array_values($parameters)); } if ($number !== null) { $parameters['%count%'] = $number; } if (isset($parameters['%count%'])) { $parameters[':count'] = $parameters['%count%']; } return (string) $translator->trans($key, $parameters); } /** * Translate using translation string or callback available. * * @param string $key key to find * @param array $parameters replacement parameters * @param string|int|float|null $number number if plural * @param TranslatorInterface|null $translator an optional translator to use * @param bool $altNumbers pass true to use alternative numbers * * @return string */ public function translate( string $key, array $parameters = [], string|int|float|null $number = null, ?TranslatorInterface $translator = null, bool $altNumbers = false, ): string { $translation = static::translateWith($translator ?? $this->getLocalTranslator(), $key, $parameters, $number); if ($number !== null && $altNumbers) { return str_replace((string) $number, $this->translateNumber((int) $number), $translation); } return $translation; } /** * Returns the alternative number for a given integer if available in the current locale. * * @param int $number * * @return string */ public function translateNumber(int $number): string { $translateKey = "alt_numbers.$number"; $symbol = $this->translate($translateKey); if ($symbol !== $translateKey) { return $symbol; } if ($number > 99 && $this->translate('alt_numbers.99') !== 'alt_numbers.99') { $start = ''; foreach ([10000, 1000, 100] as $exp) { $key = "alt_numbers_pow.$exp"; if ($number >= $exp && $number < $exp * 10 && ($pow = $this->translate($key)) !== $key) { $unit = floor($number / $exp); $number -= $unit * $exp; $start .= ($unit > 1 ? $this->translate("alt_numbers.$unit") : '').$pow; } } $result = ''; while ($number) { $chunk = $number % 100; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 100); } return "$start$result"; } if ($number > 9 && $this->translate('alt_numbers.9') !== 'alt_numbers.9') { $result = ''; while ($number) { $chunk = $number % 10; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 10); } return $result; } return (string) $number; } /** * Translate a time string from a locale to an other. * * @param string $timeString date/time/duration string to translate (may also contain English) * @param string|null $from input locale of the $timeString parameter (`Carbon::getLocale()` by default) * @param string|null $to output locale of the result returned (`"en"` by default) * @param int $mode specify what to translate with options: * - CarbonInterface::TRANSLATE_ALL (default) * - CarbonInterface::TRANSLATE_MONTHS * - CarbonInterface::TRANSLATE_DAYS * - CarbonInterface::TRANSLATE_UNITS * - CarbonInterface::TRANSLATE_MERIDIEM * You can use pipe to group: CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS * * @return string */ public static function translateTimeString( string $timeString, ?string $from = null, ?string $to = null, int $mode = CarbonInterface::TRANSLATE_ALL, ): string { // Fallback source and destination locales $from = $from ?: static::getLocale(); $to = $to ?: CarbonInterface::DEFAULT_LOCALE; if ($from === $to) { return $timeString; } // Standardize apostrophe $timeString = strtr($timeString, ['’' => "'"]); $fromTranslations = []; $toTranslations = []; foreach (['from', 'to'] as $key) { $language = $$key; $translator = Translator::get($language); $translations = $translator->getMessages(); if (!isset($translations[$language])) { return $timeString; } $translationKey = $key.'Translations'; $messages = $translations[$language]; $months = $messages['months'] ?? []; $weekdays = $messages['weekdays'] ?? []; $meridiem = $messages['meridiem'] ?? ['AM', 'PM']; if (isset($messages['ordinal_words'])) { $timeString = self::replaceOrdinalWords( $timeString, $key === 'from' ? array_flip($messages['ordinal_words']) : $messages['ordinal_words'] ); } if ($key === 'from') { foreach (['months', 'weekdays'] as $variable) { $list = $messages[$variable.'_standalone'] ?? null; if ($list) { foreach ($$variable as $index => &$name) { $name .= '|'.$list[$index]; } } } } $$translationKey = array_merge( $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($months, static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($messages['months_short'] ?? [], static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($weekdays, static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($messages['weekdays_short'] ?? [], static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DIFF ? self::translateWordsByKeys([ 'diff_now', 'diff_today', 'diff_yesterday', 'diff_tomorrow', 'diff_before_yesterday', 'diff_after_tomorrow', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_UNITS ? self::translateWordsByKeys([ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_MERIDIEM ? array_map(function ($hour) use ($meridiem) { if (\is_array($meridiem)) { return $meridiem[$hour < static::HOURS_PER_DAY / 2 ? 0 : 1]; } return $meridiem($hour, 0, false); }, range(0, 23)) : [], ); } return substr(preg_replace_callback('/(?<=[\d\s+.\/,_-])('.implode('|', $fromTranslations).')(?=[\d\s+.\/,_-])/iu', function ($match) use ($fromTranslations, $toTranslations) { [$chunk] = $match; foreach ($fromTranslations as $index => $word) { if (preg_match("/^$word\$/iu", $chunk)) { return $toTranslations[$index] ?? ''; } } return $chunk; // @codeCoverageIgnore }, " $timeString "), 1, -1); } /** * Translate a time string from the current locale (`$date->locale()`) to another one. * * @param string $timeString time string to translate * @param string|null $to output locale of the result returned ("en" by default) * * @return string */ public function translateTimeStringTo(string $timeString, ?string $to = null): string { return static::translateTimeString($timeString, $this->getTranslatorLocale(), $to); } /** * Get/set the locale for the current instance. * * @param string|null $locale * @param string ...$fallbackLocales * * @return $this|string */ public function locale(?string $locale = null, string ...$fallbackLocales): static|string { if ($locale === null) { return $this->getTranslatorLocale(); } if (!$this->localTranslator || $this->getTranslatorLocale($this->localTranslator) !== $locale) { $translator = Translator::get($locale); if (!empty($fallbackLocales)) { $translator->setFallbackLocales($fallbackLocales); foreach ($fallbackLocales as $fallbackLocale) { $messages = Translator::get($fallbackLocale)->getMessages(); if (isset($messages[$fallbackLocale])) { $translator->setMessages($fallbackLocale, $messages[$fallbackLocale]); } } } $this->localTranslator = $translator; } return $this; } /** * Get the current translator locale. * * @return string */ public static function getLocale(): string { return static::getLocaleAwareTranslator()->getLocale(); } /** * Set the current translator locale and indicate if the source locale file exists. * Pass 'auto' as locale to use the closest language to the current LC_TIME locale. * * @param string $locale locale ex. en */ public static function setLocale(string $locale): void { static::getLocaleAwareTranslator()->setLocale($locale); } /** * Set the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales * * @param string $locale */ public static function setFallbackLocale(string $locale): void { $translator = static::getTranslator(); if (method_exists($translator, 'setFallbackLocales')) { $translator->setFallbackLocales([$locale]); if ($translator instanceof Translator) { $preferredLocale = $translator->getLocale(); $translator->setMessages($preferredLocale, array_replace_recursive( $translator->getMessages()[$locale] ?? [], Translator::get($locale)->getMessages()[$locale] ?? [], $translator->getMessages($preferredLocale), )); } } } /** * Get the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales */ public static function getFallbackLocale(): ?string { $translator = static::getTranslator(); if (method_exists($translator, 'getFallbackLocales')) { return $translator->getFallbackLocales()[0] ?? null; } return null; } /** * Set the current locale to the given, execute the passed function, reset the locale to previous one, * then return the result of the closure (or null if the closure was void). * * @param string $locale locale ex. en * @param callable $func * * @return mixed */ public static function executeWithLocale(string $locale, callable $func): mixed { $currentLocale = static::getLocale(); static::setLocale($locale); $newLocale = static::getLocale(); $result = $func( $newLocale === 'en' && strtolower(substr((string) $locale, 0, 2)) !== 'en' ? false : $newLocale, static::getTranslator(), ); static::setLocale($currentLocale); return $result; } /** * Returns true if the given locale is internally supported and has short-units support. * Support is considered enabled if either year, day or hour has a short variant translated. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasShortUnits(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return ($newLocale && (($y = static::translateWith($translator, 'y')) !== 'y' && $y !== static::translateWith($translator, 'year'))) || ( ($y = static::translateWith($translator, 'd')) !== 'd' && $y !== static::translateWith($translator, 'day') ) || ( ($y = static::translateWith($translator, 'h')) !== 'h' && $y !== static::translateWith($translator, 'hour') ); }); } /** * Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffSyntax(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { if (!$newLocale) { return false; } foreach (['ago', 'from_now', 'before', 'after'] as $key) { if ($translator instanceof TranslatorBagInterface && self::getFromCatalogue($translator, $translator->getCatalogue($newLocale), $key) instanceof Closure ) { continue; } if ($translator->trans($key) === $key) { return false; } } return true; }); } /** * Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow). * Support is considered enabled if the 3 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffOneDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_now') !== 'diff_now' && $translator->trans('diff_yesterday') !== 'diff_yesterday' && $translator->trans('diff_tomorrow') !== 'diff_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow). * Support is considered enabled if the 2 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffTwoDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_before_yesterday') !== 'diff_before_yesterday' && $translator->trans('diff_after_tomorrow') !== 'diff_after_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasPeriodSyntax($locale) { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('period_recurrences') !== 'period_recurrences' && $translator->trans('period_interval') !== 'period_interval' && $translator->trans('period_start_date') !== 'period_start_date' && $translator->trans('period_end_date') !== 'period_end_date'; }); } /** * Returns the list of internally available locales and already loaded custom locales. * (It will ignore custom translator dynamic loading.) * * @return array */ public static function getAvailableLocales() { $translator = static::getLocaleAwareTranslator(); return $translator instanceof Translator ? $translator->getAvailableLocales() : [$translator->getLocale()]; } /** * Returns list of Language object for each available locale. This object allow you to get the ISO name, native * name, region and variant of the locale. * * @return Language[] */ public static function getAvailableLocalesInfo() { $languages = []; foreach (static::getAvailableLocales() as $id) { $languages[$id] = new Language($id); } return $languages; } /** * Get the locale of a given translator. * * If null or omitted, current local translator is used. * If no local translator is in use, current global translator is used. */ protected function getTranslatorLocale($translator = null): ?string { if (\func_num_args() === 0) { $translator = $this->getLocalTranslator(); } $translator = static::getLocaleAwareTranslator($translator); return $translator?->getLocale(); } /** * Throw an error if passed object is not LocaleAwareInterface. * * @param LocaleAwareInterface|null $translator * * @return LocaleAwareInterface|null */ protected static function getLocaleAwareTranslator($translator = null) { if (\func_num_args() === 0) { $translator = static::getTranslator(); } if ($translator && !($translator instanceof LocaleAwareInterface || method_exists($translator, 'getLocale'))) { throw new NotLocaleAwareException($translator); // @codeCoverageIgnore } return $translator; } /** * @param mixed $translator * @param \Symfony\Component\Translation\MessageCatalogueInterface $catalogue * * @return mixed */ private static function getFromCatalogue($translator, $catalogue, string $id, string $domain = 'messages') { return $translator instanceof TranslatorStrongTypeInterface ? $translator->getFromCatalogue($catalogue, $id, $domain) : $catalogue->get($id, $domain); // @codeCoverageIgnore } /** * Return the word cleaned from its translation codes. * * @param string $word * * @return string */ private static function cleanWordFromTranslationString($word) { $word = str_replace([':count', '%count', ':time'], '', $word); $word = strtr($word, ['’' => "'"]); $word = preg_replace( '/\{(?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?}|[\[\]](?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?[\[\]]/', '', $word, ); return trim($word); } /** * Translate a list of words. * * @param string[] $keys keys to translate. * @param string[] $messages messages bag handling translations. * @param string $key 'to' (to get the translation) or 'from' (to get the detection RegExp pattern). * * @return string[] */ private static function translateWordsByKeys($keys, $messages, $key): array { return array_map(function ($wordKey) use ($messages, $key) { $message = $key === 'from' && isset($messages[$wordKey.'_regexp']) ? $messages[$wordKey.'_regexp'] : ($messages[$wordKey] ?? null); if (!$message) { return '>>DO NOT REPLACE<<'; } $parts = explode('|', $message); return $key === 'to' ? self::cleanWordFromTranslationString(end($parts)) : '(?:'.implode('|', array_map(static::cleanWordFromTranslationString(...), $parts)).')'; }, $keys); } /** * Get an array of translations based on the current date. * * @param callable $translation * @param int $length * @param string $timeString * * @return string[] */ private static function getTranslationArray($translation, $length, $timeString): array { $filler = '>>DO NOT REPLACE<<'; if (\is_array($translation)) { return array_pad($translation, $length, $filler); } $list = []; $date = static::now(); for ($i = 0; $i < $length; $i++) { $list[] = $translation($date, $timeString, $i) ?? $filler; } return $list; } private static function replaceOrdinalWords(string $timeString, array $ordinalWords): string { return preg_replace_callback('/(?<![a-z])[a-z]+(?![a-z])/i', function (array $match) use ($ordinalWords) { return $ordinalWords[mb_strtolower($match[0])] ?? $match[0]; }, $timeString); } }
PHP
{ "end_line": 514, "name": "localeHasDiffSyntax", "signature": "public static function localeHasDiffSyntax(string $locale): bool", "start_line": 493 }
{ "class_name": "Localization", "class_signature": "trait Localization", "namespace": "Carbon\\Traits" }
localeHasPeriodSyntax
Carbon/src/Carbon/Traits/Localization.php
public static function localeHasPeriodSyntax($locale) { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('period_recurrences') !== 'period_recurrences' && $translator->trans('period_interval') !== 'period_interval' && $translator->trans('period_start_date') !== 'period_start_date' && $translator->trans('period_end_date') !== 'period_end_date'; }); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidTypeException; use Carbon\Exceptions\NotLocaleAwareException; use Carbon\Language; use Carbon\Translator; use Carbon\TranslatorStrongTypeInterface; use Closure; use Symfony\Component\Translation\TranslatorBagInterface; use Symfony\Contracts\Translation\LocaleAwareInterface; use Symfony\Contracts\Translation\TranslatorInterface; /** * Trait Localization. * * Embed default and locale translators and translation base methods. */ trait Localization { use StaticLocalization; /** * Specific translator of the current instance. */ protected ?TranslatorInterface $localTranslator = null; /** * Return true if the current instance has its own translator. */ public function hasLocalTranslator(): bool { return isset($this->localTranslator); } /** * Get the translator of the current instance or the default if none set. */ public function getLocalTranslator(): TranslatorInterface { return $this->localTranslator ?? $this->transmitFactory(static fn () => static::getTranslator()); } /** * Set the translator for the current instance. */ public function setLocalTranslator(TranslatorInterface $translator): self { $this->localTranslator = $translator; return $this; } /** * Returns raw translation message for a given key. * * @param TranslatorInterface|null $translator the translator to use * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * * @return string|Closure|null */ public static function getTranslationMessageWith($translator, string $key, ?string $locale = null, ?string $default = null) { if (!($translator instanceof TranslatorBagInterface && $translator instanceof TranslatorInterface)) { throw new InvalidTypeException( 'Translator does not implement '.TranslatorInterface::class.' and '.TranslatorBagInterface::class.'. '. (\is_object($translator) ? \get_class($translator) : \gettype($translator)).' has been given.', ); } if (!$locale && $translator instanceof LocaleAwareInterface) { $locale = $translator->getLocale(); } $result = self::getFromCatalogue($translator, $translator->getCatalogue($locale), $key); return $result === $key ? $default : $result; } /** * Returns raw translation message for a given key. * * @param string $key key to find * @param string|null $locale current locale used if null * @param string|null $default default value if translation returns the key * @param TranslatorInterface $translator an optional translator to use * * @return string */ public function getTranslationMessage(string $key, ?string $locale = null, ?string $default = null, $translator = null) { return static::getTranslationMessageWith($translator ?? $this->getLocalTranslator(), $key, $locale, $default); } /** * Translate using translation string or callback available. * * @param TranslatorInterface $translator an optional translator to use * @param string $key key to find * @param array $parameters replacement parameters * @param int|float|null $number number if plural * * @return string */ public static function translateWith(TranslatorInterface $translator, string $key, array $parameters = [], $number = null): string { $message = static::getTranslationMessageWith($translator, $key, null, $key); if ($message instanceof Closure) { return (string) $message(...array_values($parameters)); } if ($number !== null) { $parameters['%count%'] = $number; } if (isset($parameters['%count%'])) { $parameters[':count'] = $parameters['%count%']; } return (string) $translator->trans($key, $parameters); } /** * Translate using translation string or callback available. * * @param string $key key to find * @param array $parameters replacement parameters * @param string|int|float|null $number number if plural * @param TranslatorInterface|null $translator an optional translator to use * @param bool $altNumbers pass true to use alternative numbers * * @return string */ public function translate( string $key, array $parameters = [], string|int|float|null $number = null, ?TranslatorInterface $translator = null, bool $altNumbers = false, ): string { $translation = static::translateWith($translator ?? $this->getLocalTranslator(), $key, $parameters, $number); if ($number !== null && $altNumbers) { return str_replace((string) $number, $this->translateNumber((int) $number), $translation); } return $translation; } /** * Returns the alternative number for a given integer if available in the current locale. * * @param int $number * * @return string */ public function translateNumber(int $number): string { $translateKey = "alt_numbers.$number"; $symbol = $this->translate($translateKey); if ($symbol !== $translateKey) { return $symbol; } if ($number > 99 && $this->translate('alt_numbers.99') !== 'alt_numbers.99') { $start = ''; foreach ([10000, 1000, 100] as $exp) { $key = "alt_numbers_pow.$exp"; if ($number >= $exp && $number < $exp * 10 && ($pow = $this->translate($key)) !== $key) { $unit = floor($number / $exp); $number -= $unit * $exp; $start .= ($unit > 1 ? $this->translate("alt_numbers.$unit") : '').$pow; } } $result = ''; while ($number) { $chunk = $number % 100; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 100); } return "$start$result"; } if ($number > 9 && $this->translate('alt_numbers.9') !== 'alt_numbers.9') { $result = ''; while ($number) { $chunk = $number % 10; $result = $this->translate("alt_numbers.$chunk").$result; $number = floor($number / 10); } return $result; } return (string) $number; } /** * Translate a time string from a locale to an other. * * @param string $timeString date/time/duration string to translate (may also contain English) * @param string|null $from input locale of the $timeString parameter (`Carbon::getLocale()` by default) * @param string|null $to output locale of the result returned (`"en"` by default) * @param int $mode specify what to translate with options: * - CarbonInterface::TRANSLATE_ALL (default) * - CarbonInterface::TRANSLATE_MONTHS * - CarbonInterface::TRANSLATE_DAYS * - CarbonInterface::TRANSLATE_UNITS * - CarbonInterface::TRANSLATE_MERIDIEM * You can use pipe to group: CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS * * @return string */ public static function translateTimeString( string $timeString, ?string $from = null, ?string $to = null, int $mode = CarbonInterface::TRANSLATE_ALL, ): string { // Fallback source and destination locales $from = $from ?: static::getLocale(); $to = $to ?: CarbonInterface::DEFAULT_LOCALE; if ($from === $to) { return $timeString; } // Standardize apostrophe $timeString = strtr($timeString, ['’' => "'"]); $fromTranslations = []; $toTranslations = []; foreach (['from', 'to'] as $key) { $language = $$key; $translator = Translator::get($language); $translations = $translator->getMessages(); if (!isset($translations[$language])) { return $timeString; } $translationKey = $key.'Translations'; $messages = $translations[$language]; $months = $messages['months'] ?? []; $weekdays = $messages['weekdays'] ?? []; $meridiem = $messages['meridiem'] ?? ['AM', 'PM']; if (isset($messages['ordinal_words'])) { $timeString = self::replaceOrdinalWords( $timeString, $key === 'from' ? array_flip($messages['ordinal_words']) : $messages['ordinal_words'] ); } if ($key === 'from') { foreach (['months', 'weekdays'] as $variable) { $list = $messages[$variable.'_standalone'] ?? null; if ($list) { foreach ($$variable as $index => &$name) { $name .= '|'.$list[$index]; } } } } $$translationKey = array_merge( $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($months, static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_MONTHS ? self::getTranslationArray($messages['months_short'] ?? [], static::MONTHS_PER_YEAR, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($weekdays, static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DAYS ? self::getTranslationArray($messages['weekdays_short'] ?? [], static::DAYS_PER_WEEK, $timeString) : [], $mode & CarbonInterface::TRANSLATE_DIFF ? self::translateWordsByKeys([ 'diff_now', 'diff_today', 'diff_yesterday', 'diff_tomorrow', 'diff_before_yesterday', 'diff_after_tomorrow', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_UNITS ? self::translateWordsByKeys([ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', ], $messages, $key) : [], $mode & CarbonInterface::TRANSLATE_MERIDIEM ? array_map(function ($hour) use ($meridiem) { if (\is_array($meridiem)) { return $meridiem[$hour < static::HOURS_PER_DAY / 2 ? 0 : 1]; } return $meridiem($hour, 0, false); }, range(0, 23)) : [], ); } return substr(preg_replace_callback('/(?<=[\d\s+.\/,_-])('.implode('|', $fromTranslations).')(?=[\d\s+.\/,_-])/iu', function ($match) use ($fromTranslations, $toTranslations) { [$chunk] = $match; foreach ($fromTranslations as $index => $word) { if (preg_match("/^$word\$/iu", $chunk)) { return $toTranslations[$index] ?? ''; } } return $chunk; // @codeCoverageIgnore }, " $timeString "), 1, -1); } /** * Translate a time string from the current locale (`$date->locale()`) to another one. * * @param string $timeString time string to translate * @param string|null $to output locale of the result returned ("en" by default) * * @return string */ public function translateTimeStringTo(string $timeString, ?string $to = null): string { return static::translateTimeString($timeString, $this->getTranslatorLocale(), $to); } /** * Get/set the locale for the current instance. * * @param string|null $locale * @param string ...$fallbackLocales * * @return $this|string */ public function locale(?string $locale = null, string ...$fallbackLocales): static|string { if ($locale === null) { return $this->getTranslatorLocale(); } if (!$this->localTranslator || $this->getTranslatorLocale($this->localTranslator) !== $locale) { $translator = Translator::get($locale); if (!empty($fallbackLocales)) { $translator->setFallbackLocales($fallbackLocales); foreach ($fallbackLocales as $fallbackLocale) { $messages = Translator::get($fallbackLocale)->getMessages(); if (isset($messages[$fallbackLocale])) { $translator->setMessages($fallbackLocale, $messages[$fallbackLocale]); } } } $this->localTranslator = $translator; } return $this; } /** * Get the current translator locale. * * @return string */ public static function getLocale(): string { return static::getLocaleAwareTranslator()->getLocale(); } /** * Set the current translator locale and indicate if the source locale file exists. * Pass 'auto' as locale to use the closest language to the current LC_TIME locale. * * @param string $locale locale ex. en */ public static function setLocale(string $locale): void { static::getLocaleAwareTranslator()->setLocale($locale); } /** * Set the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales * * @param string $locale */ public static function setFallbackLocale(string $locale): void { $translator = static::getTranslator(); if (method_exists($translator, 'setFallbackLocales')) { $translator->setFallbackLocales([$locale]); if ($translator instanceof Translator) { $preferredLocale = $translator->getLocale(); $translator->setMessages($preferredLocale, array_replace_recursive( $translator->getMessages()[$locale] ?? [], Translator::get($locale)->getMessages()[$locale] ?? [], $translator->getMessages($preferredLocale), )); } } } /** * Get the fallback locale. * * @see https://symfony.com/doc/current/components/translation.html#fallback-locales */ public static function getFallbackLocale(): ?string { $translator = static::getTranslator(); if (method_exists($translator, 'getFallbackLocales')) { return $translator->getFallbackLocales()[0] ?? null; } return null; } /** * Set the current locale to the given, execute the passed function, reset the locale to previous one, * then return the result of the closure (or null if the closure was void). * * @param string $locale locale ex. en * @param callable $func * * @return mixed */ public static function executeWithLocale(string $locale, callable $func): mixed { $currentLocale = static::getLocale(); static::setLocale($locale); $newLocale = static::getLocale(); $result = $func( $newLocale === 'en' && strtolower(substr((string) $locale, 0, 2)) !== 'en' ? false : $newLocale, static::getTranslator(), ); static::setLocale($currentLocale); return $result; } /** * Returns true if the given locale is internally supported and has short-units support. * Support is considered enabled if either year, day or hour has a short variant translated. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasShortUnits(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return ($newLocale && (($y = static::translateWith($translator, 'y')) !== 'y' && $y !== static::translateWith($translator, 'year'))) || ( ($y = static::translateWith($translator, 'd')) !== 'd' && $y !== static::translateWith($translator, 'day') ) || ( ($y = static::translateWith($translator, 'h')) !== 'h' && $y !== static::translateWith($translator, 'hour') ); }); } /** * Returns true if the given locale is internally supported and has diff syntax support (ago, from now, before, after). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffSyntax(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { if (!$newLocale) { return false; } foreach (['ago', 'from_now', 'before', 'after'] as $key) { if ($translator instanceof TranslatorBagInterface && self::getFromCatalogue($translator, $translator->getCatalogue($newLocale), $key) instanceof Closure ) { continue; } if ($translator->trans($key) === $key) { return false; } } return true; }); } /** * Returns true if the given locale is internally supported and has words for 1-day diff (just now, yesterday, tomorrow). * Support is considered enabled if the 3 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffOneDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_now') !== 'diff_now' && $translator->trans('diff_yesterday') !== 'diff_yesterday' && $translator->trans('diff_tomorrow') !== 'diff_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has words for 2-days diff (before yesterday, after tomorrow). * Support is considered enabled if the 2 words are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasDiffTwoDayWords(string $locale): bool { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('diff_before_yesterday') !== 'diff_before_yesterday' && $translator->trans('diff_after_tomorrow') !== 'diff_after_tomorrow'; }); } /** * Returns true if the given locale is internally supported and has period syntax support (X times, every X, from X, to X). * Support is considered enabled if the 4 sentences are translated in the given locale. * * @param string $locale locale ex. en * * @return bool */ public static function localeHasPeriodSyntax($locale) { return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) { return $newLocale && $translator->trans('period_recurrences') !== 'period_recurrences' && $translator->trans('period_interval') !== 'period_interval' && $translator->trans('period_start_date') !== 'period_start_date' && $translator->trans('period_end_date') !== 'period_end_date'; }); } /** * Returns the list of internally available locales and already loaded custom locales. * (It will ignore custom translator dynamic loading.) * * @return array */ public static function getAvailableLocales() { $translator = static::getLocaleAwareTranslator(); return $translator instanceof Translator ? $translator->getAvailableLocales() : [$translator->getLocale()]; } /** * Returns list of Language object for each available locale. This object allow you to get the ISO name, native * name, region and variant of the locale. * * @return Language[] */ public static function getAvailableLocalesInfo() { $languages = []; foreach (static::getAvailableLocales() as $id) { $languages[$id] = new Language($id); } return $languages; } /** * Get the locale of a given translator. * * If null or omitted, current local translator is used. * If no local translator is in use, current global translator is used. */ protected function getTranslatorLocale($translator = null): ?string { if (\func_num_args() === 0) { $translator = $this->getLocalTranslator(); } $translator = static::getLocaleAwareTranslator($translator); return $translator?->getLocale(); } /** * Throw an error if passed object is not LocaleAwareInterface. * * @param LocaleAwareInterface|null $translator * * @return LocaleAwareInterface|null */ protected static function getLocaleAwareTranslator($translator = null) { if (\func_num_args() === 0) { $translator = static::getTranslator(); } if ($translator && !($translator instanceof LocaleAwareInterface || method_exists($translator, 'getLocale'))) { throw new NotLocaleAwareException($translator); // @codeCoverageIgnore } return $translator; } /** * @param mixed $translator * @param \Symfony\Component\Translation\MessageCatalogueInterface $catalogue * * @return mixed */ private static function getFromCatalogue($translator, $catalogue, string $id, string $domain = 'messages') { return $translator instanceof TranslatorStrongTypeInterface ? $translator->getFromCatalogue($catalogue, $id, $domain) : $catalogue->get($id, $domain); // @codeCoverageIgnore } /** * Return the word cleaned from its translation codes. * * @param string $word * * @return string */ private static function cleanWordFromTranslationString($word) { $word = str_replace([':count', '%count', ':time'], '', $word); $word = strtr($word, ['’' => "'"]); $word = preg_replace( '/\{(?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?}|[\[\]](?:-?\d+(?:\.\d+)?|-?Inf)(?:,(?:-?\d+|-?Inf))?[\[\]]/', '', $word, ); return trim($word); } /** * Translate a list of words. * * @param string[] $keys keys to translate. * @param string[] $messages messages bag handling translations. * @param string $key 'to' (to get the translation) or 'from' (to get the detection RegExp pattern). * * @return string[] */ private static function translateWordsByKeys($keys, $messages, $key): array { return array_map(function ($wordKey) use ($messages, $key) { $message = $key === 'from' && isset($messages[$wordKey.'_regexp']) ? $messages[$wordKey.'_regexp'] : ($messages[$wordKey] ?? null); if (!$message) { return '>>DO NOT REPLACE<<'; } $parts = explode('|', $message); return $key === 'to' ? self::cleanWordFromTranslationString(end($parts)) : '(?:'.implode('|', array_map(static::cleanWordFromTranslationString(...), $parts)).')'; }, $keys); } /** * Get an array of translations based on the current date. * * @param callable $translation * @param int $length * @param string $timeString * * @return string[] */ private static function getTranslationArray($translation, $length, $timeString): array { $filler = '>>DO NOT REPLACE<<'; if (\is_array($translation)) { return array_pad($translation, $length, $filler); } $list = []; $date = static::now(); for ($i = 0; $i < $length; $i++) { $list[] = $translation($date, $timeString, $i) ?? $filler; } return $list; } private static function replaceOrdinalWords(string $timeString, array $ordinalWords): string { return preg_replace_callback('/(?<![a-z])[a-z]+(?![a-z])/i', function (array $match) use ($ordinalWords) { return $ordinalWords[mb_strtolower($match[0])] ?? $match[0]; }, $timeString); } }
PHP
{ "end_line": 568, "name": "localeHasPeriodSyntax", "signature": "public static function localeHasPeriodSyntax($locale)", "start_line": 559 }
{ "class_name": "Localization", "class_signature": "trait Localization", "namespace": "Carbon\\Traits" }
change
Carbon/src/Carbon/Traits/Modifiers.php
public function change($modifier) { return $this->modify(preg_replace_callback('/^(next|previous|last)\s+(\d{1,2}(h|am|pm|:\d{1,2}(:\d{1,2})?))$/i', function ($match) { $match[2] = str_replace('h', ':00', $match[2]); $test = $this->avoidMutation()->modify($match[2]); $method = $match[1] === 'next' ? 'lt' : 'gt'; $match[1] = $test->$method($this) ? $match[1].' day' : 'today'; return $match[1].' '.$match[2]; }, strtr(trim($modifier), [ ' at ' => ' ', 'just now' => 'now', 'after tomorrow' => 'tomorrow +1 day', 'before yesterday' => 'yesterday -1 day', ]))); }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\CarbonInterface; use Carbon\Exceptions\InvalidFormatException; use ReturnTypeWillChange; /** * Trait Modifiers. * * Returns dates relative to current date using modifier short-hand. */ trait Modifiers { /** * Midday/noon hour. * * @var int */ protected static $midDayAt = 12; /** * get midday/noon hour * * @return int */ public static function getMidDayAt() { return static::$midDayAt; } /** * @deprecated To avoid conflict between different third-party libraries, static setters should not be used. * You should rather consider mid-day is always 12pm, then if you need to test if it's an other * hour, test it explicitly: * $date->format('G') == 13 * or to set explicitly to a given hour: * $date->setTime(13, 0, 0, 0) * * Set midday/noon hour * * @param int $hour midday hour * * @return void */ public static function setMidDayAt($hour) { static::$midDayAt = $hour; } /** * Modify to midday, default to self::$midDayAt * * @return static */ public function midDay() { return $this->setTime(static::$midDayAt, 0, 0, 0); } /** * Modify to the next occurrence of a given modifier such as a day of * the week. If no modifier is provided, modify to the next occurrence * of the current day of the week. Use the supplied constants * to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param string|int|null $modifier * * @return static */ public function next($modifier = null) { if ($modifier === null) { $modifier = $this->dayOfWeek; } return $this->change( 'next '.(\is_string($modifier) ? $modifier : static::$days[$modifier]), ); } /** * Go forward or backward to the next week- or weekend-day. * * @param bool $weekday * @param bool $forward * * @return static */ private function nextOrPreviousDay($weekday = true, $forward = true) { /** @var CarbonInterface $date */ $date = $this; $step = $forward ? 1 : -1; do { $date = $date->addDays($step); } while ($weekday ? $date->isWeekend() : $date->isWeekday()); return $date; } /** * Go forward to the next weekday. * * @return static */ public function nextWeekday() { return $this->nextOrPreviousDay(); } /** * Go backward to the previous weekday. * * @return static */ public function previousWeekday() { return $this->nextOrPreviousDay(true, false); } /** * Go forward to the next weekend day. * * @return static */ public function nextWeekendDay() { return $this->nextOrPreviousDay(false); } /** * Go backward to the previous weekend day. * * @return static */ public function previousWeekendDay() { return $this->nextOrPreviousDay(false, false); } /** * Modify to the previous occurrence of a given modifier such as a day of * the week. If no dayOfWeek is provided, modify to the previous occurrence * of the current day of the week. Use the supplied constants * to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param string|int|null $modifier * * @return static */ public function previous($modifier = null) { if ($modifier === null) { $modifier = $this->dayOfWeek; } return $this->change( 'last '.(\is_string($modifier) ? $modifier : static::$days[$modifier]), ); } /** * Modify to the first occurrence of a given day of the week * in the current month. If no dayOfWeek is provided, modify to the * first day of the current month. Use the supplied constants * to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param int|null $dayOfWeek * * @return static */ public function firstOfMonth($dayOfWeek = null) { $date = $this->startOfDay(); if ($dayOfWeek === null) { return $date->day(1); } return $date->modify('first '.static::$days[$dayOfWeek].' of '.$date->rawFormat('F').' '.$date->year); } /** * Modify to the last occurrence of a given day of the week * in the current month. If no dayOfWeek is provided, modify to the * last day of the current month. Use the supplied constants * to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param int|null $dayOfWeek * * @return static */ public function lastOfMonth($dayOfWeek = null) { $date = $this->startOfDay(); if ($dayOfWeek === null) { return $date->day($date->daysInMonth); } return $date->modify('last '.static::$days[$dayOfWeek].' of '.$date->rawFormat('F').' '.$date->year); } /** * Modify to the given occurrence of a given day of the week * in the current month. If the calculated occurrence is outside the scope * of the current month, then return false and no modifications are made. * Use the supplied constants to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param int $nth * @param int $dayOfWeek * * @return mixed */ public function nthOfMonth($nth, $dayOfWeek) { $date = $this->avoidMutation()->firstOfMonth(); $check = $date->rawFormat('Y-m'); $date = $date->modify('+'.$nth.' '.static::$days[$dayOfWeek]); return $date->rawFormat('Y-m') === $check ? $this->modify((string) $date) : false; } /** * Modify to the first occurrence of a given day of the week * in the current quarter. If no dayOfWeek is provided, modify to the * first day of the current quarter. Use the supplied constants * to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param int|null $dayOfWeek day of the week default null * * @return static */ public function firstOfQuarter($dayOfWeek = null) { return $this->setDate($this->year, $this->quarter * static::MONTHS_PER_QUARTER - 2, 1)->firstOfMonth($dayOfWeek); } /** * Modify to the last occurrence of a given day of the week * in the current quarter. If no dayOfWeek is provided, modify to the * last day of the current quarter. Use the supplied constants * to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param int|null $dayOfWeek day of the week default null * * @return static */ public function lastOfQuarter($dayOfWeek = null) { return $this->setDate($this->year, $this->quarter * static::MONTHS_PER_QUARTER, 1)->lastOfMonth($dayOfWeek); } /** * Modify to the given occurrence of a given day of the week * in the current quarter. If the calculated occurrence is outside the scope * of the current quarter, then return false and no modifications are made. * Use the supplied constants to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param int $nth * @param int $dayOfWeek * * @return mixed */ public function nthOfQuarter($nth, $dayOfWeek) { $date = $this->avoidMutation()->day(1)->month($this->quarter * static::MONTHS_PER_QUARTER); $lastMonth = $date->month; $year = $date->year; $date = $date->firstOfQuarter()->modify('+'.$nth.' '.static::$days[$dayOfWeek]); return ($lastMonth < $date->month || $year !== $date->year) ? false : $this->modify((string) $date); } /** * Modify to the first occurrence of a given day of the week * in the current year. If no dayOfWeek is provided, modify to the * first day of the current year. Use the supplied constants * to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param int|null $dayOfWeek day of the week default null * * @return static */ public function firstOfYear($dayOfWeek = null) { return $this->month(1)->firstOfMonth($dayOfWeek); } /** * Modify to the last occurrence of a given day of the week * in the current year. If no dayOfWeek is provided, modify to the * last day of the current year. Use the supplied constants * to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param int|null $dayOfWeek day of the week default null * * @return static */ public function lastOfYear($dayOfWeek = null) { return $this->month(static::MONTHS_PER_YEAR)->lastOfMonth($dayOfWeek); } /** * Modify to the given occurrence of a given day of the week * in the current year. If the calculated occurrence is outside the scope * of the current year, then return false and no modifications are made. * Use the supplied constants to indicate the desired dayOfWeek, ex. static::MONDAY. * * @param int $nth * @param int $dayOfWeek * * @return mixed */ public function nthOfYear($nth, $dayOfWeek) { $date = $this->avoidMutation()->firstOfYear()->modify('+'.$nth.' '.static::$days[$dayOfWeek]); return $this->year === $date->year ? $this->modify((string) $date) : false; } /** * Modify the current instance to the average of a given instance (default now) and the current instance * (second-precision). * * @param \Carbon\Carbon|\DateTimeInterface|null $date * * @return static */ public function average($date = null) { return $this->addRealMicroseconds((int) ($this->diffInMicroseconds($this->resolveCarbon($date), false) / 2)); } /** * Get the closest date from the instance (second-precision). * * @param \Carbon\Carbon|\DateTimeInterface|mixed $date1 * @param \Carbon\Carbon|\DateTimeInterface|mixed $date2 * * @return static */ public function closest($date1, $date2) { return $this->diffInMicroseconds($date1, true) < $this->diffInMicroseconds($date2, true) ? $date1 : $date2; } /** * Get the farthest date from the instance (second-precision). * * @param \Carbon\Carbon|\DateTimeInterface|mixed $date1 * @param \Carbon\Carbon|\DateTimeInterface|mixed $date2 * * @return static */ public function farthest($date1, $date2) { return $this->diffInMicroseconds($date1, true) > $this->diffInMicroseconds($date2, true) ? $date1 : $date2; } /** * Get the minimum instance between a given instance (default now) and the current instance. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $date * * @return static */ public function min($date = null) { $date = $this->resolveCarbon($date); return $this->lt($date) ? $this : $date; } /** * Get the minimum instance between a given instance (default now) and the current instance. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $date * * @see min() * * @return static */ public function minimum($date = null) { return $this->min($date); } /** * Get the maximum instance between a given instance (default now) and the current instance. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $date * * @return static */ public function max($date = null) { $date = $this->resolveCarbon($date); return $this->gt($date) ? $this : $date; } /** * Get the maximum instance between a given instance (default now) and the current instance. * * @param \Carbon\Carbon|\DateTimeInterface|mixed $date * * @see max() * * @return static */ public function maximum($date = null) { return $this->max($date); } /** * Calls \DateTime::modify if mutable or \DateTimeImmutable::modify else. * * @see https://php.net/manual/en/datetime.modify.php * * @return static */ #[ReturnTypeWillChange] public function modify($modify) { return parent::modify((string) $modify) ?: throw new InvalidFormatException('Could not modify with: '.var_export($modify, true)); } /** * Similar to native modify() method of DateTime but can handle more grammars. * * @example * ``` * echo Carbon::now()->change('next 2pm'); * ``` * * @link https://php.net/manual/en/datetime.modify.php * * @param string $modifier * * @return static */ public function change($modifier) { return $this->modify(preg_replace_callback('/^(next|previous|last)\s+(\d{1,2}(h|am|pm|:\d{1,2}(:\d{1,2})?))$/i', function ($match) { $match[2] = str_replace('h', ':00', $match[2]); $test = $this->avoidMutation()->modify($match[2]); $method = $match[1] === 'next' ? 'lt' : 'gt'; $match[1] = $test->$method($this) ? $match[1].' day' : 'today'; return $match[1].' '.$match[2]; }, strtr(trim($modifier), [ ' at ' => ' ', 'just now' => 'now', 'after tomorrow' => 'tomorrow +1 day', 'before yesterday' => 'yesterday -1 day', ]))); } }
PHP
{ "end_line": 475, "name": "change", "signature": "public function change($modifier)", "start_line": 460 }
{ "class_name": "Modifiers", "class_signature": "trait Modifiers", "namespace": "Carbon\\Traits" }
settings
Carbon/src/Carbon/Traits/Options.php
public function settings(array $settings): static { $this->localStrictModeEnabled = $settings['strictMode'] ?? null; $this->localMonthsOverflow = $settings['monthOverflow'] ?? null; $this->localYearsOverflow = $settings['yearOverflow'] ?? null; $this->localHumanDiffOptions = $settings['humanDiffOptions'] ?? null; $this->localToStringFormat = $settings['toStringFormat'] ?? null; $this->localSerializer = $settings['toJsonFormat'] ?? null; $this->localMacros = $settings['macros'] ?? null; $this->localGenericMacros = $settings['genericMacros'] ?? null; $this->localFormatFunction = $settings['formatFunction'] ?? null; if (isset($settings['locale'])) { $locales = $settings['locale']; if (!\is_array($locales)) { $locales = [$locales]; } $this->locale(...$locales); } elseif (isset($settings['translator']) && property_exists($this, 'localTranslator')) { $this->localTranslator = $settings['translator']; } if (isset($settings['innerTimezone'])) { return $this->setTimezone($settings['innerTimezone']); } if (isset($settings['timezone'])) { return $this->shiftTimezone($settings['timezone']); } return $this; }
<?php declare(strict_types=1); /** * This file is part of the Carbon package. * * (c) Brian Nesbitt <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Carbon\Traits; use Carbon\CarbonInterface; use DateTimeInterface; use Throwable; /** * Trait Options. * * Embed base methods to change settings of Carbon classes. * * Depends on the following methods: * * @method static shiftTimezone($timezone) Set the timezone */ trait Options { use StaticOptions; use Localization; /** * Indicates if months should be calculated with overflow. * Specific setting. */ protected ?bool $localMonthsOverflow = null; /** * Indicates if years should be calculated with overflow. * Specific setting. */ protected ?bool $localYearsOverflow = null; /** * Indicates if the strict mode is in use. * Specific setting. */ protected ?bool $localStrictModeEnabled = null; /** * Options for diffForHumans and forHumans methods. */ protected ?int $localHumanDiffOptions = null; /** * Format to use on string cast. * * @var string|callable|null */ protected $localToStringFormat = null; /** * Format to use on JSON serialization. * * @var string|callable|null */ protected $localSerializer = null; /** * Instance-specific macros. */ protected ?array $localMacros = null; /** * Instance-specific generic macros. */ protected ?array $localGenericMacros = null; /** * Function to call instead of format. * * @var string|callable|null */ protected $localFormatFunction = null; /** * Set specific options. * - strictMode: true|false|null * - monthOverflow: true|false|null * - yearOverflow: true|false|null * - humanDiffOptions: int|null * - toStringFormat: string|Closure|null * - toJsonFormat: string|Closure|null * - locale: string|null * - timezone: \DateTimeZone|string|int|null * - macros: array|null * - genericMacros: array|null * * @param array $settings * * @return $this|static */ public function settings(array $settings): static { $this->localStrictModeEnabled = $settings['strictMode'] ?? null; $this->localMonthsOverflow = $settings['monthOverflow'] ?? null; $this->localYearsOverflow = $settings['yearOverflow'] ?? null; $this->localHumanDiffOptions = $settings['humanDiffOptions'] ?? null; $this->localToStringFormat = $settings['toStringFormat'] ?? null; $this->localSerializer = $settings['toJsonFormat'] ?? null; $this->localMacros = $settings['macros'] ?? null; $this->localGenericMacros = $settings['genericMacros'] ?? null; $this->localFormatFunction = $settings['formatFunction'] ?? null; if (isset($settings['locale'])) { $locales = $settings['locale']; if (!\is_array($locales)) { $locales = [$locales]; } $this->locale(...$locales); } elseif (isset($settings['translator']) && property_exists($this, 'localTranslator')) { $this->localTranslator = $settings['translator']; } if (isset($settings['innerTimezone'])) { return $this->setTimezone($settings['innerTimezone']); } if (isset($settings['timezone'])) { return $this->shiftTimezone($settings['timezone']); } return $this; } /** * Returns current local settings. */ public function getSettings(): array { $settings = []; $map = [ 'localStrictModeEnabled' => 'strictMode', 'localMonthsOverflow' => 'monthOverflow', 'localYearsOverflow' => 'yearOverflow', 'localHumanDiffOptions' => 'humanDiffOptions', 'localToStringFormat' => 'toStringFormat', 'localSerializer' => 'toJsonFormat', 'localMacros' => 'macros', 'localGenericMacros' => 'genericMacros', 'locale' => 'locale', 'tzName' => 'timezone', 'localFormatFunction' => 'formatFunction', ]; foreach ($map as $property => $key) { $value = $this->$property ?? null; if ($value !== null && ($key !== 'locale' || $value !== 'en' || $this->localTranslator)) { $settings[$key] = $value; } } return $settings; } /** * Show truthy properties on var_dump(). */ public function __debugInfo(): array { $infos = array_filter(get_object_vars($this), static function ($var) { return $var; }); foreach (['dumpProperties', 'constructedObjectId', 'constructed', 'originalInput'] as $property) { if (isset($infos[$property])) { unset($infos[$property]); } } $this->addExtraDebugInfos($infos); foreach (["\0*\0", ''] as $prefix) { $key = $prefix.'carbonRecurrences'; if (\array_key_exists($key, $infos)) { $infos['recurrences'] = $infos[$key]; unset($infos[$key]); } } return $infos; } protected function isLocalStrictModeEnabled(): bool { return $this->localStrictModeEnabled ?? $this->transmitFactory(static fn () => static::isStrictModeEnabled()); } protected function addExtraDebugInfos(array &$infos): void { if ($this instanceof DateTimeInterface) { try { $infos['date'] ??= $this->format(CarbonInterface::MOCK_DATETIME_FORMAT); $infos['timezone'] ??= $this->tzName ?? $this->timezoneSetting ?? $this->timezone ?? null; } catch (Throwable) { // noop } } } }
PHP
{ "end_line": 138, "name": "settings", "signature": "public function settings(array $settings): static", "start_line": 105 }
{ "class_name": "Options", "class_signature": "trait Options", "namespace": "Carbon\\Traits" }