Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • sibidharan/api-development-course-apr-2021
  • krithikramraja/api-development-course-apr-2021
  • monish-palanikumar/api-development-course-apr-2021
  • Pranesh/api-development-course-apr-2021
  • ganesha005/api-development-course-apr-2021
  • selva1011/api-development-course-apr-2021
  • hema/api-development-course-apr-2021
  • Kartheeekn/api-development-course-apr-2021
  • GopiKrishnan/api-development-course-apr-2021
  • Mhd_khalid/api-development-course-apr-2021
  • sibivarma/api-development-course-apr-2021
  • ramanajsr1/api-development-course-apr-2021
  • rahulprem2k2910/api-development-course-apr-2021
  • sabarinathanfb/api-development-course-apr-2021
  • hariharanrd/api-development-course-apr-2021
  • Akram24/api-development-course-apr-2021
  • At_muthu__/api-development-course-apr-2021
  • rii/api-development-course-apr-2021
  • harishvarmaj7/api-development-course-apr-2021
  • moovendhan/rest-api
  • k3XD16/api-development-course-apr-2021
  • vimal/api-development-course-apr-2021
  • shiva007/api-development-course-apr-2021
  • Amudhan/api-development-course-apr-2021
  • abinayacyber604/api-development-course-apr-2021
  • subash_19/api
  • Saransaran/api-development-course-apr-2021
27 results
Show changes
Showing
with 8680 additions and 0 deletions
<?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* 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\UnknownUnitException;
/**
* Trait Boundaries.
*
* startOf, endOf and derived method for each unit.
*
* Depends on the following properties:
*
* @property int $year
* @property int $month
* @property int $daysInMonth
* @property int $quarter
*
* Depends on the following methods:
*
* @method $this setTime(int $hour, int $minute, int $second = 0, int $microseconds = 0)
* @method $this setDate(int $year, int $month, int $day)
* @method $this addMonths(int $value = 1)
*/
trait Boundaries
{
/**
* Resets the time to 00:00:00 start of day
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfDay();
* ```
*
* @return static
*/
public function startOfDay()
{
return $this->setTime(0, 0, 0, 0);
}
/**
* Resets the time to 23:59:59.999999 end of day
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfDay();
* ```
*
* @return static
*/
public function endOfDay()
{
return $this->setTime(static::HOURS_PER_DAY - 1, static::MINUTES_PER_HOUR - 1, static::SECONDS_PER_MINUTE - 1, static::MICROSECONDS_PER_SECOND - 1);
}
/**
* Resets the date to the first day of the month and the time to 00:00:00
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfMonth();
* ```
*
* @return static
*/
public function startOfMonth()
{
return $this->setDate($this->year, $this->month, 1)->startOfDay();
}
/**
* Resets the date to end of the month and time to 23:59:59.999999
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfMonth();
* ```
*
* @return static
*/
public function endOfMonth()
{
return $this->setDate($this->year, $this->month, $this->daysInMonth)->endOfDay();
}
/**
* Resets the date to the first day of the quarter and the time to 00:00:00
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfQuarter();
* ```
*
* @return static
*/
public function startOfQuarter()
{
$month = ($this->quarter - 1) * static::MONTHS_PER_QUARTER + 1;
return $this->setDate($this->year, $month, 1)->startOfDay();
}
/**
* Resets the date to end of the quarter and time to 23:59:59.999999
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfQuarter();
* ```
*
* @return static
*/
public function endOfQuarter()
{
return $this->startOfQuarter()->addMonths(static::MONTHS_PER_QUARTER - 1)->endOfMonth();
}
/**
* Resets the date to the first day of the year and the time to 00:00:00
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfYear();
* ```
*
* @return static
*/
public function startOfYear()
{
return $this->setDate($this->year, 1, 1)->startOfDay();
}
/**
* Resets the date to end of the year and time to 23:59:59.999999
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfYear();
* ```
*
* @return static
*/
public function endOfYear()
{
return $this->setDate($this->year, 12, 31)->endOfDay();
}
/**
* Resets the date to the first day of the decade and the time to 00:00:00
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfDecade();
* ```
*
* @return static
*/
public function startOfDecade()
{
$year = $this->year - $this->year % static::YEARS_PER_DECADE;
return $this->setDate($year, 1, 1)->startOfDay();
}
/**
* Resets the date to end of the decade and time to 23:59:59.999999
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfDecade();
* ```
*
* @return static
*/
public function endOfDecade()
{
$year = $this->year - $this->year % static::YEARS_PER_DECADE + static::YEARS_PER_DECADE - 1;
return $this->setDate($year, 12, 31)->endOfDay();
}
/**
* Resets the date to the first day of the century and the time to 00:00:00
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfCentury();
* ```
*
* @return static
*/
public function startOfCentury()
{
$year = $this->year - ($this->year - 1) % static::YEARS_PER_CENTURY;
return $this->setDate($year, 1, 1)->startOfDay();
}
/**
* Resets the date to end of the century and time to 23:59:59.999999
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfCentury();
* ```
*
* @return static
*/
public function endOfCentury()
{
$year = $this->year - 1 - ($this->year - 1) % static::YEARS_PER_CENTURY + static::YEARS_PER_CENTURY;
return $this->setDate($year, 12, 31)->endOfDay();
}
/**
* Resets the date to the first day of the millennium and the time to 00:00:00
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfMillennium();
* ```
*
* @return static
*/
public function startOfMillennium()
{
$year = $this->year - ($this->year - 1) % static::YEARS_PER_MILLENNIUM;
return $this->setDate($year, 1, 1)->startOfDay();
}
/**
* Resets the date to end of the millennium and time to 23:59:59.999999
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfMillennium();
* ```
*
* @return static
*/
public function endOfMillennium()
{
$year = $this->year - 1 - ($this->year - 1) % static::YEARS_PER_MILLENNIUM + static::YEARS_PER_MILLENNIUM;
return $this->setDate($year, 12, 31)->endOfDay();
}
/**
* Resets the date to the first day of week (defined in $weekStartsAt) and the time to 00:00:00
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfWeek() . "\n";
* echo Carbon::parse('2018-07-25 12:45:16')->locale('ar')->startOfWeek() . "\n";
* echo Carbon::parse('2018-07-25 12:45:16')->startOfWeek(Carbon::SUNDAY) . "\n";
* ```
*
* @param int $weekStartsAt optional start allow you to specify the day of week to use to start the week
*
* @return static
*/
public function startOfWeek($weekStartsAt = null)
{
return $this->subDays((7 + $this->dayOfWeek - ($weekStartsAt ?? $this->firstWeekDay)) % 7)->startOfDay();
}
/**
* Resets the date to end of week (defined in $weekEndsAt) and time to 23:59:59.999999
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfWeek() . "\n";
* echo Carbon::parse('2018-07-25 12:45:16')->locale('ar')->endOfWeek() . "\n";
* echo Carbon::parse('2018-07-25 12:45:16')->endOfWeek(Carbon::SATURDAY) . "\n";
* ```
*
* @param int $weekEndsAt optional start allow you to specify the day of week to use to end the week
*
* @return static
*/
public function endOfWeek($weekEndsAt = null)
{
return $this->addDays((7 - $this->dayOfWeek + ($weekEndsAt ?? $this->lastWeekDay)) % 7)->endOfDay();
}
/**
* Modify to start of current hour, minutes and seconds become 0
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfHour();
* ```
*
* @return static
*/
public function startOfHour()
{
return $this->setTime($this->hour, 0, 0, 0);
}
/**
* Modify to end of current hour, minutes and seconds become 59
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfHour();
* ```
*
* @return static
*/
public function endOfHour()
{
return $this->setTime($this->hour, static::MINUTES_PER_HOUR - 1, static::SECONDS_PER_MINUTE - 1, static::MICROSECONDS_PER_SECOND - 1);
}
/**
* Modify to start of current minute, seconds become 0
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->startOfMinute();
* ```
*
* @return static
*/
public function startOfMinute()
{
return $this->setTime($this->hour, $this->minute, 0, 0);
}
/**
* Modify to end of current minute, seconds become 59
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16')->endOfMinute();
* ```
*
* @return static
*/
public function endOfMinute()
{
return $this->setTime($this->hour, $this->minute, static::SECONDS_PER_MINUTE - 1, static::MICROSECONDS_PER_SECOND - 1);
}
/**
* Modify to start of current second, microseconds become 0
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16.334455')
* ->startOfSecond()
* ->format('H:i:s.u');
* ```
*
* @return static
*/
public function startOfSecond()
{
return $this->setTime($this->hour, $this->minute, $this->second, 0);
}
/**
* Modify to end of current second, microseconds become 999999
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16.334455')
* ->endOfSecond()
* ->format('H:i:s.u');
* ```
*
* @return static
*/
public function endOfSecond()
{
return $this->setTime($this->hour, $this->minute, $this->second, static::MICROSECONDS_PER_SECOND - 1);
}
/**
* Modify to start of current given unit.
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16.334455')
* ->startOf('month')
* ->endOf('week', Carbon::FRIDAY);
* ```
*
* @param string $unit
* @param array<int, mixed> $params
*
* @return static
*/
public function startOf($unit, ...$params)
{
$ucfUnit = ucfirst(static::singularUnit($unit));
$method = "startOf$ucfUnit";
if (!method_exists($this, $method)) {
throw new UnknownUnitException($unit);
}
return $this->$method(...$params);
}
/**
* Modify to end of current given unit.
*
* @example
* ```
* echo Carbon::parse('2018-07-25 12:45:16.334455')
* ->startOf('month')
* ->endOf('week', Carbon::FRIDAY);
* ```
*
* @param string $unit
* @param array<int, mixed> $params
*
* @return static
*/
public function endOf($unit, ...$params)
{
$ucfUnit = ucfirst(static::singularUnit($unit));
$method = "endOf$ucfUnit";
if (!method_exists($this, $method)) {
throw new UnknownUnitException($unit);
}
return $this->$method(...$params);
}
}
<?php
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.
*
* @param string $className The $className::instance() method will be called to cast the current object.
*
* @return DateTimeInterface
*/
public function cast(string $className)
{
if (!method_exists($className, 'instance')) {
if (is_a($className, DateTimeInterface::class, true)) {
return new $className($this->rawFormat('Y-m-d H:i:s.u'), $this->getTimezone());
}
throw new InvalidCastException("$className has not the instance() method needed to cast the date.");
}
return $className::instance($this);
}
}
<?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* 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\CarbonInterface;
use Carbon\Exceptions\BadComparisonUnitException;
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
{
/** @var bool */
protected $endOfTime = false;
/** @var bool */
protected $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
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @see equalTo()
*
* @return bool
*/
public function eq($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
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @return bool
*/
public function equalTo($date): bool
{
return $this == $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
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @see notEqualTo()
*
* @return bool
*/
public function ne($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
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @return bool
*/
public function notEqualTo($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
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @see greaterThan()
*
* @return bool
*/
public function gt($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
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @return bool
*/
public function greaterThan($date): bool
{
return $this > $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
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @see greaterThan()
*
* @return bool
*/
public function isAfter($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
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @see greaterThanOrEqualTo()
*
* @return bool
*/
public function gte($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
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @return bool
*/
public function greaterThanOrEqualTo($date): bool
{
return $this >= $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
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @see lessThan()
*
* @return bool
*/
public function lt($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
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @return bool
*/
public function lessThan($date): bool
{
return $this < $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
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @see lessThan()
*
* @return bool
*/
public function isBefore($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
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @see lessThanOrEqualTo()
*
* @return bool
*/
public function lte($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
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date
*
* @return bool
*/
public function lessThanOrEqualTo($date): bool
{
return $this <= $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 \Carbon\Carbon|\DateTimeInterface|mixed $date1
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date2
* @param bool $equal Indicates if an equal to comparison should be done
*
* @return bool
*/
public function between($date1, $date2, $equal = true): bool
{
$date1 = $this->resolveCarbon($date1);
$date2 = $this->resolveCarbon($date2);
if ($date1->greaterThan($date2)) {
[$date1, $date2] = [$date2, $date1];
}
if ($equal) {
return $this->greaterThanOrEqualTo($date1) && $this->lessThanOrEqualTo($date2);
}
return $this->greaterThan($date1) && $this->lessThan($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
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date1
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date2
*
* @return bool
*/
public function betweenIncluded($date1, $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
* ```
*
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date1
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date2
*
* @return bool
*/
public function betweenExcluded($date1, $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 \Carbon\Carbon|\DateTimeInterface|mixed $date1
* @param \Carbon\Carbon|\DateTimeInterface|mixed $date2
* @param bool $equal Indicates if an equal to comparison should be done
*
* @return bool
*/
public function isBetween($date1, $date2, $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
* ```
*
* @return bool
*/
public function isWeekday()
{
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
* ```
*
* @return bool
*/
public function isWeekend()
{
return \in_array($this->dayOfWeek, static::$weekendDays);
}
/**
* Determines if the instance is yesterday.
*
* @example
* ```
* Carbon::yesterday()->isYesterday(); // true
* Carbon::tomorrow()->isYesterday(); // false
* ```
*
* @return bool
*/
public function isYesterday()
{
return $this->toDateString() === static::yesterday($this->getTimezone())->toDateString();
}
/**
* Determines if the instance is today.
*
* @example
* ```
* Carbon::today()->isToday(); // true
* Carbon::tomorrow()->isToday(); // false
* ```
*
* @return bool
*/
public function isToday()
{
return $this->toDateString() === $this->nowWithSameTz()->toDateString();
}
/**
* Determines if the instance is tomorrow.
*
* @example
* ```
* Carbon::tomorrow()->isTomorrow(); // true
* Carbon::yesterday()->isTomorrow(); // false
* ```
*
* @return bool
*/
public function isTomorrow()
{
return $this->toDateString() === 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
* ```
*
* @return bool
*/
public function isFuture()
{
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
* ```
*
* @return bool
*/
public function isPast()
{
return $this->lessThan($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
* ```
*
* @return bool
*/
public function isLeapYear()
{
return $this->rawFormat('L') === '1';
}
/**
* Determines if the instance is a long year
*
* @example
* ```
* Carbon::parse('2015-01-01')->isLongYear(); // true
* Carbon::parse('2016-01-01')->isLongYear(); // false
* ```
*
* @see https://en.wikipedia.org/wiki/ISO_8601#Week_dates
*
* @return bool
*/
public function isLongYear()
{
return static::create($this->year, 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 \Carbon\Carbon|\DateTimeInterface|string|null $date instance to compare with or null to use current day.
*
* @return bool
*/
public function isSameAs($format, $date = null)
{
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 \Carbon\Carbon|\DateTimeInterface|null $date instance to compare with or null to use current day.
*
* @throws BadComparisonUnitException
*
* @return bool
*/
public function isSameUnit($unit, $date = null)
{
$units = [
// @call isSameUnit
'year' => 'Y',
// @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
'micro' => 'Y-m-d H:i:s.u',
// @call isSameUnit
'microsecond' => 'Y-m-d H:i:s.u',
];
if (!isset($units[$unit])) {
if (isset($this->$unit)) {
return $this->$unit === $this->resolveCarbon($date)->$unit;
}
if ($this->localStrictModeEnabled ?? static::isStrictModeEnabled()) {
throw new BadComparisonUnitException($unit);
}
return false;
}
return $this->isSameAs($units[$unit], $date);
}
/**
* 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
*
* @return bool
*/
public function isCurrentUnit($unit)
{
return $this->{'isSame'.ucfirst($unit)}();
}
/**
* 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 \Carbon\Carbon|\DateTimeInterface|string|null $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($date = null, $ofSameYear = true)
{
$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 \Carbon\Carbon|\DateTimeInterface|null $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($date = null, $ofSameYear = true)
{
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 $dayOfWeek
*
* @return bool
*/
public function isDayOfWeek($dayOfWeek)
{
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 \Carbon\Carbon|\DateTimeInterface|null $date The instance to compare with or null to use current day.
*
* @return bool
*/
public function isBirthday($date = null)
{
return $this->isSameAs('md', $date);
}
/**
* 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
* ```
*
* @return bool
*/
public function isLastOfMonth()
{
return $this->day === $this->daysInMonth;
}
/**
* 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
*
* @return bool
*/
public function isStartOfDay($checkMicroseconds = false)
{
/* @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
*
* @return bool
*/
public function isEndOfDay($checkMicroseconds = false)
{
/* @var CarbonInterface $this */
return $checkMicroseconds
? $this->rawFormat('H:i:s.u') === '23:59:59.999999'
: $this->rawFormat('H:i:s') === '23:59:59';
}
/**
* 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
* ```
*
* @return bool
*/
public function isMidnight()
{
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
* ```
*
* @return bool
*/
public function isMidday()
{
/* @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
* ```
*
* @param string $date
* @param string $format
*
* @return bool
*/
public static function hasFormat($date, $format)
{
// 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 self::matchFormatPattern((string) $date, preg_quote((string) $format, '/'), static::$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
* ```
*
* @param string $date
* @param string $format
*
* @return bool
*/
public static function hasFormatWithModifiers($date, $format): bool
{
return self::matchFormatPattern((string) $date, (string) $format, array_merge(static::$regexFormats, static::$regexFormatModifiers));
}
/**
* 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
* ```
*
* @param string $date
* @param string $format
*
* @return bool
*/
public static function canBeCreatedFromFormat($date, $format)
{
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 $e) {
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
*
* @return bool
*/
public function is(string $tester)
{
$tester = trim($tester);
if (preg_match('/^\d+$/', $tester)) {
return $this->year === \intval($tester);
}
if (preg_match('/^\d{3,}-\d{1,2}$/', $tester)) {
return $this->isSameMonth(static::parse($tester));
}
if (preg_match('/^\d{1,2}-\d{1,2}$/', $tester)) {
return $this->isSameDay(static::parse($this->year.'-'.$tester));
}
$modifier = preg_replace('/(\d)h$/i', '$1:00', $tester);
/* @var CarbonInterface $max */
$median = static::parse('5555-06-15 12:30:30.555555')->modify($modifier);
$current = $this->copy();
/* @var CarbonInterface $other */
$other = $this->copy()->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 ($median->$unit === $minimum) {
$current = $current->startOf($startUnit);
break;
}
}
return $current->eq($other);
}
/**
* 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 static 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)).'])/',
function ($match) use ($replacements) {
return $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);
}
/**
* 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
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* 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\UnitException;
use Closure;
use DateTime;
use DateTimeImmutable;
/**
* 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
{
/**
* Format to use for __toString method when type juggling occurs.
*
* @var string|Closure|null
*/
protected static $toStringFormat = null;
/**
* Reset the format used to the default when type juggling a Carbon instance to a string
*
* @return void
*/
public static function resetToStringFormat()
{
static::setToStringFormat(null);
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather let Carbon object being casted to string with DEFAULT_TO_STRING_FORMAT, and
* use other method or custom format passed to format() method if you need to dump an other string
* format.
*
* Set the default format used when type juggling a Carbon instance to a string
*
* @param string|Closure|null $format
*
* @return void
*/
public static function setToStringFormat($format)
{
static::$toStringFormat = $format;
}
/**
* Returns the formatted date string on success or FALSE on failure.
*
* @see https://php.net/manual/en/datetime.format.php
*
* @param string $format
*
* @return string
*/
public function format($format)
{
$function = $this->localFormatFunction ?: 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
*
* @param string $format
*
* @return string
*/
public function rawFormat($format)
{
return parent::format($format);
}
/**
* Format the instance as a string using the set format
*
* @example
* ```
* echo Carbon::now(); // Carbon instances can be casted to string
* ```
*
* @return string
*/
public function __toString()
{
$format = $this->localToStringFormat ?? static::$toStringFormat;
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();
* ```
*
* @return string
*/
public function toDateString()
{
return $this->rawFormat('Y-m-d');
}
/**
* Format the instance as a readable date
*
* @example
* ```
* echo Carbon::now()->toFormattedDateString();
* ```
*
* @return string
*/
public function toFormattedDateString()
{
return $this->rawFormat('M j, Y');
}
/**
* Format the instance as time
*
* @example
* ```
* echo Carbon::now()->toTimeString();
* ```
*
* @param string $unitPrecision
*
* @return string
*/
public function toTimeString($unitPrecision = 'second')
{
return $this->rawFormat(static::getTimeFormatByPrecision($unitPrecision));
}
/**
* Format the instance as date and time
*
* @example
* ```
* echo Carbon::now()->toDateTimeString();
* ```
*
* @param string $unitPrecision
*
* @return string
*/
public function toDateTimeString($unitPrecision = 'second')
{
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"
*
* @return string
*/
public static function getTimeFormatByPrecision($unitPrecision)
{
switch (static::singularUnit($unitPrecision)) {
case 'minute':
return 'H:i';
case 'second':
return 'H:i:s';
case 'm':
case 'millisecond':
return 'H:i:s.v';
case 'µ':
case 'microsecond':
return 'H:i:s.u';
}
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
* ```
*
* @param string $unitPrecision
*
* @return string
*/
public function toDateTimeLocalString($unitPrecision = 'second')
{
return $this->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision));
}
/**
* Format the instance with day, date and time
*
* @example
* ```
* echo Carbon::now()->toDayDateTimeString();
* ```
*
* @return string
*/
public function toDayDateTimeString()
{
return $this->rawFormat('D, M j, Y g:i A');
}
/**
* Format the instance as ATOM
*
* @example
* ```
* echo Carbon::now()->toAtomString();
* ```
*
* @return string
*/
public function toAtomString()
{
return $this->rawFormat(DateTime::ATOM);
}
/**
* Format the instance as COOKIE
*
* @example
* ```
* echo Carbon::now()->toCookieString();
* ```
*
* @return string
*/
public function toCookieString()
{
return $this->rawFormat(DateTime::COOKIE);
}
/**
* Format the instance as ISO8601
*
* @example
* ```
* echo Carbon::now()->toIso8601String();
* ```
*
* @return string
*/
public function toIso8601String()
{
return $this->toAtomString();
}
/**
* Format the instance as RFC822
*
* @example
* ```
* echo Carbon::now()->toRfc822String();
* ```
*
* @return string
*/
public function toRfc822String()
{
return $this->rawFormat(DateTime::RFC822);
}
/**
* Convert the instance to UTC and return as Zulu ISO8601
*
* @example
* ```
* echo Carbon::now()->toIso8601ZuluString();
* ```
*
* @param string $unitPrecision
*
* @return string
*/
public function toIso8601ZuluString($unitPrecision = 'second')
{
return $this->copy()->utc()->rawFormat('Y-m-d\T'.static::getTimeFormatByPrecision($unitPrecision).'\Z');
}
/**
* Format the instance as RFC850
*
* @example
* ```
* echo Carbon::now()->toRfc850String();
* ```
*
* @return string
*/
public function toRfc850String()
{
return $this->rawFormat(DateTime::RFC850);
}
/**
* Format the instance as RFC1036
*
* @example
* ```
* echo Carbon::now()->toRfc1036String();
* ```
*
* @return string
*/
public function toRfc1036String()
{
return $this->rawFormat(DateTime::RFC1036);
}
/**
* Format the instance as RFC1123
*
* @example
* ```
* echo Carbon::now()->toRfc1123String();
* ```
*
* @return string
*/
public function toRfc1123String()
{
return $this->rawFormat(DateTime::RFC1123);
}
/**
* Format the instance as RFC2822
*
* @example
* ```
* echo Carbon::now()->toRfc2822String();
* ```
*
* @return string
*/
public function toRfc2822String()
{
return $this->rawFormat(DateTime::RFC2822);
}
/**
* Format the instance as RFC3339
*
* @param bool $extended
*
* @example
* ```
* echo Carbon::now()->toRfc3339String() . "\n";
* echo Carbon::now()->toRfc3339String(true) . "\n";
* ```
*
* @return string
*/
public function toRfc3339String($extended = false)
{
$format = DateTime::RFC3339;
if ($extended) {
$format = DateTime::RFC3339_EXTENDED;
}
return $this->rawFormat($format);
}
/**
* Format the instance as RSS
*
* @example
* ```
* echo Carbon::now()->toRssString();
* ```
*
* @return string
*/
public function toRssString()
{
return $this->rawFormat(DateTime::RSS);
}
/**
* Format the instance as W3C
*
* @example
* ```
* echo Carbon::now()->toW3cString();
* ```
*
* @return string
*/
public function toW3cString()
{
return $this->rawFormat(DateTime::W3C);
}
/**
* Format the instance as RFC7231
*
* @example
* ```
* echo Carbon::now()->toRfc7231String();
* ```
*
* @return string
*/
public function toRfc7231String()
{
return $this->copy()
->setTimezone('GMT')
->rawFormat(\defined('static::RFC7231_FORMAT') ? static::RFC7231_FORMAT : CarbonInterface::RFC7231_FORMAT);
}
/**
* Get default array representation.
*
* @example
* ```
* var_dump(Carbon::now()->toArray());
* ```
*
* @return array
*/
public function toArray()
{
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());
* ```
*
* @return object
*/
public function toObject()
{
return (object) $this->toArray();
}
/**
* Returns english human readable complete date string.
*
* @example
* ```
* echo Carbon::now()->toString();
* ```
*
* @return string
*/
public function toString()
{
return $this->copy()->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.
*
* @return null|string
*/
public function toISOString($keepOffset = false)
{
if (!$this->isValid()) {
return null;
}
$yearFormat = $this->year < 0 || $this->year > 9999 ? 'YYYYYY' : 'YYYY';
$tzFormat = $keepOffset ? 'Z' : '[Z]';
$date = $keepOffset ? $this : $this->copy()->utc();
return $date->isoFormat("$yearFormat-MM-DD[T]HH:mm:ss.SSSSSS$tzFormat");
}
/**
* Return the ISO-8601 string (ex: 1977-04-22T06:00:00Z) with UTC timezone.
*
* @example
* ```
* echo Carbon::now('America/Toronto')->toJSON();
* ```
*
* @return null|string
*/
public function toJSON()
{
return $this->toISOString();
}
/**
* Return native DateTime PHP object matching the current instance.
*
* @example
* ```
* var_dump(Carbon::now()->toDateTime());
* ```
*
* @return DateTime
*/
public function toDateTime()
{
return new DateTime($this->rawFormat('Y-m-d H:i:s.u'), $this->getTimezone());
}
/**
* Return native toDateTimeImmutable PHP object matching the current instance.
*
* @example
* ```
* var_dump(Carbon::now()->toDateTimeImmutable());
* ```
*
* @return DateTimeImmutable
*/
public function toDateTimeImmutable()
{
return new DateTimeImmutable($this->rawFormat('Y-m-d H:i:s.u'), $this->getTimezone());
}
/**
* @alias toDateTime
*
* Return native DateTime PHP object matching the current instance.
*
* @example
* ```
* var_dump(Carbon::now()->toDate());
* ```
*
* @return DateTime
*/
public function toDate()
{
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
*
* @return CarbonPeriod
*/
public function toPeriod($end = null, $interval = null, $unit = null)
{
if ($unit) {
$interval = CarbonInterval::make("$interval ".static::pluralUnit($unit));
}
$period = (new CarbonPeriod())->setDateClass(static::class)->setStartDate($this);
if ($interval) {
$period->setDateInterval($interval);
}
if (\is_int($end) || \is_string($end) && ctype_digit($end)) {
$period->setRecurrences($end);
} elseif ($end) {
$period->setEndDate($end);
}
return $period;
}
/**
* 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
*
* @return CarbonPeriod
*/
public function range($end = null, $interval = null, $unit = null)
{
return $this->toPeriod($end, $interval, $unit);
}
}
<?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* 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\OutOfRangeException;
use Carbon\Translator;
use Closure;
use DateTimeInterface;
use DateTimeZone;
use Exception;
/**
* Trait Creator.
*
* Static creators.
*
* Depends on the following methods:
*
* @method static Carbon|CarbonImmutable getTestNow()
*/
trait Creator
{
use ObjectInitialisation;
/**
* The errors that can occur.
*
* @var array
*/
protected static $lastErrors;
/**
* 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.
*
* @param DateTimeInterface|string|null $time
* @param DateTimeZone|string|null $tz
*
* @throws InvalidFormatException
*/
public function __construct($time = null, $tz = null)
{
if ($time instanceof DateTimeInterface) {
$time = $this->constructTimezoneFromDateTime($time, $tz)->format('Y-m-d H:i:s.u');
}
if (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 = empty($time) || $time === 'now';
if (method_exists(static::class, 'hasTestNow') &&
method_exists(static::class, 'getTestNow') &&
static::hasTestNow() &&
($isNow || static::hasRelativeKeywords($time))
) {
static::mockConstructorParameters($time, $tz);
}
// Work-around for PHP bug https://bugs.php.net/bug.php?id=67127
if (strpos((string) .1, '.') === false) {
$locale = setlocale(LC_NUMERIC, '0');
setlocale(LC_NUMERIC, 'C');
}
try {
parent::__construct($time ?: 'now', static::safeCreateDateTimeZone($tz) ?: null);
} catch (Exception $exception) {
throw new InvalidFormatException($exception->getMessage(), 0, $exception);
}
$this->constructedObjectId = spl_object_hash($this);
if (isset($locale)) {
setlocale(LC_NUMERIC, $locale);
}
static::setLastErrors(parent::getLastErrors());
}
/**
* Get timezone from a datetime instance.
*
* @param DateTimeInterface $date
* @param DateTimeZone|string|null $tz
*
* @return DateTimeInterface
*/
private function constructTimezoneFromDateTime(DateTimeInterface $date, &$tz)
{
if ($tz !== null) {
$safeTz = static::safeCreateDateTimeZone($tz);
if ($safeTz) {
return $date->setTimezone($safeTz);
}
return $date;
}
$tz = $date->getTimezone();
return $date;
}
/**
* Update constructedObjectId on cloned.
*/
public function __clone()
{
$this->constructedObjectId = spl_object_hash($this);
}
/**
* Create a Carbon instance from a DateTime one.
*
* @param DateTimeInterface $date
*
* @return static
*/
public static function instance($date)
{
if ($date instanceof static) {
return clone $date;
}
static::expectDateTime($date);
$instance = new static($date->format('Y-m-d H:i:s.u'), $date->getTimezone());
if ($date instanceof CarbonInterface || $date instanceof Options) {
$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().
*
* @param string|DateTimeInterface|null $time
* @param DateTimeZone|string|null $tz
*
* @throws InvalidFormatException
*
* @return static
*/
public static function rawParse($time = null, $tz = null)
{
if ($time instanceof DateTimeInterface) {
return static::instance($time);
}
try {
return new static($time, $tz);
} catch (Exception $exception) {
$date = @static::now($tz)->change($time);
if (!$date) {
throw new InvalidFormatException("Could not parse '$time': ".$exception->getMessage(), 0, $exception);
}
return $date;
}
}
/**
* 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().
*
* @param string|DateTimeInterface|null $time
* @param DateTimeZone|string|null $tz
*
* @throws InvalidFormatException
*
* @return static
*/
public static function parse($time = null, $tz = null)
{
$function = static::$parseFunction;
if (!$function) {
return static::rawParse($time, $tz);
}
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|null $tz optional timezone for the new instance.
*
* @throws InvalidFormatException
*
* @return static
*/
public static function parseFromLocale($time, $locale = null, $tz = null)
{
return static::rawParse(static::translateTimeString($time, $locale, 'en'), $tz);
}
/**
* Get a Carbon instance for the current date and time.
*
* @param DateTimeZone|string|null $tz
*
* @return static
*/
public static function now($tz = null)
{
return new static(null, $tz);
}
/**
* Create a Carbon instance for today.
*
* @param DateTimeZone|string|null $tz
*
* @return static
*/
public static function today($tz = null)
{
return static::rawParse('today', $tz);
}
/**
* Create a Carbon instance for tomorrow.
*
* @param DateTimeZone|string|null $tz
*
* @return static
*/
public static function tomorrow($tz = null)
{
return static::rawParse('tomorrow', $tz);
}
/**
* Create a Carbon instance for yesterday.
*
* @param DateTimeZone|string|null $tz
*
* @return static
*/
public static function yesterday($tz = null)
{
return static::rawParse('yesterday', $tz);
}
/**
* Create a Carbon instance for the greatest supported date.
*
* @return static
*/
public static function maxValue()
{
if (self::$PHPIntSize === 4) {
// 32 bit
return static::createFromTimestamp(PHP_INT_MAX); // @codeCoverageIgnore
}
// 64 bit
return static::create(9999, 12, 31, 23, 59, 59);
}
/**
* Create a Carbon instance for the lowest supported date.
*
* @return static
*/
public static function minValue()
{
if (self::$PHPIntSize === 4) {
// 32 bit
return static::createFromTimestamp(~PHP_INT_MAX); // @codeCoverageIgnore
}
// 64 bit
return static::create(1, 1, 1, 0, 0, 0);
}
private static function assertBetween($unit, $value, $min, $max)
{
if (static::isStrictModeEnabled() && ($value < $min || $value > $max)) {
throw new OutOfRangeException($unit, $min, $max, $value);
}
}
private static function createNowInstance($tz)
{
if (!static::hasTestNow()) {
return static::now($tz);
}
$now = static::getTestNow();
if ($now instanceof Closure) {
return $now(static::now($tz));
}
return $now;
}
/**
* 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 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|null $tz
*
* @throws InvalidFormatException
*
* @return static|false
*/
public static function create($year = 0, $month = 1, $day = 1, $hour = 0, $minute = 0, $second = 0, $tz = null)
{
if (\is_string($year) && !is_numeric($year)) {
return static::parse($year, $tz ?: (\is_string($month) || $month instanceof DateTimeZone ? $month : null));
}
$defaults = null;
$getDefault = function ($unit) use ($tz, &$defaults) {
if ($defaults === null) {
$now = self::createNowInstance($tz);
$defaults = array_combine([
'year',
'month',
'day',
'hour',
'minute',
'second',
], explode('-', $now->rawFormat('Y-n-j-G-i-s.u')));
}
return $defaults[$unit];
};
$year = $year === null ? $getDefault('year') : $year;
$month = $month === null ? $getDefault('month') : $month;
$day = $day === null ? $getDefault('day') : $day;
$hour = $hour === null ? $getDefault('hour') : $hour;
$minute = $minute === null ? $getDefault('minute') : $minute;
$second = (float) ($second === null ? $getDefault('second') : $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), $tz);
if ($fixYear !== null) {
$instance = $instance->addYears($fixYear);
}
return $instance;
}
/**
* 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|null $tz
*
* @throws InvalidDateException
*
* @return static|false
*/
public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null)
{
$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 false;
}
}
$instance = static::create($year, $month, $day, $hour, $minute, $second, $tz);
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 false;
}
}
return $instance;
}
/**
* 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|null $tz
*
* @throws InvalidFormatException
*
* @return static
*/
public static function createFromDate($year = null, $month = null, $day = null, $tz = null)
{
return static::create($year, $month, $day, null, null, null, $tz);
}
/**
* 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|null $tz
*
* @throws InvalidFormatException
*
* @return static
*/
public static function createMidnightDate($year = null, $month = null, $day = null, $tz = null)
{
return static::create($year, $month, $day, 0, 0, 0, $tz);
}
/**
* 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|null $tz
*
* @throws InvalidFormatException
*
* @return static
*/
public static function createFromTime($hour = 0, $minute = 0, $second = 0, $tz = null)
{
return static::create(null, null, null, $hour, $minute, $second, $tz);
}
/**
* Create a Carbon instance from a time string. The date portion is set to today.
*
* @param string $time
* @param DateTimeZone|string|null $tz
*
* @throws InvalidFormatException
*
* @return static
*/
public static function createFromTimeString($time, $tz = null)
{
return static::today($tz)->setTimeFromTimeString($time);
}
/**
* @param string $format Datetime format
* @param string $time
* @param DateTimeZone|string|false|null $originalTz
*
* @return DateTimeInterface|false
*/
private static function createFromFormatAndTimezone($format, $time, $originalTz)
{
// Work-around for https://bugs.php.net/bug.php?id=75577
// @codeCoverageIgnoreStart
if (version_compare(PHP_VERSION, '7.3.0-dev', '<')) {
$format = str_replace('.v', '.u', $format);
}
// @codeCoverageIgnoreEnd
if ($originalTz === null) {
return parent::createFromFormat($format, "$time");
}
$tz = \is_int($originalTz)
? @timezone_name_from_abbr('', (int) ($originalTz * static::MINUTES_PER_HOUR * static::SECONDS_PER_MINUTE), 1)
: $originalTz;
$tz = static::safeCreateDateTimeZone($tz, $originalTz);
if ($tz === false) {
return false;
}
return parent::createFromFormat($format, "$time", $tz);
}
/**
* Create a Carbon instance from a specific format.
*
* @param string $format Datetime format
* @param string $time
* @param DateTimeZone|string|false|null $tz
*
* @throws InvalidFormatException
*
* @return static|false
*/
public static function rawCreateFromFormat($format, $time, $tz = null)
{
// 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);
}
// First attempt to create an instance, so that error messages are based on the unmodified format.
$date = self::createFromFormatAndTimezone($format, $time, $tz);
$lastErrors = parent::getLastErrors();
/** @var \Carbon\CarbonImmutable|\Carbon\Carbon|null $mock */
$mock = static::getMockedTestNow($tz);
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 ($tz === null && !preg_match("/{$nonEscaped}[eOPT]/", $nonIgnored)) {
$tz = clone $mock->getTimezone();
}
// Set microseconds to zero to match behavior of DateTime::createFromFormat()
// See https://bugs.php.net/bug.php?id=74332
$mock = $mock->copy()->microsecond(0);
// Prepend mock datetime only if the format does not contain non escaped unix epoch reset flag.
if (!preg_match("/{$nonEscaped}[!|]/", $format)) {
$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, $tz);
}
if ($date instanceof DateTimeInterface) {
$instance = static::instance($date);
$instance::setLastErrors($lastErrors);
return $instance;
}
if (static::isStrictModeEnabled()) {
throw new InvalidFormatException(implode(PHP_EOL, $lastErrors['errors']));
}
return false;
}
/**
* Create a Carbon instance from a specific format.
*
* @param string $format Datetime format
* @param string $time
* @param DateTimeZone|string|false|null $tz
*
* @throws InvalidFormatException
*
* @return static|false
*/
public static function createFromFormat($format, $time, $tz = null)
{
$function = static::$createFromFormatFunction;
if (!$function) {
return static::rawCreateFromFormat($format, $time, $tz);
}
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|false|null $tz 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 \Symfony\Component\Translation\TranslatorInterface $translator optional custom translator to use for macro-formats
*
* @throws InvalidFormatException
*
* @return static|false
*/
public static function createFromIsoFormat($format, $time, $tz = null, $locale = 'en', $translator = null)
{
$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 ?: Translator::get($locale);
$formats = [
'LT' => static::getTranslationMessageWith($translator, 'formats.LT', $locale, 'h:mm A'),
'LTS' => static::getTranslationMessageWith($translator, 'formats.LTS', $locale, 'h:mm:ss A'),
'L' => static::getTranslationMessageWith($translator, 'formats.L', $locale, 'MM/DD/YYYY'),
'LL' => static::getTranslationMessageWith($translator, 'formats.LL', $locale, 'MMMM D, YYYY'),
'LLL' => static::getTranslationMessageWith($translator, 'formats.LLL', $locale, 'MMMM D, YYYY h:mm A'),
'LLLL' => static::getTranslationMessageWith($translator, 'formats.LLLL', $locale, 'dddd, MMMM D, YYYY h:mm A'),
];
}
return $formats[$code] ?? preg_replace_callback(
'/MMMM|MM|DD|dddd/',
function ($code) {
return 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, $tz);
}
/**
* 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|false|null $tz
*
* @throws InvalidFormatException
*
* @return static|false
*/
public static function createFromLocaleFormat($format, $locale, $time, $tz = null)
{
return static::rawCreateFromFormat($format, static::translateTimeString($time, $locale, 'en'), $tz);
}
/**
* 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|false|null $tz
*
* @throws InvalidFormatException
*
* @return static|false
*/
public static function createFromLocaleIsoFormat($format, $locale, $time, $tz = null)
{
$time = static::translateTimeString($time, $locale, 'en', CarbonInterface::TRANSLATE_MONTHS | CarbonInterface::TRANSLATE_DAYS | CarbonInterface::TRANSLATE_MERIDIEM);
return static::createFromIsoFormat($format, $time, $tz, $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)
{
if ($var instanceof DateTimeInterface) {
return static::instance($var);
}
$date = null;
if (\is_string($var)) {
$var = trim($var);
if (!preg_match('/^P[0-9T]/', $var) &&
!preg_match('/^R[0-9]/', $var) &&
preg_match('/[a-z0-9]/i', $var)
) {
$date = static::parse($var);
}
}
return $date;
}
/**
* Set last errors.
*
* @param array $lastErrors
*
* @return void
*/
private static function setLastErrors(array $lastErrors)
{
static::$lastErrors = $lastErrors;
}
/**
* {@inheritdoc}
*/
public static function getLastErrors()
{
return static::$lastErrors;
}
}
<?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* 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\InvalidTypeException;
use Carbon\Exceptions\UnknownGetterException;
use Carbon\Exceptions\UnknownMethodException;
use Carbon\Exceptions\UnknownSetterException;
use Carbon\Exceptions\UnknownUnitException;
use Closure;
use DateInterval;
use DatePeriod;
use DateTime;
use DateTimeInterface;
use DateTimeZone;
use InvalidArgumentException;
use ReflectionException;
use Throwable;
/**
* A simple API extension for DateTime.
*
* <autodoc generated by `composer phpdoc`>
*
* @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|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 string $localeDayOfWeek the day of week in current locale LC_TIME
* @property string $shortLocaleDayOfWeek the abbreviated day of week in current locale LC_TIME
* @property string $localeMonth the month in current locale LC_TIME
* @property string $shortLocaleMonth the abbreviated month in current locale LC_TIME
* @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 $dayOfYear 1 through 366
* @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-read int $dayOfWeek 0 (for Sunday) through 6 (for Saturday)
* @property-read int $dayOfWeekIso 1 (for Monday) through 7 (for Sunday)
* @property-read int $weekOfYear ISO-8601 week number of year, weeks starting on Monday
* @property-read int $daysInMonth number of days in the given month
* @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 $weeksInYear 51 through 53
* @property-read int $isoWeeksInYear 51 through 53
* @property-read int $weekOfMonth 1 through 5
* @property-read int $weekNumberInMonth 1 through 5
* @property-read int $firstWeekDay 0 through 6
* @property-read int $lastWeekDay 0 through 6
* @property-read int $daysInYear 365 or 366
* @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
*
* @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(Carbon|DateTimeInterface|string|null $date = null) 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 isSameWeek(Carbon|DateTimeInterface|string|null $date = null) 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(Carbon|DateTimeInterface|string|null $date = null) 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(Carbon|DateTimeInterface|string|null $date = null) 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(Carbon|DateTimeInterface|string|null $date = null) 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(Carbon|DateTimeInterface|string|null $date = null) 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 isSameMicro(Carbon|DateTimeInterface|string|null $date = null) 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(Carbon|DateTimeInterface|string|null $date = null) 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 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 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 bool isSameDecade(Carbon|DateTimeInterface|string|null $date = null) 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(Carbon|DateTimeInterface|string|null $date = null) 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(Carbon|DateTimeInterface|string|null $date = null) 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 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(int $value) Set current instance month to the given value.
* @method CarbonInterface month(int $value) Set current instance month to the given value.
* @method CarbonInterface setMonths(int $value) Set current instance month to the given value.
* @method CarbonInterface setMonth(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 CarbonInterface setMicrosecond(int $value) Set current instance microsecond to the given value.
* @method CarbonInterface addYears(int $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 $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 addRealMicros(int $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface addRealMicro() Add one microsecond to the instance (using timestamp).
* @method CarbonInterface subRealMicros(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface subRealMicro() Sub one microsecond to the instance (using timestamp).
* @method CarbonPeriod microsUntil($endDate = null, int $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 CarbonInterface addRealMicroseconds(int $value = 1) Add microseconds (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface addRealMicrosecond() Add one microsecond to the instance (using timestamp).
* @method CarbonInterface subRealMicroseconds(int $value = 1) Sub microseconds (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface subRealMicrosecond() Sub one microsecond to the instance (using timestamp).
* @method CarbonPeriod microsecondsUntil($endDate = null, int $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 CarbonInterface addRealMillis(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface addRealMilli() Add one millisecond to the instance (using timestamp).
* @method CarbonInterface subRealMillis(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface subRealMilli() Sub one millisecond to the instance (using timestamp).
* @method CarbonPeriod millisUntil($endDate = null, int $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 CarbonInterface addRealMilliseconds(int $value = 1) Add milliseconds (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface addRealMillisecond() Add one millisecond to the instance (using timestamp).
* @method CarbonInterface subRealMilliseconds(int $value = 1) Sub milliseconds (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface subRealMillisecond() Sub one millisecond to the instance (using timestamp).
* @method CarbonPeriod millisecondsUntil($endDate = null, int $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 CarbonInterface addRealSeconds(int $value = 1) Add seconds (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface addRealSecond() Add one second to the instance (using timestamp).
* @method CarbonInterface subRealSeconds(int $value = 1) Sub seconds (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface subRealSecond() Sub one second to the instance (using timestamp).
* @method CarbonPeriod secondsUntil($endDate = null, int $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 CarbonInterface addRealMinutes(int $value = 1) Add minutes (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface addRealMinute() Add one minute to the instance (using timestamp).
* @method CarbonInterface subRealMinutes(int $value = 1) Sub minutes (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface subRealMinute() Sub one minute to the instance (using timestamp).
* @method CarbonPeriod minutesUntil($endDate = null, int $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 CarbonInterface addRealHours(int $value = 1) Add hours (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface addRealHour() Add one hour to the instance (using timestamp).
* @method CarbonInterface subRealHours(int $value = 1) Sub hours (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface subRealHour() Sub one hour to the instance (using timestamp).
* @method CarbonPeriod hoursUntil($endDate = null, int $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 CarbonInterface addRealDays(int $value = 1) Add days (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface addRealDay() Add one day to the instance (using timestamp).
* @method CarbonInterface subRealDays(int $value = 1) Sub days (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface subRealDay() Sub one day to the instance (using timestamp).
* @method CarbonPeriod daysUntil($endDate = null, int $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 CarbonInterface addRealWeeks(int $value = 1) Add weeks (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface addRealWeek() Add one week to the instance (using timestamp).
* @method CarbonInterface subRealWeeks(int $value = 1) Sub weeks (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface subRealWeek() Sub one week to the instance (using timestamp).
* @method CarbonPeriod weeksUntil($endDate = null, int $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 CarbonInterface addRealMonths(int $value = 1) Add months (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface addRealMonth() Add one month to the instance (using timestamp).
* @method CarbonInterface subRealMonths(int $value = 1) Sub months (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface subRealMonth() Sub one month to the instance (using timestamp).
* @method CarbonPeriod monthsUntil($endDate = null, int $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 CarbonInterface addRealQuarters(int $value = 1) Add quarters (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface addRealQuarter() Add one quarter to the instance (using timestamp).
* @method CarbonInterface subRealQuarters(int $value = 1) Sub quarters (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface subRealQuarter() Sub one quarter to the instance (using timestamp).
* @method CarbonPeriod quartersUntil($endDate = null, int $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 CarbonInterface addRealYears(int $value = 1) Add years (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface addRealYear() Add one year to the instance (using timestamp).
* @method CarbonInterface subRealYears(int $value = 1) Sub years (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface subRealYear() Sub one year to the instance (using timestamp).
* @method CarbonPeriod yearsUntil($endDate = null, int $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 CarbonInterface addRealDecades(int $value = 1) Add decades (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface addRealDecade() Add one decade to the instance (using timestamp).
* @method CarbonInterface subRealDecades(int $value = 1) Sub decades (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface subRealDecade() Sub one decade to the instance (using timestamp).
* @method CarbonPeriod decadesUntil($endDate = null, int $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 CarbonInterface addRealCenturies(int $value = 1) Add centuries (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface addRealCentury() Add one century to the instance (using timestamp).
* @method CarbonInterface subRealCenturies(int $value = 1) Sub centuries (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface subRealCentury() Sub one century to the instance (using timestamp).
* @method CarbonPeriod centuriesUntil($endDate = null, int $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 CarbonInterface addRealMillennia(int $value = 1) Add millennia (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface addRealMillennium() Add one millennium to the instance (using timestamp).
* @method CarbonInterface subRealMillennia(int $value = 1) Sub millennia (the $value count passed in) to the instance (using timestamp).
* @method CarbonInterface subRealMillennium() Sub one millennium to the instance (using timestamp).
* @method CarbonPeriod millenniaUntil($endDate = null, int $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 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.)
*
* </autodoc>
*/
trait Date
{
use Boundaries;
use Comparison;
use Converter;
use Creator;
use Difference;
use Macro;
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',
];
/**
* Will UTF8 encoding be used to print localized date/time ?
*
* @var bool
*/
protected static $utf8 = false;
/**
* 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|null $object original value to get CarbonTimeZone from it.
* @param DateTimeZone|string|int|null $objectDump dump of the object for error messages.
*
* @throws InvalidTimeZoneException
*
* @return CarbonTimeZone|false
*/
protected static function safeCreateDateTimeZone($object, $objectDump = null)
{
return CarbonTimeZone::instance($object, $objectDump);
}
/**
* Get the TimeZone associated with the Carbon instance (as CarbonTimeZone).
*
* @return CarbonTimeZone
*
* @link http://php.net/manual/en/datetime.gettimezone.php
*/
public function getTimezone()
{
return CarbonTimeZone::instance(parent::getTimezone());
}
/**
* List of minimum and maximums for each unit.
*
* @return array
*/
protected static function getRangesByUnit()
{
return [
// @call roundUnit
'year' => [1, 9999],
// @call roundUnit
'month' => [1, static::MONTHS_PER_YEAR],
// @call roundUnit
'day' => [1, 31],
// @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;
}
/**
* Returns a present instance in the same timezone.
*
* @return static
*/
public function nowWithSameTz()
{
return static::now($this->getTimezone());
}
/**
* Throws an exception if the given object is not a DateTime and does not implement DateTimeInterface.
*
* @param mixed $date
* @param string|array $other
*
* @throws InvalidTypeException
*/
protected static function expectDateTime($date, $other = [])
{
$message = 'Expected ';
foreach ((array) $other as $expect) {
$message .= "$expect, ";
}
if (!$date instanceof DateTime && !$date instanceof DateTimeInterface) {
throw new InvalidTypeException(
$message.'DateTime or DateTimeInterface, '.
(\is_object($date) ? \get_class($date) : \gettype($date)).' given'
);
}
}
/**
* 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|DateTimeInterface|string|null $date
*
* @return static
*/
protected function resolveCarbon($date = null)
{
if (!$date) {
return $this->nowWithSameTz();
}
if (\is_string($date)) {
return static::parse($date, $this->getTimezone());
}
static::expectDateTime($date, ['null', 'string']);
return $date instanceof self ? $date : static::instance($date);
}
/**
* 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->copy()->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
*
* @param string $name
*
* @throws UnknownGetterException
*
* @return string|int|bool|DateTimeZone|null
*/
public function __get($name)
{
return $this->get($name);
}
/**
* Get a part of the Carbon object
*
* @param string $name
*
* @throws UnknownGetterException
*
* @return string|int|bool|DateTimeZone|null
*/
public function get($name)
{
static $formats = [
// @property int
'year' => 'Y',
// @property int
'yearIso' => 'o',
// @property int
// @call isSameUnit
'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-read int 0 (for Sunday) through 6 (for Saturday)
'dayOfWeek' => 'w',
// @property-read int 1 (for Monday) through 7 (for Sunday)
'dayOfWeekIso' => 'N',
// @property-read 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 string the day of week in current locale LC_TIME
'localeDayOfWeek' => '%A',
// @property string the abbreviated day of week in current locale LC_TIME
'shortLocaleDayOfWeek' => '%a',
// @property string the month in current locale LC_TIME
'localeMonth' => '%B',
// @property string the abbreviated month in current locale LC_TIME
'shortLocaleMonth' => '%b',
// @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]):
$format = $formats[$name];
$method = substr($format, 0, 1) === '%' ? 'formatLocalized' : 'rawFormat';
$value = $this->$method($format);
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($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 (int) $this->weeksInYear();
// @property-read int 51 through 53
case $name === 'isoWeeksInYear':
return (int) $this->isoWeeksInYear();
// @property-read 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->copy()->startOfMonth()->dayOfWeekIso - 1) / static::DAYS_PER_WEEK);
// @property-read int 0 through 6
case $name === 'firstWeekDay':
return $this->localTranslator ? ($this->getTranslationMessage('first_day_of_week') ?? 0) : static::getWeekStartsAt();
// @property-read int 0 through 6
case $name === 'lastWeekDay':
return $this->localTranslator ? (($this->getTranslationMessage('first_day_of_week') ?? 0) + static::DAYS_PER_WEEK - 1) % static::DAYS_PER_WEEK : static::getWeekEndsAt();
// @property int 1 through 366
case $name === 'dayOfYear':
return 1 + \intval($this->rawFormat('z'));
// @property-read int 365 or 366
case $name === 'daysInYear':
return $this->isLeapYear() ? 366 : 365;
// @property int does a diffInYears() with default parameters
case $name === 'age':
return $this->diffInYears();
// @property-read int the quarter of this instance, 1 - 4
// @call isSameUnit
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->copy()->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 CarbonTimeZone $timezone the current timezone
// @property CarbonTimeZone $tz alias of $timezone
case $name === 'timezone' || $name === 'tz':
return CarbonTimeZone::instance($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();
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 $e) {
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
*
* @param string|array $name
* @param string|int|DateTimeZone $value
*
* @throws ImmutableException|UnknownSetterException
*
* @return $this
*/
public function set($name, $value = null)
{
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;
}
switch ($name) {
case 'milliseconds':
case 'millisecond':
case 'milli':
case 'microseconds':
case 'microsecond':
case 'micro':
if (substr($name, 0, 5) === '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 = $value;
$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 '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:
$macro = $this->getLocalMacro('set'.ucfirst($name));
if ($macro) {
$this->executeCallableWithContext($macro, $value);
break;
}
if ($this->localStrictModeEnabled ?? static::isStrictModeEnabled()) {
throw new UnknownSetterException($name);
}
$this->$name = $value;
}
return $this;
}
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);
}
/**
* 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
*
* @return string
*/
public function getTranslatedDayName($context = null, $keySuffix = '', $defaultValue = null)
{
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
*
* @return string
*/
public function getTranslatedShortDayName($context = null)
{
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
*
* @return string
*/
public function getTranslatedMinDayName($context = null)
{
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
*
* @return string
*/
public function getTranslatedMonthName($context = null, $keySuffix = '', $defaultValue = null)
{
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
*
* @return string
*/
public function getTranslatedShortMonthName($context = null)
{
return $this->getTranslatedMonthName($context, '_short', $this->shortEnglishMonth);
}
/**
* Get/set the day of year.
*
* @param int|null $value new value for day of year if using as setter.
*
* @return static|int
*/
public function dayOfYear($value = null)
{
$dayOfYear = $this->dayOfYear;
return \is_null($value) ? $dayOfYear : $this->addDays($value - $dayOfYear);
}
/**
* Get/set the weekday from 0 (Sunday) to 6 (Saturday).
*
* @param int|null $value new value for weekday if using as setter.
*
* @return static|int
*/
public function weekday($value = null)
{
$dayOfWeek = ($this->dayOfWeek + 7 - \intval($this->getTranslationMessage('first_day_of_week') ?? 0)) % 7;
return \is_null($value) ? $dayOfWeek : $this->addDays($value - $dayOfWeek);
}
/**
* Get/set the ISO weekday from 1 (Monday) to 7 (Sunday).
*
* @param int|null $value new value for weekday if using as setter.
*
* @return static|int
*/
public function isoWeekday($value = null)
{
$dayOfWeekIso = $this->dayOfWeekIso;
return \is_null($value) ? $dayOfWeekIso : $this->addDays($value - $dayOfWeekIso);
}
/**
* 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
*
* @return static
*/
public function setUnitNoOverflow($valueUnit, $value, $overflowUnit)
{
try {
$original = $this->copy();
/** @var static $date */
$date = $this->$valueUnit($value);
$end = $original->copy()->endOf($overflowUnit);
$start = $original->copy()->startOf($overflowUnit);
if ($date < $start) {
$date = $date->setDateTimeFrom($start);
} elseif ($date > $end) {
$date = $date->setDateTimeFrom($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
*
* @return static
*/
public function addUnitNoOverflow($valueUnit, $value, $overflowUnit)
{
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
*
* @return static
*/
public function subUnitNoOverflow($valueUnit, $value, $overflowUnit)
{
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.
*
* @param int|null $minuteOffset
*
* @return int|static
*/
public function utcOffset(int $minuteOffset = null)
{
if (\func_num_args() < 1) {
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
*
* @param int $year
* @param int $month
* @param int $day
*
* @return static
*/
public function setDate($year, $month, $day)
{
return parent::setDate((int) $year, (int) $month, (int) $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
*
* @param int $year
* @param int $week
* @param int $day
*
* @return static
*/
public function setISODate($year, $week, $day = 1)
{
return parent::setISODate((int) $year, (int) $week, (int) $day);
}
/**
* Set the date and time all together.
*
* @param int $year
* @param int $month
* @param int $day
* @param int $hour
* @param int $minute
* @param int $second
* @param int $microseconds
*
* @return static
*/
public function setDateTime($year, $month, $day, $hour, $minute, $second = 0, $microseconds = 0)
{
return $this->setDate($year, $month, $day)->setTime((int) $hour, (int) $minute, (int) $second, (int) $microseconds);
}
/**
* Resets the current time of the DateTime object to a different time.
*
* @see https://php.net/manual/en/datetime.settime.php
*
* @param int $hour
* @param int $minute
* @param int $second
* @param int $microseconds
*
* @return static
*/
public function setTime($hour, $minute, $second = 0, $microseconds = 0)
{
return parent::setTime((int) $hour, (int) $minute, (int) $second, (int) $microseconds);
}
/**
* Set the instance's timestamp.
*
* Timestamp input can be given as int, float or a string containing one or more numbers.
*
* @param float|int|string $unixTimestamp
*
* @return static
*/
public function setTimestamp($unixTimestamp)
{
[$timestamp, $microseconds] = self::getIntegerAndDecimalParts($unixTimestamp);
return parent::setTimestamp((int) $timestamp)->setMicroseconds((int) $microseconds);
}
/**
* Set the time by time string.
*
* @param string $time
*
* @return static
*/
public function setTimeFromTimeString($time)
{
if (strpos($time, ':') === false) {
$time .= ':0';
}
return $this->modify($time);
}
/**
* @alias setTimezone
*
* @param DateTimeZone|string $value
*
* @return static
*/
public function timezone($value)
{
return $this->setTimezone($value);
}
/**
* Set the timezone or returns the timezone name if no arguments passed.
*
* @param DateTimeZone|string $value
*
* @return static|string
*/
public function tz($value = null)
{
if (\func_num_args() < 1) {
return $this->tzName;
}
return $this->setTimezone($value);
}
/**
* Set the instance's timezone from a string or object.
*
* @param DateTimeZone|string $value
*
* @return static
*/
public function setTimezone($value)
{
return parent::setTimezone(static::safeCreateDateTimeZone($value));
}
/**
* Set the instance's timezone from a string or object and add/subtract the offset difference.
*
* @param DateTimeZone|string $value
*
* @return static
*/
public function shiftTimezone($value)
{
$offset = $this->offset;
$date = $this->setTimezone($value);
return $date->addRealMicroseconds(($offset - $date->offset) * static::MICROSECONDS_PER_SECOND);
}
/**
* Set the instance's timezone to UTC.
*
* @return static
*/
public function utc()
{
return $this->setTimezone('UTC');
}
/**
* Set the year, month, and date for this instance to that of the passed instance.
*
* @param Carbon|DateTimeInterface $date now if null
*
* @return static
*/
public function setDateFrom($date = null)
{
$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.
*
* @param Carbon|DateTimeInterface $date now if null
*
* @return static
*/
public function setTimeFrom($date = null)
{
$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.
*
* @param Carbon|DateTimeInterface $date
*
* @return static
*/
public function setDateTimeFrom($date = null)
{
$date = $this->resolveCarbon($date);
return $this->modify($date->rawFormat('Y-m-d H:i:s.u'));
}
/**
* Get the days of the week
*
* @return array
*/
public static function getDays()
{
return static::$days;
}
///////////////////////////////////////////////////////////////////
/////////////////////// WEEK SPECIAL DAYS /////////////////////////
///////////////////////////////////////////////////////////////////
private static function getFirstDayOfWeek(): int
{
return (int) static::getTranslationMessageWith(
static::getTranslator(),
'first_day_of_week'
);
}
/**
* Get the first day of week
*
* @return int
*/
public static function getWeekStartsAt()
{
if (static::$weekStartsAt === static::WEEK_DAY_AUTO) {
return static::getFirstDayOfWeek();
}
return static::$weekStartsAt;
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* Use $weekEndsAt optional parameter instead when using endOfWeek method. You can also use the
* 'first_day_of_week' locale setting to change the start of week according to current locale
* selected and implicitly the end of week.
*
* Set the first day of week
*
* @param int|string $day week start day (or 'auto' to get the first day of week from Carbon::getLocale() culture).
*
* @return void
*/
public static function setWeekStartsAt($day)
{
static::$weekStartsAt = $day === static::WEEK_DAY_AUTO ? $day : max(0, (7 + $day) % 7);
}
/**
* Get the last day of week
*
* @return int
*/
public static function getWeekEndsAt()
{
if (static::$weekStartsAt === static::WEEK_DAY_AUTO) {
return (int) (static::DAYS_PER_WEEK - 1 + static::getFirstDayOfWeek()) % static::DAYS_PER_WEEK;
}
return static::$weekEndsAt;
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* Use $weekStartsAt optional parameter instead when using startOfWeek, floorWeek, ceilWeek
* or roundWeek method. You can also use the 'first_day_of_week' locale setting to change the
* start of week according to current locale selected and implicitly the end of week.
*
* Set the last day of week
*
* @param int|string $day week end day (or 'auto' to get the day before the first day of week
* from Carbon::getLocale() culture).
*
* @return void
*/
public static function setWeekEndsAt($day)
{
static::$weekEndsAt = $day === static::WEEK_DAY_AUTO ? $day : max(0, (7 + $day) % 7);
}
/**
* Get weekend days
*
* @return array
*/
public static function getWeekendDays()
{
return static::$weekendDays;
}
/**
* @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
*
* @param array $days
*
* @return void
*/
public static function setWeekendDays($days)
{
static::$weekendDays = $days;
}
/**
* Determine if a time string will produce a relative date.
*
* @param string $time
*
* @return bool true if time match a relative date, false if absolute or invalid time string
*/
public static function hasRelativeKeywords($time)
{
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 /////////////////////////
///////////////////////////////////////////////////////////////////
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather use UTF-8 language packages on every machine.
*
* Set if UTF8 will be used for localized date/time.
*
* @param bool $utf8
*/
public static function setUtf8($utf8)
{
static::$utf8 = $utf8;
}
/**
* Format the instance with the current locale. You can set the current
* locale using setlocale() http://php.net/setlocale.
*
* @param string $format
*
* @return string
*/
public function formatLocalized($format)
{
// Check for Windows to find and replace the %e modifier correctly.
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
$format = preg_replace('#(?<!%)((?:%%)*)%e#', '\1%#d', $format); // @codeCoverageIgnore
}
$formatted = strftime($format, strtotime($this->toDateTimeString()));
return static::$utf8 ? utf8_encode($formatted) : $formatted;
}
/**
* Returns list of locale formats for ISO formatting.
*
* @param string|null $locale current locale used if null
*
* @return array
*/
public function getIsoFormats($locale = null)
{
return [
'LT' => $this->getTranslationMessage('formats.LT', $locale, 'h:mm A'),
'LTS' => $this->getTranslationMessage('formats.LTS', $locale, 'h:mm:ss A'),
'L' => $this->getTranslationMessage('formats.L', $locale, 'MM/DD/YYYY'),
'LL' => $this->getTranslationMessage('formats.LL', $locale, 'MMMM D, YYYY'),
'LLL' => $this->getTranslationMessage('formats.LLL', $locale, 'MMMM D, YYYY h:mm A'),
'LLLL' => $this->getTranslationMessage('formats.LLLL', $locale, 'dddd, MMMM D, YYYY h:mm A'),
];
}
/**
* Returns list of calendar formats for ISO formatting.
*
* @param string|null $locale current locale used if null
*
* @return array
*/
public function getCalendarFormats($locale = null)
{
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.
*
* @return array
*/
public static function getIsoUnits()
{
static $units = null;
if ($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' => function (CarbonInterface $date, $originalFormat = null) {
return $date->getTranslatedMinDayName($originalFormat);
},
'ddd' => function (CarbonInterface $date, $originalFormat = null) {
return $date->getTranslatedShortDayName($originalFormat);
},
'dddd' => function (CarbonInterface $date, $originalFormat = null) {
return $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' => function (CarbonInterface $date) {
return \strval((string) floor($date->micro / 100000));
},
'SS' => function (CarbonInterface $date) {
return str_pad((string) floor($date->micro / 10000), 2, '0', STR_PAD_LEFT);
},
'SSS' => function (CarbonInterface $date) {
return str_pad((string) floor($date->micro / 1000), 3, '0', STR_PAD_LEFT);
},
'SSSS' => function (CarbonInterface $date) {
return str_pad((string) floor($date->micro / 100), 4, '0', STR_PAD_LEFT);
},
'SSSSS' => function (CarbonInterface $date) {
return str_pad((string) floor($date->micro / 10), 5, '0', STR_PAD_LEFT);
},
'SSSSSS' => ['getPaddedUnit', ['micro', 6]],
'SSSSSSS' => function (CarbonInterface $date) {
return str_pad((string) floor($date->micro * 10), 7, '0', STR_PAD_LEFT);
},
'SSSSSSSS' => function (CarbonInterface $date) {
return str_pad((string) floor($date->micro * 100), 8, '0', STR_PAD_LEFT);
},
'SSSSSSSSS' => function (CarbonInterface $date) {
return str_pad((string) floor($date->micro * 1000), 9, '0', STR_PAD_LEFT);
},
'M' => 'month',
'MM' => ['rawFormat', ['m']],
'MMM' => function (CarbonInterface $date, $originalFormat = null) {
$month = $date->getTranslatedShortMonthName($originalFormat);
$suffix = $date->getTranslationMessage('mmm_suffix');
if ($suffix && $month !== $date->monthName) {
$month .= $suffix;
}
return $month;
},
'MMMM' => function (CarbonInterface $date, $originalFormat = null) {
return $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' => function (CarbonInterface $date) {
return ($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)
*
* @return string
*/
public function getPaddedUnit($unit, $length = 2, $padString = '0', $padType = STR_PAD_LEFT)
{
return ($this->$unit < 0 ? '-' : '').str_pad((string) abs($this->$unit), $length, $padString, $padType);
}
/**
* Return a property with its ordinal.
*
* @param string $key
* @param string|null $period
*
* @return string
*/
public function ordinal(string $key, string $period = null): string
{
$number = $this->$key;
$result = $this->translate('ordinal', [
':number' => $number,
':period' => $period,
]);
return \strval($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.
*
* @return string
*/
public function meridiem(bool $isLower = false): string
{
$hour = $this->hour;
$index = $hour < 12 ? 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
*
* @return string
*/
public function getAltNumber(string $key): string
{
return $this->translateNumber(\strlen($key) > 1 ? $this->$key : $this->rawFormat('h'));
}
/**
* Format in the current language using ISO replacement patterns.
*
* @param string $format
* @param string|null $originalFormat provide context if a chunk has been passed alone
*
* @return string
*/
public function isoFormat(string $format, string $originalFormat = null): string
{
$result = '';
$length = mb_strlen($format);
$originalFormat = $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|[Ll]{1,4})/', $input, $match)) {
if ($formats === null) {
$formats = $this->getIsoFormats();
}
$code = $match[0];
$sequence = $formats[$code] ?? preg_replace_callback(
'/MMMM|MM|DD|dddd/',
function ($code) {
return 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 $e) {
$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("$sequence") - 1;
$length = mb_strlen($format);
$char = $sequence;
}
$result .= $char;
}
return $result;
}
/**
* List of replacements from date() format to isoFormat().
*
* @return array
*/
public static function getFormatsToIsoReplacements()
{
static $replacements = null;
if ($replacements === null) {
$replacements = [
'd' => true,
'D' => 'ddd',
'j' => true,
'l' => 'dddd',
'N' => true,
'S' => function ($date) {
$day = $date->rawFormat('j');
return str_replace("$day", '', $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,
];
}
return $replacements;
}
/**
* Format as ->format() do (using date replacements patterns from http://php.net/manual/fr/function.date.php)
* but translate words whenever possible (months, day names, etc.) using the current locale.
*
* @param string $format
*
* @return string
*/
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)
*
* @return string
*/
public function getOffsetString($separator = ':')
{
$second = $this->getOffset();
$symbol = $second < 0 ? '-' : '+';
$minute = abs($second) / static::SECONDS_PER_MINUTE;
$hour = str_pad((string) floor($minute / static::MINUTES_PER_HOUR), 2, '0', STR_PAD_LEFT);
$minute = str_pad((string) ($minute % static::MINUTES_PER_HOUR), 2, '0', STR_PAD_LEFT);
return "$symbol$hour$separator$minute";
}
protected static function executeStaticCallable($macro, ...$parameters)
{
return static::bindMacroContext(null, function () use (&$macro, &$parameters) {
if ($macro instanceof Closure) {
$boundMacro = @Closure::bind($macro, null, static::class);
return ($boundMacro ?: $macro)(...$parameters);
}
return $macro(...$parameters);
});
}
/**
* Dynamically handle calls to the class.
*
* @param string $method magic method name called
* @param array $parameters parameters list
*
* @throws BadMethodCallException
*
* @return mixed
*/
public static function __callStatic($method, $parameters)
{
if (!static::hasMacro($method)) {
foreach (static::getGenericMacros() as $callback) {
try {
return static::executeStaticCallable($callback, $method, ...$parameters);
} catch (BadMethodCallException $exception) {
continue;
}
}
if (static::isStrictModeEnabled()) {
throw new UnknownMethodException(sprintf('%s::%s', static::class, $method));
}
return null;
}
return static::executeStaticCallable(static::$globalMacros[$method], ...$parameters);
}
/**
* Set specified unit to new given value.
*
* @param string $unit year, month, day, hour, minute, second or microsecond
* @param int $value new value for given unit
*
* @return static
*/
public function setUnit($unit, $value = null)
{
$unit = static::singularUnit($unit);
$dateUnits = ['year', 'month', 'day'];
if (\in_array($unit, $dateUnits)) {
return $this->setDate(...array_map(function ($name) use ($unit, $value) {
return (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(function ($name) use ($unit, $value) {
return (int) ($name === $unit ? $value : $this->$name);
}, $units));
}
/**
* Returns standardized singular of a given singular/plural unit name (in English).
*
* @param string $unit
*
* @return string
*/
public static function singularUnit(string $unit): string
{
$unit = rtrim(mb_strtolower($unit), 's');
if ($unit === 'centurie') {
return 'century';
}
if ($unit === 'millennia') {
return 'millennium';
}
return $unit;
}
/**
* Returns standardized plural of a given singular/plural unit name (in English).
*
* @param string $unit
*
* @return string
*/
public static function pluralUnit(string $unit): string
{
$unit = rtrim(strtolower($unit), 's');
if ($unit === 'century') {
return 'centuries';
}
if ($unit === 'millennium' || $unit === 'millennia') {
return 'millennia';
}
return "${unit}s";
}
protected function executeCallable($macro, ...$parameters)
{
if ($macro instanceof Closure) {
$boundMacro = @$macro->bindTo($this, static::class) ?: @$macro->bindTo(null, static::class);
return ($boundMacro ?: $macro)(...$parameters);
}
return $macro(...$parameters);
}
protected function executeCallableWithContext($macro, ...$parameters)
{
return static::bindMacroContext($this, function () use (&$macro, &$parameters) {
return $this->executeCallable($macro, ...$parameters);
});
}
protected static function getGenericMacros()
{
foreach (static::$globalGenericMacros as $list) {
foreach ($list as $macro) {
yield $macro;
}
}
}
/**
* Dynamically handle calls to the class.
*
* @param string $method magic method name called
* @param array $parameters parameters list
*
* @throws UnknownMethodException|BadMethodCallException|ReflectionException|Throwable
*
* @return mixed
*/
public function __call($method, $parameters)
{
$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)DiffForHumans$/", $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);
}
$roundedValue = $this->callRoundMethod($method, $parameters);
if ($roundedValue !== null) {
return $roundedValue;
}
$unit = rtrim($method, 's');
if (substr($unit, 0, 2) === 'is') {
$word = substr($unit, 2);
if (\in_array($word, static::$days)) {
return $this->isDayOfWeek($word);
}
switch ($word) {
// @call is Check if the current instance has UTC timezone. (Both isUtc and isUTC cases are valid.)
case 'Utc':
case 'UTC':
return $this->utc;
// @call is Check if the current instance has non-UTC timezone.
case 'Local':
return $this->local;
// @call is Check if the current instance is a valid date.
case 'Valid':
return $this->year !== 0;
// @call is Check if the current instance is in a daylight saving time.
case 'DST':
return $this->dst;
}
}
$action = substr($unit, 0, 3);
$overflow = null;
if ($action === 'set') {
$unit = strtolower(substr($unit, 3));
}
if (\in_array($unit, static::$units)) {
return $this->setUnit($unit, ...$parameters);
}
if ($action === 'add' || $action === 'sub') {
$unit = substr($unit, 3);
if (substr($unit, 0, 4) === 'Real') {
$unit = static::singularUnit(substr($unit, 4));
return $this->{"${action}RealUnit"}($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, $parameters[0] ?? 1, $overflow);
}
$sixFirstLetters = substr($unit, 0, 6);
$factor = -1;
if ($sixFirstLetters === 'isLast') {
$sixFirstLetters = 'isNext';
$factor = 1;
}
if ($sixFirstLetters === 'isNext') {
$lowerUnit = strtolower(substr($unit, 6));
if (static::isModifiableUnit($lowerUnit)) {
return $this->copy()->addUnit($lowerUnit, $factor, false)->isSameUnit($lowerUnit, ...$parameters);
}
}
if ($sixFirstLetters === 'isSame') {
try {
return $this->isSameUnit(strtolower(substr($unit, 6)), ...$parameters);
} catch (BadComparisonUnitException $exception) {
// Try next
}
}
if (substr($unit, 0, 9) === 'isCurrent') {
try {
return $this->isCurrentUnit(strtolower(substr($unit, 9)));
} catch (BadComparisonUnitException | BadMethodCallException $exception) {
// Try next
}
}
if (substr($method, -5) === 'Until') {
try {
$unit = static::singularUnit(substr($method, 0, -5));
return $this->range($parameters[0] ?? $this, $parameters[1] ?? 1, $unit);
} catch (InvalidArgumentException $exception) {
// Try macros
}
}
return static::bindMacroContext($this, function () use (&$method, &$parameters) {
$macro = $this->getLocalMacro($method);
if (!$macro) {
foreach ([$this->localGenericMacros ?: [], static::getGenericMacros()] as $list) {
foreach ($list as $callback) {
try {
return $this->executeCallable($callback, $method, ...$parameters);
} catch (BadMethodCallException $exception) {
continue;
}
}
}
if ($this->localStrictModeEnabled ?? static::isStrictModeEnabled()) {
throw new UnknownMethodException($method);
}
return null;
}
return $this->executeCallable($macro, ...$parameters);
});
}
}
<?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* 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\Translator;
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)
* @method static Translator translator()
*/
trait Difference
{
/**
* @codeCoverageIgnore
*
* @param CarbonInterval $diff
*/
protected static function fixNegativeMicroseconds(CarbonInterval $diff)
{
if ($diff->s !== 0 || $diff->i !== 0 || $diff->h !== 0 || $diff->d !== 0 || $diff->m !== 0 || $diff->y !== 0) {
$diff->f = (round($diff->f * 1000000) + 1000000) / 1000000;
$diff->s--;
if ($diff->s < 0) {
$diff->s += 60;
$diff->i--;
if ($diff->i < 0) {
$diff->i += 60;
$diff->h--;
if ($diff->h < 0) {
$diff->h += 24;
$diff->d--;
if ($diff->d < 0) {
$diff->d += 30;
$diff->m--;
if ($diff->m < 0) {
$diff->m += 12;
$diff->y--;
}
}
}
}
}
return;
}
$diff->f *= -1;
$diff->invert();
}
/**
* @param DateInterval $diff
* @param bool $absolute
*
* @return CarbonInterval
*/
protected static function fixDiffInterval(DateInterval $diff, $absolute)
{
$diff = CarbonInterval::instance($diff);
// Work-around for https://bugs.php.net/bug.php?id=77145
// @codeCoverageIgnoreStart
if ($diff->f > 0 && $diff->y === -1 && $diff->m === 11 && $diff->d >= 27 && $diff->h === 23 && $diff->i === 59 && $diff->s === 59) {
$diff->y = 0;
$diff->m = 0;
$diff->d = 0;
$diff->h = 0;
$diff->i = 0;
$diff->s = 0;
$diff->f = (1000000 - round($diff->f * 1000000)) / 1000000;
$diff->invert();
} elseif ($diff->f < 0) {
static::fixNegativeMicroseconds($diff);
}
// @codeCoverageIgnoreEnd
if ($absolute && $diff->invert) {
$diff->invert();
}
return $diff;
}
/**
* Get the difference as a DateInterval instance.
* Return relative interval (negative if
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return DateInterval
*/
public function diff($date = null, $absolute = false)
{
return parent::diff($this->resolveCarbon($date), (bool) $absolute);
}
/**
* Get the difference as a CarbonInterval instance.
* Return absolute interval (always positive) unless you pass false to the second argument.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return CarbonInterval
*/
public function diffAsCarbonInterval($date = null, $absolute = true)
{
return static::fixDiffInterval($this->diff($this->resolveCarbon($date), $absolute), $absolute);
}
/**
* Get the difference in years
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInYears($date = null, $absolute = true)
{
return (int) $this->diff($this->resolveCarbon($date), $absolute)->format('%r%y');
}
/**
* Get the difference in quarters rounded down.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInQuarters($date = null, $absolute = true)
{
return (int) ($this->diffInMonths($date, $absolute) / static::MONTHS_PER_QUARTER);
}
/**
* Get the difference in months rounded down.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInMonths($date = null, $absolute = true)
{
$date = $this->resolveCarbon($date);
return $this->diffInYears($date, $absolute) * static::MONTHS_PER_YEAR + (int) $this->diff($date, $absolute)->format('%r%m');
}
/**
* Get the difference in weeks rounded down.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInWeeks($date = null, $absolute = true)
{
return (int) ($this->diffInDays($date, $absolute) / static::DAYS_PER_WEEK);
}
/**
* Get the difference in days rounded down.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInDays($date = null, $absolute = true)
{
return (int) $this->diff($this->resolveCarbon($date), $absolute)->format('%r%a');
}
/**
* Get the difference in days using a filter closure rounded down.
*
* @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, $absolute = true)
{
return $this->diffFiltered(CarbonInterval::day(), $callback, $date, $absolute);
}
/**
* Get the difference in hours using a filter closure rounded down.
*
* @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, $absolute = true)
{
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, $absolute = true)
{
$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 rounded down.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInWeekdays($date = null, $absolute = true)
{
return $this->diffInDaysFiltered(function (CarbonInterface $date) {
return $date->isWeekday();
}, $date, $absolute);
}
/**
* Get the difference in weekend days using a filter rounded down.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInWeekendDays($date = null, $absolute = true)
{
return $this->diffInDaysFiltered(function (CarbonInterface $date) {
return $date->isWeekend();
}, $date, $absolute);
}
/**
* Get the difference in hours rounded down.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInHours($date = null, $absolute = true)
{
return (int) ($this->diffInSeconds($date, $absolute) / static::SECONDS_PER_MINUTE / static::MINUTES_PER_HOUR);
}
/**
* Get the difference in hours rounded down using timestamps.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInRealHours($date = null, $absolute = true)
{
return (int) ($this->diffInRealSeconds($date, $absolute) / static::SECONDS_PER_MINUTE / static::MINUTES_PER_HOUR);
}
/**
* Get the difference in minutes rounded down.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInMinutes($date = null, $absolute = true)
{
return (int) ($this->diffInSeconds($date, $absolute) / static::SECONDS_PER_MINUTE);
}
/**
* Get the difference in minutes rounded down using timestamps.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInRealMinutes($date = null, $absolute = true)
{
return (int) ($this->diffInRealSeconds($date, $absolute) / static::SECONDS_PER_MINUTE);
}
/**
* Get the difference in seconds rounded down.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInSeconds($date = null, $absolute = true)
{
$diff = $this->diff($date);
if ($diff->days === 0) {
$diff = static::fixDiffInterval($diff, $absolute);
}
$value = (((($diff->m || $diff->y ? $diff->days : $diff->d) * static::HOURS_PER_DAY) +
$diff->h) * static::MINUTES_PER_HOUR +
$diff->i) * static::SECONDS_PER_MINUTE +
$diff->s;
return $absolute || !$diff->invert ? $value : -$value;
}
/**
* Get the difference in microseconds.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInMicroseconds($date = null, $absolute = true)
{
$diff = $this->diff($date);
$value = (int) round(((((($diff->m || $diff->y ? $diff->days : $diff->d) * static::HOURS_PER_DAY) +
$diff->h) * static::MINUTES_PER_HOUR +
$diff->i) * static::SECONDS_PER_MINUTE +
($diff->f + $diff->s)) * static::MICROSECONDS_PER_SECOND);
return $absolute || !$diff->invert ? $value : -$value;
}
/**
* Get the difference in milliseconds rounded down.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInMilliseconds($date = null, $absolute = true)
{
return (int) ($this->diffInMicroseconds($date, $absolute) / static::MICROSECONDS_PER_MILLISECOND);
}
/**
* Get the difference in seconds using timestamps.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInRealSeconds($date = null, $absolute = true)
{
/** @var CarbonInterface $date */
$date = $this->resolveCarbon($date);
$value = $date->getTimestamp() - $this->getTimestamp();
return $absolute ? abs($value) : $value;
}
/**
* Get the difference in microseconds using timestamps.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInRealMicroseconds($date = null, $absolute = true)
{
/** @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 rounded down using timestamps.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return int
*/
public function diffInRealMilliseconds($date = null, $absolute = true)
{
return (int) ($this->diffInRealMicroseconds($date, $absolute) / static::MICROSECONDS_PER_MILLISECOND);
}
/**
* Get the difference in seconds as float (microsecond-precision).
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function floatDiffInSeconds($date = null, $absolute = true)
{
return $this->diffInMicroseconds($date, $absolute) / static::MICROSECONDS_PER_SECOND;
}
/**
* Get the difference in minutes as float (microsecond-precision).
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function floatDiffInMinutes($date = null, $absolute = true)
{
return $this->floatDiffInSeconds($date, $absolute) / static::SECONDS_PER_MINUTE;
}
/**
* Get the difference in hours as float (microsecond-precision).
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function floatDiffInHours($date = null, $absolute = true)
{
return $this->floatDiffInMinutes($date, $absolute) / static::MINUTES_PER_HOUR;
}
/**
* Get the difference in days as float (microsecond-precision).
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function floatDiffInDays($date = null, $absolute = true)
{
$hoursDiff = $this->floatDiffInHours($date, $absolute);
$interval = $this->diff($date, $absolute);
if ($interval->y === 0 && $interval->m === 0 && $interval->d === 0) {
return $hoursDiff / static::HOURS_PER_DAY;
}
$daysDiff = (int) $interval->format('%r%a');
return $daysDiff + fmod($hoursDiff, static::HOURS_PER_DAY) / static::HOURS_PER_DAY;
}
/**
* Get the difference in weeks as float (microsecond-precision).
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function floatDiffInWeeks($date = null, $absolute = true)
{
return $this->floatDiffInDays($date, $absolute) / static::DAYS_PER_WEEK;
}
/**
* Get the difference in months as float (microsecond-precision).
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function floatDiffInMonths($date = null, $absolute = true)
{
$start = $this;
$end = $this->resolveCarbon($date);
$ascending = ($start <= $end);
$sign = $absolute || $ascending ? 1 : -1;
if (!$ascending) {
[$start, $end] = [$end, $start];
}
$monthsDiff = $start->diffInMonths($end);
/** @var Carbon|CarbonImmutable $floorEnd */
$floorEnd = $start->copy()->addMonths($monthsDiff);
if ($floorEnd >= $end) {
return $sign * $monthsDiff;
}
/** @var Carbon|CarbonImmutable $startOfMonthAfterFloorEnd */
$startOfMonthAfterFloorEnd = $floorEnd->copy()->addMonth()->startOfMonth();
if ($startOfMonthAfterFloorEnd > $end) {
return $sign * ($monthsDiff + $floorEnd->floatDiffInDays($end) / $floorEnd->daysInMonth);
}
return $sign * ($monthsDiff + $floorEnd->floatDiffInDays($startOfMonthAfterFloorEnd) / $floorEnd->daysInMonth + $startOfMonthAfterFloorEnd->floatDiffInDays($end) / $end->daysInMonth);
}
/**
* Get the difference in year as float (microsecond-precision).
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function floatDiffInYears($date = null, $absolute = true)
{
$start = $this;
$end = $this->resolveCarbon($date);
$ascending = ($start <= $end);
$sign = $absolute || $ascending ? 1 : -1;
if (!$ascending) {
[$start, $end] = [$end, $start];
}
$yearsDiff = $start->diffInYears($end);
/** @var Carbon|CarbonImmutable $floorEnd */
$floorEnd = $start->copy()->addYears($yearsDiff);
if ($floorEnd >= $end) {
return $sign * $yearsDiff;
}
/** @var Carbon|CarbonImmutable $startOfYearAfterFloorEnd */
$startOfYearAfterFloorEnd = $floorEnd->copy()->addYear()->startOfYear();
if ($startOfYearAfterFloorEnd > $end) {
return $sign * ($yearsDiff + $floorEnd->floatDiffInDays($end) / $floorEnd->daysInYear);
}
return $sign * ($yearsDiff + $floorEnd->floatDiffInDays($startOfYearAfterFloorEnd) / $floorEnd->daysInYear + $startOfYearAfterFloorEnd->floatDiffInDays($end) / $end->daysInYear);
}
/**
* Get the difference in seconds as float (microsecond-precision) using timestamps.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function floatDiffInRealSeconds($date = null, $absolute = true)
{
return $this->diffInRealMicroseconds($date, $absolute) / static::MICROSECONDS_PER_SECOND;
}
/**
* Get the difference in minutes as float (microsecond-precision) using timestamps.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function floatDiffInRealMinutes($date = null, $absolute = true)
{
return $this->floatDiffInRealSeconds($date, $absolute) / static::SECONDS_PER_MINUTE;
}
/**
* Get the difference in hours as float (microsecond-precision) using timestamps.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function floatDiffInRealHours($date = null, $absolute = true)
{
return $this->floatDiffInRealMinutes($date, $absolute) / static::MINUTES_PER_HOUR;
}
/**
* Get the difference in days as float (microsecond-precision).
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function floatDiffInRealDays($date = null, $absolute = true)
{
$date = $this->resolveCarbon($date)->utc();
$utc = $this->copy()->utc();
$hoursDiff = $utc->floatDiffInRealHours($date, $absolute);
return ($hoursDiff < 0 ? -1 : 1) * $utc->diffInDays($date) + fmod($hoursDiff, static::HOURS_PER_DAY) / static::HOURS_PER_DAY;
}
/**
* Get the difference in weeks as float (microsecond-precision).
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function floatDiffInRealWeeks($date = null, $absolute = true)
{
return $this->floatDiffInRealDays($date, $absolute) / static::DAYS_PER_WEEK;
}
/**
* Get the difference in months as float (microsecond-precision) using timestamps.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function floatDiffInRealMonths($date = null, $absolute = true)
{
$start = $this;
$end = $this->resolveCarbon($date);
$ascending = ($start <= $end);
$sign = $absolute || $ascending ? 1 : -1;
if (!$ascending) {
[$start, $end] = [$end, $start];
}
$monthsDiff = $start->diffInMonths($end);
/** @var Carbon|CarbonImmutable $floorEnd */
$floorEnd = $start->copy()->addMonths($monthsDiff);
if ($floorEnd >= $end) {
return $sign * $monthsDiff;
}
/** @var Carbon|CarbonImmutable $startOfMonthAfterFloorEnd */
$startOfMonthAfterFloorEnd = $floorEnd->copy()->addMonth()->startOfMonth();
if ($startOfMonthAfterFloorEnd > $end) {
return $sign * ($monthsDiff + $floorEnd->floatDiffInRealDays($end) / $floorEnd->daysInMonth);
}
return $sign * ($monthsDiff + $floorEnd->floatDiffInRealDays($startOfMonthAfterFloorEnd) / $floorEnd->daysInMonth + $startOfMonthAfterFloorEnd->floatDiffInRealDays($end) / $end->daysInMonth);
}
/**
* Get the difference in year as float (microsecond-precision) using timestamps.
*
* @param \Carbon\CarbonInterface|\DateTimeInterface|string|null $date
* @param bool $absolute Get the absolute of the difference
*
* @return float
*/
public function floatDiffInRealYears($date = null, $absolute = true)
{
$start = $this;
$end = $this->resolveCarbon($date);
$ascending = ($start <= $end);
$sign = $absolute || $ascending ? 1 : -1;
if (!$ascending) {
[$start, $end] = [$end, $start];
}
$yearsDiff = $start->diffInYears($end);
/** @var Carbon|CarbonImmutable $floorEnd */
$floorEnd = $start->copy()->addYears($yearsDiff);
if ($floorEnd >= $end) {
return $sign * $yearsDiff;
}
/** @var Carbon|CarbonImmutable $startOfYearAfterFloorEnd */
$startOfYearAfterFloorEnd = $floorEnd->copy()->addYear()->startOfYear();
if ($startOfYearAfterFloorEnd > $end) {
return $sign * ($yearsDiff + $floorEnd->floatDiffInRealDays($end) / $floorEnd->daysInYear);
}
return $sign * ($yearsDiff + $floorEnd->floatDiffInRealDays($startOfYearAfterFloorEnd) / $floorEnd->daysInYear + $startOfYearAfterFloorEnd->floatDiffInRealDays($end) / $end->daysInYear);
}
/**
* The number of seconds since midnight.
*
* @return int
*/
public function secondsSinceMidnight()
{
return $this->diffInSeconds($this->copy()->startOfDay());
}
/**
* The number of seconds until 23:59:59.
*
* @return int
*/
public function secondsUntilEndOfDay()
{
return $this->diffInSeconds($this->copy()->endOfDay());
}
/**
* 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)
* - '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 diffForHumans($other = null, $syntax = null, $short = false, $parts = 1, $options = null)
{
/* @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 === null ? static::DIFF_RELATIVE_AUTO : $intSyntax);
$intSyntax = $intSyntax === static::DIFF_RELATIVE_AUTO && $other === null ? static::DIFF_RELATIVE_TO_NOW : $intSyntax;
$parts = min(7, max(1, (int) $parts));
return $this->diffAsCarbonInterval($other, false)
->setLocalTranslator($this->getLocalTranslator())
->forHumans($syntax, (bool) $short, $parts, $options ?? $this->localHumanDiffOptions ?? static::getHumanDiffOptions());
}
/**
* @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 an other
* instance given (or now if null given).
*
* @return string
*/
public function timespan($other = null, $timezone = null)
{
if (!$other instanceof DateTimeInterface) {
$other = static::parse($other, $timezone);
}
return $this->diffForHumans($other, [
'join' => ', ',
'syntax' => CarbonInterface::DIFF_ABSOLUTE,
'options' => CarbonInterface::NO_ZERO_DIFF,
'parts' => -1,
]);
}
/**
* 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->copy()->startOfDay();
/** @var CarbonInterface $other */
$other = $this->resolveCarbon($referenceTime)->copy()->setTimezone($this->getTimezone())->startOfDay();
$diff = $other->diffInDays($current, false);
$format = $diff < -6 ? 'sameElse' : (
$diff < -1 ? 'lastWeek' : (
$diff < 0 ? 'lastDay' : (
$diff < 1 ? 'sameDay' : (
$diff < 2 ? 'nextDay' : (
$diff < 7 ? 'nextWeek' : 'sameElse'
)
)
)
)
);
$format = array_merge($this->getCalendarFormats(), $formats)[$format];
if ($format instanceof Closure) {
$format = $format($current, $other) ?? '';
}
return $this->isoFormat(\strval($format));
}
}
<?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Carbon\CarbonInterval;
use Carbon\Exceptions\InvalidIntervalException;
use DateInterval;
/**
* Trait to call rounding methods to interval or the interval of a period.
*/
trait IntervalRounding
{
protected function callRoundMethod(string $method, array $parameters)
{
$action = substr($method, 0, 4);
if ($action !== 'ceil') {
$action = substr($method, 0, 5);
}
if (\in_array($action, ['round', 'floor', 'ceil'])) {
return $this->{$action.'Unit'}(substr($method, \strlen($action)), ...$parameters);
}
return null;
}
protected function roundWith($precision, $function)
{
$unit = 'second';
if ($precision instanceof DateInterval) {
$precision = (string) CarbonInterval::instance($precision);
}
if (\is_string($precision) && preg_match('/^\s*(?<precision>\d+)?\s*(?<unit>\w+)(?<other>\W.*)?$/', $precision, $match)) {
if (trim($match['other'] ?? '') !== '') {
throw new InvalidIntervalException('Rounding is only possible with single unit intervals.');
}
$precision = (int) ($match['precision'] ?: 1);
$unit = $match['unit'];
}
return $this->roundUnit($unit, $precision, $function);
}
}
<?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* 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 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) {
return $carbonDate->setDateTimeFrom(($this->step)($carbonDate->copy(), $negated));
}
if ($negated) {
return $carbonDate->rawSub($this);
}
return $carbonDate->rawAdd($this);
}
/**
* Convert DateTimeImmutable instance to CarbonImmutable instance and DateTime instance to Carbon instance.
*
* @param DateTimeInterface $dateTime
*
* @return Carbon|CarbonImmutable
*/
private function resolveCarbon(DateTimeInterface $dateTime)
{
if ($dateTime instanceof DateTimeImmutable) {
return CarbonImmutable::instance($dateTime);
}
return Carbon::instance($dateTime);
}
}
<?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* 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 Closure;
use Symfony\Component\Translation\TranslatorBagInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Contracts\Translation\LocaleAwareInterface;
use Symfony\Contracts\Translation\TranslatorInterface as ContractsTranslatorInterface;
if (!interface_exists('Symfony\\Component\\Translation\\TranslatorInterface')) {
class_alias(
'Symfony\\Contracts\\Translation\\TranslatorInterface',
'Symfony\\Component\\Translation\\TranslatorInterface'
);
}
/**
* Trait Localization.
*
* Embed default and locale translators and translation base methods.
*/
trait Localization
{
/**
* Default translator.
*
* @var \Symfony\Component\Translation\TranslatorInterface
*/
protected static $translator;
/**
* Specific translator of the current instance.
*
* @var \Symfony\Component\Translation\TranslatorInterface
*/
protected $localTranslator;
/**
* Options for diffForHumans().
*
* @var int
*/
protected static $humanDiffOptions = CarbonInterface::NO_ZERO_DIFF;
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather use the ->settings() method.
* @see settings
*
* @param int $humanDiffOptions
*/
public static function setHumanDiffOptions($humanDiffOptions)
{
static::$humanDiffOptions = $humanDiffOptions;
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather use the ->settings() method.
* @see settings
*
* @param int $humanDiffOption
*/
public static function enableHumanDiffOption($humanDiffOption)
{
static::$humanDiffOptions = static::getHumanDiffOptions() | $humanDiffOption;
}
/**
* @deprecated To avoid conflict between different third-party libraries, static setters should not be used.
* You should rather use the ->settings() method.
* @see settings
*
* @param int $humanDiffOption
*/
public static function disableHumanDiffOption($humanDiffOption)
{
static::$humanDiffOptions = static::getHumanDiffOptions() & ~$humanDiffOption;
}
/**
* Return default humanDiff() options (merged flags as integer).
*
* @return int
*/
public static function getHumanDiffOptions()
{
return static::$humanDiffOptions;
}
/**
* Get the default translator instance in use.
*
* @return \Symfony\Component\Translation\TranslatorInterface
*/
public static function getTranslator()
{
return static::translator();
}
/**
* Set the default translator instance to use.
*
* @param \Symfony\Component\Translation\TranslatorInterface $translator
*
* @return void
*/
public static function setTranslator(TranslatorInterface $translator)
{
static::$translator = $translator;
}
/**
* Return true if the current instance has its own translator.
*
* @return bool
*/
public function hasLocalTranslator()
{
return isset($this->localTranslator);
}
/**
* Get the translator of the current instance or the default if none set.
*
* @return \Symfony\Component\Translation\TranslatorInterface
*/
public function getLocalTranslator()
{
return $this->localTranslator ?: static::translator();
}
/**
* Set the translator for the current instance.
*
* @param \Symfony\Component\Translation\TranslatorInterface $translator
*
* @return $this
*/
public function setLocalTranslator(TranslatorInterface $translator)
{
$this->localTranslator = $translator;
return $this;
}
/**
* Returns raw translation message for a given key.
*
* @param \Symfony\Component\Translation\TranslatorInterface $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
*/
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 = $translator->getCatalogue($locale)->get($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 \Symfony\Component\Translation\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 \Symfony\Component\Translation\TranslatorInterface $translator
* @param string $key
* @param array $parameters
* @param null $number
*
* @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%'];
}
// @codeCoverageIgnoreStart
$choice = $translator instanceof ContractsTranslatorInterface
? $translator->trans($key, $parameters)
: $translator->transChoice($key, $number, $parameters);
// @codeCoverageIgnoreEnd
return (string) $choice;
}
/**
* Translate using translation string or callback available.
*
* @param string $key
* @param array $parameters
* @param null $number
* @param \Symfony\Component\Translation\TranslatorInterface $translator
*
* @return string
*/
public function translate(string $key, array $parameters = [], $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($number, $this->translateNumber($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 "$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($timeString, $from = null, $to = null, $mode = CarbonInterface::TRANSLATE_ALL)
{
// Fallback source and destination locales
$from = $from ?: static::getLocale();
$to = $to ?: 'en';
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 ($key === 'from') {
foreach (['months', 'weekdays'] as $variable) {
$list = $messages[$variable.'_standalone'] ?? null;
if ($list) {
foreach ($$variable as $index => &$name) {
$name .= '|'.$messages[$variable.'_standalone'][$index];
}
}
}
}
$$translationKey = array_merge(
$mode & CarbonInterface::TRANSLATE_MONTHS ? static::getTranslationArray($months, 12, $timeString) : [],
$mode & CarbonInterface::TRANSLATE_MONTHS ? static::getTranslationArray($messages['months_short'] ?? [], 12, $timeString) : [],
$mode & CarbonInterface::TRANSLATE_DAYS ? static::getTranslationArray($weekdays, 7, $timeString) : [],
$mode & CarbonInterface::TRANSLATE_DAYS ? static::getTranslationArray($messages['weekdays_short'] ?? [], 7, $timeString) : [],
$mode & CarbonInterface::TRANSLATE_DIFF ? static::translateWordsByKeys([
'diff_now',
'diff_today',
'diff_yesterday',
'diff_tomorrow',
'diff_before_yesterday',
'diff_after_tomorrow',
], $messages, $key) : [],
$mode & CarbonInterface::TRANSLATE_UNITS ? static::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 < 12 ? 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 an other.
*
* @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($timeString, $to = null)
{
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, ...$fallbackLocales)
{
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->setLocalTranslator($translator);
}
return $this;
}
/**
* Get the current translator locale.
*
* @return string
*/
public static function getLocale()
{
return static::getLocaleAwareTranslator()->getLocale();
}
/**
* Set the current translator locale and indicate if the source locale file exists.
* Pass 'auto' as locale to use closest language from the current LC_TIME locale.
*
* @param string $locale locale ex. en
*
* @return bool
*/
public static function setLocale($locale)
{
return static::getLocaleAwareTranslator()->setLocale($locale) !== false;
}
/**
* Set the fallback locale.
*
* @see https://symfony.com/doc/current/components/translation.html#fallback-locales
*
* @param string $locale
*/
public static function setFallbackLocale($locale)
{
$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
*
* @return string|null
*/
public static function getFallbackLocale()
{
$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($locale, $func)
{
$currentLocale = static::getLocale();
$result = $func(static::setLocale($locale) ? static::getLocale() : false, static::translator());
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($locale)
{
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($locale)
{
return static::executeWithLocale($locale, function ($newLocale, TranslatorInterface $translator) {
if (!$newLocale) {
return false;
}
foreach (['ago', 'from_now', 'before', 'after'] as $key) {
if ($translator instanceof TranslatorBagInterface && $translator->getCatalogue($newLocale)->get($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($locale)
{
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($locale)
{
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;
}
/**
* Initialize the default translator instance if necessary.
*
* @return \Symfony\Component\Translation\TranslatorInterface
*/
protected static function translator()
{
if (static::$translator === null) {
static::$translator = Translator::get();
}
return static::$translator;
}
/**
* 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.
*
* @param null $translator
*
* @return string|null
*/
protected function getTranslatorLocale($translator = null): ?string
{
if (\func_num_args() === 0) {
$translator = $this->getLocalTranslator();
}
$translator = static::getLocaleAwareTranslator($translator);
return $translator ? $translator->getLocale() : null;
}
/**
* 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::translator();
}
if ($translator && !($translator instanceof LocaleAwareInterface || method_exists($translator, 'getLocale'))) {
throw new NotLocaleAwareException($translator);
}
return $translator;
}
/**
* 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+(,(\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'
? static::cleanWordFromTranslationString(end($parts))
: '(?:'.implode('|', array_map([static::class, '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;
}
}
<?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
/**
* Trait Macros.
*
* Allows users to register macros within the Carbon class.
*/
trait Macro
{
use Mixin;
/**
* The registered macros.
*
* @var array
*/
protected static $globalMacros = [];
/**
* The registered generic macros.
*
* @var array
*/
protected static $globalGenericMacros = [];
/**
* Register a custom macro.
*
* @example
* ```
* $userSettings = [
* 'locale' => 'pt',
* 'timezone' => 'America/Sao_Paulo',
* ];
* Carbon::macro('userFormat', function () use ($userSettings) {
* return $this->copy()->locale($userSettings['locale'])->tz($userSettings['timezone'])->calendar();
* });
* echo Carbon::yesterday()->hours(11)->userFormat();
* ```
*
* @param string $name
* @param object|callable $macro
*
* @return void
*/
public static function macro($name, $macro)
{
static::$globalMacros[$name] = $macro;
}
/**
* Remove all macros and generic macros.
*/
public static function resetMacros()
{
static::$globalMacros = [];
static::$globalGenericMacros = [];
}
/**
* Register a custom macro.
*
* @param object|callable $macro
* @param int $priority marco with higher priority is tried first
*
* @return void
*/
public static function genericMacro($macro, $priority = 0)
{
if (!isset(static::$globalGenericMacros[$priority])) {
static::$globalGenericMacros[$priority] = [];
krsort(static::$globalGenericMacros, SORT_NUMERIC);
}
static::$globalGenericMacros[$priority][] = $macro;
}
/**
* Checks if macro is registered globally.
*
* @param string $name
*
* @return bool
*/
public static function hasMacro($name)
{
return isset(static::$globalMacros[$name]);
}
/**
* Get the raw callable macro registered globally for a given name.
*
* @param string $name
*
* @return callable|null
*/
public static function getMacro($name)
{
return static::$globalMacros[$name] ?? null;
}
/**
* Checks if macro is registered globally or locally.
*
* @param string $name
*
* @return bool
*/
public function hasLocalMacro($name)
{
return ($this->localMacros && isset($this->localMacros[$name])) || static::hasMacro($name);
}
/**
* Get the raw callable macro registered globally or locally for a given name.
*
* @param string $name
*
* @return callable|null
*/
public function getLocalMacro($name)
{
return ($this->localMacros ?? [])[$name] ?? static::getMacro($name);
}
}
<?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
use Closure;
use Generator;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use Throwable;
/**
* Trait Mixin.
*
* Allows mixing in entire classes with multiple macros.
*/
trait Mixin
{
/**
* Stack of macro instance contexts.
*
* @var array
*/
protected static $macroContextStack = [];
/**
* Mix another object into the class.
*
* @example
* ```
* Carbon::mixin(new class {
* public function addMoon() {
* return function () {
* return $this->addDays(30);
* };
* }
* public function subMoon() {
* return function () {
* return $this->subDays(30);
* };
* }
* });
* $fullMoon = Carbon::create('2018-12-22');
* $nextFullMoon = $fullMoon->addMoon();
* $blackMoon = Carbon::create('2019-01-06');
* $previousBlackMoon = $blackMoon->subMoon();
* echo "$nextFullMoon\n";
* echo "$previousBlackMoon\n";
* ```
*
* @param object|string $mixin
*
* @throws ReflectionException
*
* @return void
*/
public static function mixin($mixin)
{
\is_string($mixin) && trait_exists($mixin)
? static::loadMixinTrait($mixin)
: static::loadMixinClass($mixin);
}
/**
* @param object|string $mixin
*
* @throws ReflectionException
*/
private static function loadMixinClass($mixin)
{
$methods = (new ReflectionClass($mixin))->getMethods(
ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED
);
foreach ($methods as $method) {
if ($method->isConstructor() || $method->isDestructor()) {
continue;
}
$method->setAccessible(true);
static::macro($method->name, $method->invoke($mixin));
}
}
/**
* @param string $trait
*/
private static function loadMixinTrait($trait)
{
$context = eval(self::getAnonymousClassCodeForTrait($trait));
$className = \get_class($context);
foreach (self::getMixableMethods($context) as $name) {
$closureBase = Closure::fromCallable([$context, $name]);
static::macro($name, function () use ($closureBase, $className) {
/** @phpstan-ignore-next-line */
$context = isset($this) ? $this->cast($className) : new $className();
try {
// @ is required to handle error if not converted into exceptions
$closure = @$closureBase->bindTo($context);
} catch (Throwable $throwable) { // @codeCoverageIgnore
$closure = $closureBase; // @codeCoverageIgnore
}
// in case of errors not converted into exceptions
$closure = $closure ?? $closureBase;
return $closure(...\func_get_args());
});
}
}
private static function getAnonymousClassCodeForTrait(string $trait)
{
return 'return new class() extends '.static::class.' {use '.$trait.';};';
}
private static function getMixableMethods(self $context): Generator
{
foreach (get_class_methods($context) as $name) {
if (method_exists(static::class, $name)) {
continue;
}
yield $name;
}
}
/**
* Stack a Carbon context from inside calls of self::this() and execute a given action.
*
* @param static|null $context
* @param callable $callable
*
* @throws Throwable
*
* @return mixed
*/
protected static function bindMacroContext($context, callable $callable)
{
static::$macroContextStack[] = $context;
$exception = null;
$result = null;
try {
$result = $callable();
} catch (Throwable $throwable) {
$exception = $throwable;
}
array_pop(static::$macroContextStack);
if ($exception) {
throw $exception;
}
return $result;
}
/**
* Return the current context from inside a macro callee or a null if static.
*
* @return static|null
*/
protected static function context()
{
return end(static::$macroContextStack) ?: null;
}
/**
* Return the current context from inside a macro callee or a new one if static.
*
* @return static
*/
protected static function this()
{
return end(static::$macroContextStack) ?: new static();
}
}
<?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* 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;
/**
* 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->copy()->firstOfMonth();
$check = $date->rawFormat('Y-m');
$date = $date->modify('+'.$nth.' '.static::$days[$dayOfWeek]);
return $date->rawFormat('Y-m') === $check ? $this->modify("$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->copy()->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("$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->copy()->firstOfYear()->modify('+'.$nth.' '.static::$days[$dayOfWeek]);
return $this->year === $date->year ? $this->modify("$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->diffInRealMicroseconds($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->diffInRealMicroseconds($date1) < $this->diffInRealMicroseconds($date2) ? $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->diffInRealMicroseconds($date1) > $this->diffInRealMicroseconds($date2) ? $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
*/
public function modify($modify)
{
return parent::modify((string) $modify);
}
/**
* 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->copy()->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
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* 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;
/**
* Trait Mutability.
*
* Utils to know if the current object is mutable or immutable and convert it.
*/
trait Mutability
{
use Cast;
/**
* Returns true if the current class/instance is mutable.
*
* @return bool
*/
public static function isMutable()
{
return false;
}
/**
* Returns true if the current class/instance is immutable.
*
* @return bool
*/
public static function isImmutable()
{
return !static::isMutable();
}
/**
* Return a mutable copy of the instance.
*
* @return Carbon
*/
public function toMutable()
{
/** @var Carbon $date */
$date = $this->cast(Carbon::class);
return $date;
}
/**
* Return a immutable copy of the instance.
*
* @return CarbonImmutable
*/
public function toImmutable()
{
/** @var CarbonImmutable $date */
$date = $this->cast(CarbonImmutable::class);
return $date;
}
}
<?php
/**
* This file is part of the Carbon package.
*
* (c) Brian Nesbitt <brian@nesbot.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Carbon\Traits;
trait ObjectInitialisation
{
/**
* True when parent::__construct has been called.
*
* @var string
*/
protected $constructedObjectId = null;
}