repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonImmutable/LastErrorTest.php | tests/CarbonImmutable/LastErrorTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonImmutable;
use Carbon\CarbonImmutable as Carbon;
use Carbon\Traits\Creator;
use DateTime;
use PHPUnit\Framework\Attributes\RequiresPhp;
use Tests\AbstractTestCase;
class LastErrorTest extends AbstractTestCase
{
/**
* @var array
*/
protected $lastErrors;
/**
* @var array
*/
protected $noErrors;
protected function setUp(): void
{
parent::setUp();
$this->lastErrors = [
'warning_count' => 1,
'warnings' => ['11' => 'The parsed date was invalid'],
'error_count' => 0,
'errors' => [],
];
}
#[RequiresPhp('>=8.2')]
public function testCreateHandlesLastErrors()
{
$carbon = new Carbon('2017-02-30');
$datetime = new DateTime('2017-02-30');
$this->assertSame($this->lastErrors, $carbon->getLastErrors());
$this->assertSame($carbon->getLastErrors(), $datetime->getLastErrors());
$carbon = new Carbon('2017-02-15');
$this->assertFalse($carbon->getLastErrors());
}
public function testLastErrorsInitialization()
{
$obj = new class() {
use Creator;
/** @phpstan-ignore-next-line */
public function __construct($time = null, $tz = null)
{
}
public function triggerError()
{
self::setLastErrors([
'warning_count' => 1,
'warnings' => ['11' => 'The parsed date was invalid'],
'error_count' => 0,
'errors' => [],
]);
}
};
$this->assertFalse($obj::getLastErrors());
$obj->triggerError();
$this->assertSame($this->lastErrors, $obj::getLastErrors());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonImmutable/ArraysTest.php | tests/CarbonImmutable/ArraysTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonImmutable;
use Carbon\CarbonImmutable as Carbon;
use Carbon\Translator;
use Tests\AbstractTestCase;
class ArraysTest extends AbstractTestCase
{
public function testToArray()
{
$dt = Carbon::now();
$dtToArray = $dt->toArray();
$this->assertIsArray($dtToArray);
$this->assertArrayHasKey('year', $dtToArray);
$this->assertSame($dt->year, $dtToArray['year']);
$this->assertArrayHasKey('month', $dtToArray);
$this->assertSame($dt->month, $dtToArray['month']);
$this->assertArrayHasKey('day', $dtToArray);
$this->assertSame($dt->day, $dtToArray['day']);
$this->assertArrayHasKey('dayOfWeek', $dtToArray);
$this->assertSame($dt->dayOfWeek, $dtToArray['dayOfWeek']);
$this->assertArrayHasKey('dayOfYear', $dtToArray);
$this->assertSame($dt->dayOfYear, $dtToArray['dayOfYear']);
$this->assertArrayHasKey('hour', $dtToArray);
$this->assertSame($dt->hour, $dtToArray['hour']);
$this->assertArrayHasKey('minute', $dtToArray);
$this->assertSame($dt->minute, $dtToArray['minute']);
$this->assertArrayHasKey('second', $dtToArray);
$this->assertSame($dt->second, $dtToArray['second']);
$this->assertArrayHasKey('micro', $dtToArray);
$this->assertSame($dt->micro, $dtToArray['micro']);
$this->assertArrayHasKey('timestamp', $dtToArray);
$this->assertSame($dt->timestamp, $dtToArray['timestamp']);
$this->assertArrayHasKey('timezone', $dtToArray);
$this->assertEquals($dt->timezone, $dtToArray['timezone']);
$this->assertArrayHasKey('formatted', $dtToArray);
$this->assertSame($dt->format(Carbon::DEFAULT_TO_STRING_FORMAT), $dtToArray['formatted']);
}
public function testDebugInfo()
{
$dt = Carbon::parse('2019-04-09 11:10:10.667952');
$debug = $dt->__debugInfo();
// Ignored as not in PHP 8
if (isset($debug['timezone_type'])) {
unset($debug['timezone_type']);
}
$this->assertSame([
'date' => '2019-04-09 11:10:10.667952',
'timezone' => 'America/Toronto',
], $debug);
$dt = Carbon::parse('2019-04-09 11:10:10.667952')->locale('fr_FR');
$debug = $dt->__debugInfo();
// Ignored as not in PHP 8
if (isset($debug['timezone_type'])) {
unset($debug['timezone_type']);
}
$this->assertSame([
'localTranslator' => Translator::get('fr_FR'),
'date' => '2019-04-09 11:10:10.667952',
'timezone' => 'America/Toronto',
], $debug);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonImmutable/FluidSettersTest.php | tests/CarbonImmutable/FluidSettersTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonImmutable;
use Carbon\CarbonImmutable as Carbon;
use Tests\AbstractTestCase;
class FluidSettersTest extends AbstractTestCase
{
public function testFluidYearSetter()
{
$d = Carbon::now();
$d2 = $d->year(1995);
$this->assertInstanceOfCarbon($d2);
$this->assertInstanceOf(Carbon::class, $d2);
$this->assertSame($this->immutableNow->year, $d->year);
$this->assertSame(1995, $d2->year);
}
public function testFluidMonthSetter()
{
$d = Carbon::now();
$d2 = $d->month(3);
$this->assertInstanceOfCarbon($d2);
$this->assertInstanceOf(Carbon::class, $d2);
$this->assertSame($this->immutableNow->month, $d->month);
$this->assertSame(3, $d2->month);
}
public function testFluidMonthSetterWithWrap()
{
$d = Carbon::createFromDate(2012, 8, 21);
$d2 = $d->month(13);
$this->assertInstanceOfCarbon($d2);
$this->assertInstanceOf(Carbon::class, $d2);
$this->assertSame(8, $d->month);
$this->assertSame(1, $d2->month);
}
public function testFluidDaySetter()
{
$d = Carbon::now();
$d2 = $d->day(2);
$this->assertInstanceOfCarbon($d2);
$this->assertInstanceOf(Carbon::class, $d2);
$this->assertSame($this->immutableNow->day, $d->day);
$this->assertSame(2, $d2->day);
}
public function testFluidDaySetterWithWrap()
{
$d = Carbon::createFromDate(2000, 1, 3);
$d2 = $d->day(32);
$this->assertInstanceOfCarbon($d2);
$this->assertInstanceOf(Carbon::class, $d2);
$this->assertSame(3, $d->day);
$this->assertSame(1, $d2->day);
}
public function testFluidSetDate()
{
$d = Carbon::createFromDate(2000, 1, 1);
$d2 = $d->setDate(1995, 13, 32);
$this->assertInstanceOfCarbon($d2);
$this->assertInstanceOf(Carbon::class, $d2);
$this->assertCarbon($d, 2000, 1, 1);
$this->assertCarbon($d2, 1996, 2, 1);
}
public function testFluidHourSetter()
{
$d = Carbon::now();
$d2 = $d->hour(2);
$this->assertInstanceOfCarbon($d2);
$this->assertInstanceOf(Carbon::class, $d2);
$this->assertSame($this->immutableNow->hour, $d->hour);
$this->assertSame(2, $d2->hour);
}
public function testFluidHourSetterWithWrap()
{
$d = Carbon::now();
$d2 = $d->hour(25);
$this->assertInstanceOfCarbon($d2);
$this->assertInstanceOf(Carbon::class, $d2);
$this->assertSame($this->immutableNow->hour, $d->hour);
$this->assertSame(1, $d2->hour);
}
public function testFluidMinuteSetter()
{
$d = Carbon::now();
$d2 = $d->minute(2);
$this->assertInstanceOfCarbon($d2);
$this->assertInstanceOf(Carbon::class, $d2);
$this->assertSame($this->immutableNow->minute, $d->minute);
$this->assertSame(2, $d2->minute);
}
public function testFluidMinuteSetterWithWrap()
{
$d = Carbon::now();
$d2 = $d->minute(61);
$this->assertInstanceOfCarbon($d2);
$this->assertInstanceOf(Carbon::class, $d2);
$this->assertSame($this->immutableNow->minute, $d->minute);
$this->assertSame(1, $d2->minute);
}
public function testFluidSecondSetter()
{
$d = Carbon::now();
$d2 = $d->second(2);
$this->assertInstanceOfCarbon($d2);
$this->assertInstanceOf(Carbon::class, $d2);
$this->assertSame($this->immutableNow->second, $d->second);
$this->assertSame(2, $d2->second);
}
public function testFluidSecondSetterWithWrap()
{
$d = Carbon::now();
$d2 = $d->second(62);
$this->assertInstanceOfCarbon($d2);
$this->assertInstanceOf(Carbon::class, $d2);
$this->assertSame($this->immutableNow->second, $d->second);
$this->assertSame(2, $d2->second);
}
public function testFluidSetTime()
{
$d = Carbon::createFromDate(2000, 1, 1);
$this->assertInstanceOfCarbon($d2 = $d->setTime(25, 61, 61));
$this->assertCarbon($d2, 2000, 1, 2, 2, 2, 1);
}
public function testFluidTimestampSetter()
{
$d = Carbon::now();
$this->assertInstanceOfCarbon($d2 = $d->timestamp(10));
$this->assertSame(10, $d2->timestamp);
$this->assertInstanceOfCarbon($d2 = $d->timestamp(1600887164.88952298));
$this->assertSame('2020-09-23 14:52:44.889523', $d2->format('Y-m-d H:i:s.u'));
$this->assertInstanceOfCarbon($d2 = $d->timestamp('0.88951247 1600887164'));
$this->assertSame('2020-09-23 14:52:44.889512', $d2->format('Y-m-d H:i:s.u'));
$this->assertInstanceOfCarbon($d2 = $d->timestamp('0.88951247/1600887164/12.56'));
$this->assertSame('2020-09-23 14:52:57.449512', $d2->format('Y-m-d H:i:s.u'));
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonImmutable/SettingsTest.php | tests/CarbonImmutable/SettingsTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonImmutable;
use Carbon\CarbonImmutable as Carbon;
use Tests\AbstractTestCase;
class SettingsTest extends AbstractTestCase
{
public function testSettings()
{
$paris = Carbon::parse('2018-01-31 00:00:00')->settings([
'timezone' => 'Europe/Paris',
'locale' => 'fr_FR',
'monthOverflow' => true,
'yearOverflow' => true,
]);
$this->assertEquals([
'timezone' => 'Europe/Paris',
'locale' => 'fr_FR',
'monthOverflow' => true,
'yearOverflow' => true,
], $paris->getSettings());
$saoPaulo = Carbon::parse('2018-01-31 00:00:00')->settings([
'timezone' => 'America/Sao_Paulo',
'locale' => 'pt',
'monthOverflow' => false,
'yearOverflow' => false,
]);
$this->assertEquals([
'timezone' => 'America/Sao_Paulo',
'locale' => 'pt',
'monthOverflow' => false,
'yearOverflow' => false,
], $saoPaulo->getSettings());
$this->assertSame('2 jours 1 heure avant', $paris->addMonth()->from(Carbon::parse('2018-03-05', 'UTC'), null, false, 3));
$this->assertSame('4 dias 21 horas antes', $saoPaulo->addMonth()->from(Carbon::parse('2018-03-05', 'UTC'), null, false, 3));
$this->assertSame('2 jours et une heure avant', $paris->addMonth()->from(Carbon::parse('2018-03-05', 'UTC'), ['parts' => 3, 'join' => true, 'aUnit' => true]));
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonImmutable/SerializationTest.php | tests/CarbonImmutable/SerializationTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonImmutable;
use Carbon\CarbonImmutable as Carbon;
use Carbon\CarbonTimeZone;
use DateTimeImmutable;
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\RequiresPhpExtension;
use ReflectionClass;
use ReflectionObject;
use ReflectionProperty;
use Tests\AbstractTestCase;
use Throwable;
class SerializationTest extends AbstractTestCase
{
protected string $serialized;
protected function setUp(): void
{
parent::setUp();
$this->serialized = \extension_loaded('msgpack')
? 'O:22:"Carbon\CarbonImmutable":4:{s:4:"date";s:26:"2016-02-01 13:20:25.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:15:"America/Toronto";s:18:"dumpDateProperties";a:2:{s:4:"date";s:26:"2016-02-01 13:20:25.000000";s:8:"timezone";s:15:"America/Toronto";}}'
: 'O:22:"Carbon\CarbonImmutable":3:{s:4:"date";s:26:"2016-02-01 13:20:25.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:15:"America/Toronto";}';
}
protected function cleanSerialization(string $serialization): string
{
return preg_replace('/s:\d+:"[^"]*dumpDateProperties"/', 's:18:"dumpDateProperties"', $serialization);
}
public function testSerialize()
{
$dt = Carbon::create(2016, 2, 1, 13, 20, 25);
$this->assertSame($this->serialized, $this->cleanSerialization($dt->serialize()));
$this->assertSame($this->serialized, $this->cleanSerialization(serialize($dt)));
}
public function testFromUnserialized()
{
$dt = Carbon::fromSerialized($this->serialized);
$this->assertCarbon($dt, 2016, 2, 1, 13, 20, 25);
$timezone = $dt->getTimezone();
$this->assertSame(CarbonTimeZone::class, $timezone::class);
$this->assertSame('America/Toronto', $timezone->getName());
$dt = unserialize($this->serialized);
$timezone = $dt->getTimezone();
$this->assertCarbon($dt, 2016, 2, 1, 13, 20, 25);
$this->assertSame(CarbonTimeZone::class, $timezone::class);
$this->assertSame('America/Toronto', $timezone->getName());
}
public function testSerialization()
{
$this->assertEquals(Carbon::now(), unserialize(serialize(Carbon::now())));
}
public static function dataForTestFromUnserializedWithInvalidValue()
{
return [
[null],
[true],
[false],
[123],
['foobar'],
];
}
#[DataProvider('dataForTestFromUnserializedWithInvalidValue')]
public function testFromUnserializedWithInvalidValue(mixed $value)
{
$this->expectExceptionObject(new InvalidArgumentException(
"Invalid serialized value: $value",
));
Carbon::fromSerialized($value);
}
public function testDateSerializationReflectionCompatibility()
{
$tz = $this->firstValidTimezoneAmong(['America/Los_Angeles', 'US/Pacific'])->getName();
try {
$reflection = (new ReflectionClass(DateTimeImmutable::class))->newInstanceWithoutConstructor();
@$reflection->date = '1990-01-17 10:28:07';
@$reflection->timezone_type = 3;
@$reflection->timezone = $tz;
$date = unserialize(serialize($reflection));
} catch (Throwable $exception) {
$this->markTestSkipped(
"It fails on DateTime so Carbon can't support it, error was:\n".$exception->getMessage()
);
}
$this->assertSame('1990-01-17 10:28:07', $date->format('Y-m-d h:i:s'));
$reflection = (new ReflectionClass(Carbon::class))->newInstanceWithoutConstructor();
@$reflection->date = '1990-01-17 10:28:07';
@$reflection->timezone_type = 3;
@$reflection->timezone = $tz;
$date = unserialize(serialize($reflection));
$this->assertSame('1990-01-17 10:28:07', $date->format('Y-m-d h:i:s'));
$reflection = new ReflectionObject(Carbon::parse('1990-01-17 10:28:07'));
$target = (new ReflectionClass(Carbon::class))->newInstanceWithoutConstructor();
/** @var ReflectionProperty[] $properties */
$properties = [];
foreach ($reflection->getProperties() as $property) {
$properties[$property->getName()] = $property;
}
$setValue = function ($key, $value) use (&$properties, &$target) {
if (isset($properties[$key])) {
$properties[$key]->setValue($target, $value);
return;
}
@$target->$key = $value;
};
$setValue('date', '1990-01-17 10:28:07');
$setValue('timezone_type', 3);
$setValue('timezone', $tz);
$date = unserialize(serialize($target));
$this->assertSame('1990-01-17 10:28:07', $date->format('Y-m-d h:i:s'));
}
#[RequiresPhpExtension('msgpack')]
public function testMsgPackExtension(): void
{
$string = '2018-06-01 21:25:13.321654 Europe/Vilnius';
$date = Carbon::parse('2018-06-01 21:25:13.321654 Europe/Vilnius');
$message = @msgpack_pack($date);
$copy = msgpack_unpack($message);
$this->assertSame($string, $copy->format('Y-m-d H:i:s.u e'));
}
public function testSerializeRawMethod(): void
{
$date = Carbon::parse('2018-06-01 21:25:13.321654 Europe/Vilnius');
$expected = [
'date' => '2018-06-01 21:25:13.321654',
'timezone_type' => 3,
'timezone' => 'Europe/Vilnius',
];
if (\extension_loaded('msgpack')) {
$expected['dumpDateProperties'] = [
'date' => $date->format('Y-m-d H:i:s.u'),
'timezone' => $date->tzName,
];
}
$this->assertSame($expected, $date->__serialize());
$date->locale('lt_LT');
$expected['dumpLocale'] = 'lt_LT';
$this->assertSame($expected, $date->__serialize());
}
public function testNewInstanceWithoutConstructor(): void
{
$tz = $this->firstValidTimezoneAmong(['America/Los_Angeles', 'US/Pacific'])->getName();
/** @var Carbon $date */
$date = (new ReflectionClass(Carbon::class))->newInstanceWithoutConstructor();
@$date->date = '1990-01-17 10:28:07';
@$date->timezone_type = 3;
@$date->timezone = $tz;
@$date->dumpLocale = 'es';
@$date->constructedObjectId = spl_object_hash($this);
$date->__construct('1990-01-17 10:28:07', $tz);
$date->locale('es');
$this->assertSame('1990-01-17 10:28:07 '.$tz, $date->format('Y-m-d H:i:s e'));
$this->assertSame('es', $date->locale);
}
public function testUnserializeRawMethod(): void
{
/** @var Carbon $date */
$date = (new ReflectionClass(Carbon::class))->newInstanceWithoutConstructor();
$date->__unserialize([
'date' => '2018-06-01 21:25:13.321654',
'timezone_type' => 3,
'timezone' => 'Europe/Vilnius',
]);
$this->assertSame('2018-06-01 21:25:13.321654 Europe/Vilnius', $date->format('Y-m-d H:i:s.u e'));
$this->assertSame('en', $date->locale);
/** @var Carbon $date */
$date = (new ReflectionClass(Carbon::class))->newInstanceWithoutConstructor();
$date->__unserialize([
'date' => '2018-06-01 21:25:13.321654',
'timezone_type' => 3,
'timezone' => 'Europe/Vilnius',
'dumpLocale' => 'lt_LT',
]);
$this->assertSame('2018-06-01 21:25:13.321654 Europe/Vilnius', $date->format('Y-m-d H:i:s.u e'));
$this->assertSame('lt_LT', $date->locale);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonImmutable/Fixtures/MyCarbon.php | tests/CarbonImmutable/Fixtures/MyCarbon.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonImmutable\Fixtures;
use Carbon\CarbonImmutable as Carbon;
class MyCarbon extends Carbon
{
//
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonImmutable/Fixtures/BadIsoCarbon.php | tests/CarbonImmutable/Fixtures/BadIsoCarbon.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonImmutable\Fixtures;
use Carbon\CarbonImmutable as Carbon;
class BadIsoCarbon extends Carbon
{
public static function getIsoUnits(): array
{
return [
'MMM' => ['fooxyz', ['barxyz']],
];
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonImmutable/Fixtures/Mixin.php | tests/CarbonImmutable/Fixtures/Mixin.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonImmutable\Fixtures;
use Carbon\CarbonImmutable;
class Mixin
{
public $timezone;
public function setUserTimezone()
{
$mixin = $this;
return function ($timezone) use ($mixin) {
$mixin->timezone = $timezone;
};
}
public function userFormat()
{
$mixin = $this;
return function ($format) use ($mixin) {
/** @var CarbonImmutable $date */
$date = $this;
if ($mixin->timezone) {
$date = $date->setTimezone($mixin->timezone);
}
return $date->format($format);
};
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonTimeZone/GettersTest.php | tests/CarbonTimeZone/GettersTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonTimeZone;
use Carbon\CarbonTimeZone;
use Carbon\FactoryImmutable;
use DateTimeImmutable;
use Tests\AbstractTestCase;
class GettersTest extends AbstractTestCase
{
public function testGetAbbr(): void
{
$tz = new CarbonTimeZone('Europe/London');
$this->assertSame('BST', $tz->getAbbr(true));
$this->assertSame('GMT', $tz->getAbbr(false));
}
public function testGetAbbreviatedName(): void
{
$tz = new CarbonTimeZone('Europe/London');
$this->assertSame('BST', $tz->getAbbreviatedName(true));
$this->assertSame('GMT', $tz->getAbbreviatedName(false));
$tz = CarbonTimeZone::create('Europe/Athens');
$this->assertSame('EEST', $tz->getAbbreviatedName(true));
$this->assertSame('EET', $tz->getAbbreviatedName(false));
$tz = CarbonTimeZone::create('Pacific/Auckland');
$this->assertSame('NZST', $tz->getAbbreviatedName(true));
$this->assertSame('NZMT', $tz->getAbbreviatedName(false));
$tz = CarbonTimeZone::create('America/Toronto');
$this->assertSame('EDT', $tz->getAbbreviatedName(true));
$this->assertSame('EST', $tz->getAbbreviatedName(false));
$tz = CarbonTimeZone::create('Arctic/Longyearbyen');
$this->assertSame('CEST', $tz->getAbbreviatedName(true));
$this->assertSame('CET', $tz->getAbbreviatedName(false));
$tz = CarbonTimeZone::create('Atlantic/Faroe');
$this->assertSame('WEST', $tz->getAbbreviatedName(true));
$this->assertSame('WET', $tz->getAbbreviatedName(false));
$tz = CarbonTimeZone::create('Africa/Ceuta');
$this->assertSame('CEST', $tz->getAbbreviatedName(true));
$this->assertSame('CET', $tz->getAbbreviatedName(false));
$tz = CarbonTimeZone::create('Canada/Yukon');
$this->assertSame('PDT', $tz->getAbbreviatedName(true));
$this->assertSame('PST', $tz->getAbbreviatedName(false));
$tz = CarbonTimeZone::create('Asia/Pontianak');
$this->assertSame('unknown', $tz->getAbbreviatedName(true));
$this->assertSame('WIB', $tz->getAbbreviatedName(false));
}
public function testToRegionName(): void
{
$summer = new DateTimeImmutable('2024-08-19 12:00 UTC');
$tz = new CarbonTimeZone('Europe/London');
$this->assertSame('Europe/London', $tz->toRegionName($summer));
$tz = new CarbonTimeZone('+05:00');
$this->assertSame('Antarctica/Mawson', $tz->toRegionName($summer));
$tz = new CarbonTimeZone('+05:00');
$this->assertSame('Antarctica/Mawson', $tz->toRegionName($summer));
$factory = new FactoryImmutable();
$factory->setTestNowAndTimezone('2024-01-19 12:00 UTC');
$this->assertSame('-06:00', $factory->now('America/Chicago')->getTimezone()->toOffsetName());
// The 2 assertions below are the current behavior
// but it's questionable, as current time is in winter, -6 should give Chicago
// @TODO Check this deeper
$this->assertSame('America/Chicago', $factory->now('-05:00')->getTimezone()->toRegionName());
$this->assertSame('America/Denver', $factory->now('-06:00')->getTimezone()->toRegionName());
$factory->setTestNowAndTimezone('2024-08-19 12:00 UTC');
$this->assertSame('-05:00', $factory->now('America/Chicago')->getTimezone()->toOffsetName());
$this->assertSame('America/Chicago', $factory->now('-05:00')->getTimezone()->toRegionName());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonTimeZone/CreateTest.php | tests/CarbonTimeZone/CreateTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonTimeZone;
use Carbon\CarbonTimeZone;
use Carbon\Exceptions\InvalidTimeZoneException;
use DateTimeZone;
use Tests\AbstractTestCase;
use Tests\CarbonTimeZone\Fixtures\UnknownZone;
class CreateTest extends AbstractTestCase
{
public function testCreate()
{
$tz = new CarbonTimeZone(6);
$this->assertInstanceOf(CarbonTimeZone::class, $tz);
$this->assertInstanceOf(DateTimeZone::class, $tz);
$this->assertSame('+06:00', $tz->getName());
$tz = CarbonTimeZone::create(6);
$this->assertSame('+06:00', $tz->getName());
$tz = CarbonTimeZone::create('+01');
$this->assertSame('+01:00', $tz->getName());
$tz = new CarbonTimeZone('+01');
$this->assertSame('+01:00', $tz->getName());
$tz = CarbonTimeZone::create('-01');
$this->assertSame('-01:00', $tz->getName());
$tz = new CarbonTimeZone('-01');
$this->assertSame('-01:00', $tz->getName());
}
public function testInstance()
{
$tz = new CarbonTimeZone('UTC');
$this->assertSame($tz, CarbonTimeZone::instance($tz));
}
public function testUnknown()
{
$tz = new UnknownZone('UTC');
$this->assertSame('unknown', $tz->getAbbreviatedName());
}
public function testSafeCreateDateTimeZoneWithoutStrictMode()
{
$this->expectExceptionObject(new InvalidTimeZoneException(
'Absolute timezone offset cannot be greater than 99.',
));
new CarbonTimeZone(-15e15);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonTimeZone/ConversionsTest.php | tests/CarbonTimeZone/ConversionsTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonTimeZone;
use Carbon\Carbon;
use Carbon\CarbonTimeZone;
use DateTimeZone;
use Generator;
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Medium;
use stdClass;
use Tests\AbstractTestCaseWithOldNow;
#[Medium]
class ConversionsTest extends AbstractTestCaseWithOldNow
{
public function testToString()
{
$this->assertSame('+06:00', (string) (new CarbonTimeZone(6)));
$this->assertSame('Europe/Paris', (string) (new CarbonTimeZone('Europe/Paris')));
}
public function testToRegionName()
{
$this->assertSame('America/Chicago', (new CarbonTimeZone(-5))->toRegionName());
$this->assertSame('America/Toronto', (new CarbonTimeZone('America/Toronto'))->toRegionName());
$this->assertSame('America/New_York', (new CarbonTimeZone('America/Toronto'))->toOffsetTimeZone()->toRegionName());
$this->assertNull((new CarbonTimeZone(-15))->toRegionName());
$date = Carbon::parse('2018-12-20');
$this->assertSame('America/Chicago', (new CarbonTimeZone('America/Toronto'))->toOffsetTimeZone($date)->toRegionName($date));
$date = Carbon::parse('2020-06-11T12:30:00-02:30');
$this->assertSame('America/St_Johns', $date->getTimezone()->toRegionName($date));
}
public function testToRegionTimeZone()
{
$this->assertSame('America/Chicago', (new CarbonTimeZone(-5))->toRegionTimeZone()->getName());
$this->assertSame('America/Toronto', (new CarbonTimeZone('America/Toronto'))->toRegionTimeZone()->getName());
$this->assertSame('America/New_York', (new CarbonTimeZone('America/Toronto'))->toOffsetTimeZone()->toRegionTimeZone()->getName());
$date = Carbon::parse('2018-12-20');
$this->assertSame('America/Chicago', (new CarbonTimeZone('America/Toronto'))->toOffsetTimeZone($date)->toRegionTimeZone($date)->getName());
}
public static function dataForToOffsetName(): Generator
{
// timezone - number
yield ['2018-12-20', '-05:00', -5];
yield ['2018-06-20', '-05:00', -5];
// timezone - use offset
yield ['2018-12-20', '-05:00', '-05:00'];
yield ['2018-06-20', '-05:00', '-05:00'];
// timezone - by name - with daylight time
yield ['2018-12-20', '-05:00', 'America/Toronto'];
yield ['2018-06-20', '-04:00', 'America/Toronto'];
// timezone - by name - without daylight time
yield ['2018-12-20', '+03:00', 'Asia/Baghdad'];
yield ['2018-06-20', '+03:00', 'Asia/Baghdad'];
// timezone - no full hour - the same time
yield ['2018-12-20', '-09:30', 'Pacific/Marquesas'];
yield ['2018-06-20', '-09:30', 'Pacific/Marquesas'];
// timezone - no full hour -
yield ['2018-12-20', '-03:30', 'America/St_Johns'];
yield ['2018-06-20', '-02:30', 'America/St_Johns'];
// timezone - no full hour +
yield ['2018-12-20', '+13:45', 'Pacific/Chatham'];
yield ['2018-06-20', '+12:45', 'Pacific/Chatham'];
// timezone - UTC
yield ['2018-12-20', '+00:00', 'UTC'];
yield ['2018-06-20', '+00:00', 'UTC'];
}
#[DataProvider('dataForToOffsetName')]
public function testToOffsetName(string $date, string $expectedOffset, string|int $timezone)
{
Carbon::setTestNow(Carbon::parse($date));
$offset = (new CarbonTimeZone($timezone))->toOffsetName();
$this->assertSame($expectedOffset, $offset);
}
#[DataProvider('dataForToOffsetName')]
public function testToOffsetNameDateAsParam(string $date, string $expectedOffset, string|int $timezone)
{
$offset = (new CarbonTimeZone($timezone))->toOffsetName(Carbon::parse($date));
$this->assertSame($expectedOffset, $offset);
}
public function testToOffsetNameFromDifferentCreationMethods()
{
$summer = Carbon::parse('2020-06-15');
$winter = Carbon::parse('2018-12-20');
$this->assertSame('+02:00', (new CarbonTimeZone('Europe/Paris'))->toOffsetName());
$this->assertSame('+05:30', $this->firstValidTimezoneAmong(['Asia/Kolkata', 'Asia/Calcutta'])->toOffsetName());
$this->assertSame('+13:45', CarbonTimeZone::create('Pacific/Chatham')->toOffsetName($winter));
$this->assertSame('+12:00', CarbonTimeZone::create('Pacific/Auckland')->toOffsetName($summer));
$this->assertSame('-05:15', CarbonTimeZone::createFromHourOffset(-5.25)->toOffsetName());
$this->assertSame('-02:30', CarbonTimeZone::createFromMinuteOffset(-150)->toOffsetName());
$this->assertSame('-08:45', CarbonTimeZone::create('-8:45')->toOffsetName());
$this->assertSame('-09:30', CarbonTimeZone::create('Pacific/Marquesas')->toOffsetName());
}
public function testCast()
{
$tz = (new CarbonTimeZone('America/Toronto'))->cast(DateTimeZone::class);
$this->assertSame(DateTimeZone::class, \get_class($tz));
$this->assertSame('America/Toronto', $tz->getName());
$obj = new class('UTC') extends CarbonTimeZone {
};
$class = \get_class($obj);
$tz = (new CarbonTimeZone('America/Toronto'))->cast($class);
$this->assertSame($class, \get_class($tz));
$this->assertSame('America/Toronto', $tz->getName());
}
public function testCastException()
{
$this->expectExceptionObject(new InvalidArgumentException(
'stdClass has not the instance() method needed to cast the date.',
));
(new CarbonTimeZone('America/Toronto'))->cast(stdClass::class);
}
public function testInvalidRegionForOffset()
{
Carbon::useStrictMode(false);
$this->assertNull((new CarbonTimeZone(-15))->toRegionTimeZone());
}
public function testInvalidRegionForOffsetInStrictMode()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Unknown timezone for offset -54000 seconds.',
));
(new CarbonTimeZone(-15))->toRegionTimeZone();
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonTimeZone/Fixtures/UnknownZone.php | tests/CarbonTimeZone/Fixtures/UnknownZone.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonTimeZone\Fixtures;
use Carbon\CarbonTimeZone;
use ReturnTypeWillChange;
class UnknownZone extends CarbonTimeZone
{
#[ReturnTypeWillChange]
public function getName()
{
return 'foobar';
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/PHPUnit/AssertObjectHasPropertyTrait.php | tests/PHPUnit/AssertObjectHasPropertyTrait.php | <?php
declare(strict_types=1);
/**
* 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 Tests\PHPUnit;
use PHPUnit\Framework\TestCase;
require_once method_exists(TestCase::class, 'assertObjectHasProperty')
? __DIR__.'/AssertObjectHasPropertyNoopTrait.php'
: __DIR__.'/AssertObjectHasPropertyPolyfillTrait.php';
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/PHPUnit/AssertObjectHasPropertyNoopTrait.php | tests/PHPUnit/AssertObjectHasPropertyNoopTrait.php | <?php
declare(strict_types=1);
/**
* 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 Tests\PHPUnit;
trait AssertObjectHasPropertyTrait
{
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/PHPUnit/AssertObjectHasPropertyPolyfillTrait.php | tests/PHPUnit/AssertObjectHasPropertyPolyfillTrait.php | <?php
declare(strict_types=1);
/**
* 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 Tests\PHPUnit;
trait AssertObjectHasPropertyTrait
{
protected static function assertObjectHasProperty(string $attributeName, $object, string $message = '')
{
self::assertObjectHasAttribute($attributeName, $object, $message);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriodImmutable/StrictModeTest.php | tests/CarbonPeriodImmutable/StrictModeTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonPeriodImmutable;
use Carbon\CarbonPeriodImmutable;
class StrictModeTest extends \Tests\CarbonPeriod\StrictModeTest
{
protected static string $periodClass = CarbonPeriodImmutable::class;
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriodImmutable/CloneTest.php | tests/CarbonPeriodImmutable/CloneTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonPeriodImmutable;
use Carbon\CarbonPeriodImmutable;
class CloneTest extends \Tests\CarbonPeriod\CloneTest
{
protected static string $periodClass = CarbonPeriodImmutable::class;
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriodImmutable/AliasTest.php | tests/CarbonPeriodImmutable/AliasTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonPeriodImmutable;
use Carbon\CarbonPeriodImmutable;
class AliasTest extends \Tests\CarbonPeriod\AliasTest
{
protected static string $periodClass = CarbonPeriodImmutable::class;
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriodImmutable/IterationMethodsTest.php | tests/CarbonPeriodImmutable/IterationMethodsTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonPeriodImmutable;
use Carbon\CarbonPeriodImmutable;
class IterationMethodsTest extends \Tests\CarbonPeriod\IterationMethodsTest
{
protected static string $periodClass = CarbonPeriodImmutable::class;
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriodImmutable/GettersTest.php | tests/CarbonPeriodImmutable/GettersTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonPeriodImmutable;
use Carbon\CarbonPeriodImmutable;
class GettersTest extends \Tests\CarbonPeriod\GettersTest
{
protected static string $periodClass = CarbonPeriodImmutable::class;
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriodImmutable/FilterTest.php | tests/CarbonPeriodImmutable/FilterTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonPeriodImmutable;
use Carbon\CarbonPeriodImmutable;
class FilterTest extends \Tests\CarbonPeriod\FilterTest
{
protected static string $periodClass = CarbonPeriodImmutable::class;
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriodImmutable/CreateTest.php | tests/CarbonPeriodImmutable/CreateTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonPeriodImmutable;
use Carbon\CarbonPeriodImmutable;
class CreateTest extends \Tests\CarbonPeriod\CreateTest
{
protected static string $periodClass = CarbonPeriodImmutable::class;
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriodImmutable/MacroTest.php | tests/CarbonPeriodImmutable/MacroTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonPeriodImmutable;
use Carbon\CarbonPeriodImmutable;
class MacroTest extends \Tests\CarbonPeriod\MacroTest
{
protected static string $periodClass = CarbonPeriodImmutable::class;
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriodImmutable/ToDatePeriodTest.php | tests/CarbonPeriodImmutable/ToDatePeriodTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonPeriodImmutable;
use Carbon\CarbonPeriodImmutable;
class ToDatePeriodTest extends \Tests\CarbonPeriod\ToDatePeriodTest
{
protected static string $periodClass = CarbonPeriodImmutable::class;
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriodImmutable/RoundingTest.php | tests/CarbonPeriodImmutable/RoundingTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonPeriodImmutable;
use Carbon\CarbonPeriodImmutable;
class RoundingTest extends \Tests\CarbonPeriod\RoundingTest
{
protected static string $periodClass = CarbonPeriodImmutable::class;
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriodImmutable/ToStringTest.php | tests/CarbonPeriodImmutable/ToStringTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonPeriodImmutable;
use Carbon\CarbonPeriodImmutable;
class ToStringTest extends \Tests\CarbonPeriod\ToStringTest
{
protected static string $periodClass = CarbonPeriodImmutable::class;
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriodImmutable/DynamicIntervalTest.php | tests/CarbonPeriodImmutable/DynamicIntervalTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonPeriodImmutable;
use Carbon\CarbonPeriodImmutable;
class DynamicIntervalTest extends \Tests\CarbonPeriod\DynamicIntervalTest
{
protected static string $periodClass = CarbonPeriodImmutable::class;
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriodImmutable/SettersTest.php | tests/CarbonPeriodImmutable/SettersTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonPeriodImmutable;
use Carbon\CarbonPeriodImmutable;
class SettersTest extends \Tests\CarbonPeriod\SettersTest
{
protected static string $periodClass = CarbonPeriodImmutable::class;
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriodImmutable/ComparisonTest.php | tests/CarbonPeriodImmutable/ComparisonTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonPeriodImmutable;
use Carbon\CarbonPeriodImmutable;
class ComparisonTest extends \Tests\CarbonPeriod\ComparisonTest
{
protected static string $periodClass = CarbonPeriodImmutable::class;
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriodImmutable/IteratorTest.php | tests/CarbonPeriodImmutable/IteratorTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonPeriodImmutable;
use Carbon\CarbonPeriodImmutable;
class IteratorTest extends \Tests\CarbonPeriod\IteratorTest
{
protected static string $periodClass = CarbonPeriodImmutable::class;
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/CarbonPeriodImmutable/ToArrayTest.php | tests/CarbonPeriodImmutable/ToArrayTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\CarbonPeriodImmutable;
use Carbon\CarbonPeriodImmutable;
class ToArrayTest extends \Tests\CarbonPeriod\ToArrayTest
{
protected static string $periodClass = CarbonPeriodImmutable::class;
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Unit/WeekDayTest.php | tests/Unit/WeekDayTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Unit;
use Carbon\Exceptions\InvalidFormatException;
use Carbon\WeekDay;
use Tests\AbstractTestCase;
class WeekDayTest extends AbstractTestCase
{
public function testFromName(): void
{
$this->assertSame(WeekDay::Friday, WeekDay::fromName('fri'));
$this->assertSame(WeekDay::Tuesday, WeekDay::fromName('TUESDAY'));
$this->assertSame(WeekDay::Saturday, WeekDay::fromName('sam', 'fr'));
$this->assertSame(WeekDay::Sunday, WeekDay::fromName('Dimanche', 'fr'));
}
public function testFromNumber(): void
{
$this->assertSame(WeekDay::Friday, WeekDay::fromNumber(5));
$this->assertSame(WeekDay::Friday, WeekDay::fromNumber(-2));
$this->assertSame(WeekDay::Tuesday, WeekDay::fromNumber(9));
$this->assertSame(WeekDay::Saturday, WeekDay::fromNumber(-1));
$this->assertSame(WeekDay::Sunday, WeekDay::fromNumber(7));
$this->assertSame(WeekDay::Sunday, WeekDay::fromNumber(0));
}
public function testLocale(): void
{
$this->assertSame('venerdì', WeekDay::Friday->locale('it')->dayName);
$this->assertSame('sábado', WeekDay::Sunday->locale('es')->subDay()->dayName);
}
public function testFromNameFailure(): void
{
$this->expectExceptionObject(new InvalidFormatException("Could not parse 'pr'"));
WeekDay::fromName('pr', 'fr');
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Unit/MonthTest.php | tests/Unit/MonthTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Unit;
use Carbon\CarbonImmutable;
use Carbon\Exceptions\InvalidFormatException;
use Carbon\Month;
use Tests\AbstractTestCase;
class MonthTest extends AbstractTestCase
{
public function testFromName(): void
{
$this->assertSame(Month::January, Month::fromName('jan'));
$this->assertSame(Month::February, Month::fromName('FEBRUARY'));
$this->assertSame(Month::February, Month::fromName('févr', 'fr'));
$this->assertSame(Month::March, Month::fromName('Mars', 'fr'));
}
public function testFromNumber(): void
{
$this->assertSame(Month::May, Month::fromNumber(5));
$this->assertSame(Month::October, Month::fromNumber(-2));
$this->assertSame(Month::September, Month::fromNumber(9));
$this->assertSame(Month::November, Month::fromNumber(-1));
$this->assertSame(Month::July, Month::fromNumber(7));
$this->assertSame(Month::December, Month::fromNumber(0));
$this->assertSame(Month::December, Month::fromNumber(12));
$this->assertSame(Month::January, Month::fromNumber(13));
}
public function testOfTheYear(): void
{
$date = Month::October->ofTheYear(2020);
$this->assertInstanceOf(CarbonImmutable::class, $date);
$this->assertSame('2020-10-01 00:00:00.000000 America/Toronto', $date->format('Y-m-d H:i:s.u e'));
}
public function testLocale(): void
{
$this->assertSame('ottobre', Month::October->locale('it')->monthName);
$this->assertSame('diciembre', Month::January->locale('es')->subMonth()->monthName);
}
public function testFromNameFailure(): void
{
$this->expectExceptionObject(new InvalidFormatException("Could not parse 'pr 1'"));
Month::fromName('pr', 'fr');
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Unit/UnitTest.php | tests/Unit/UnitTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Unit;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterval;
use Carbon\CarbonPeriodImmutable;
use Carbon\Unit;
use Carbon\WeekDay;
use PHPUnit\Framework\Attributes\TestWith;
use Tests\AbstractTestCase;
class UnitTest extends AbstractTestCase
{
public static function setUpBeforeClass(): void
{
parent::setUpBeforeClass();
CarbonImmutable::setLocale('en');
}
#[TestWith([Unit::Microsecond, 'microseconds'])]
#[TestWith([Unit::Millisecond, 'millisecond'])]
#[TestWith([Unit::Second, 'second'])]
#[TestWith([Unit::Minute, 'minute'])]
#[TestWith([Unit::Hour, 'hours'])]
#[TestWith([Unit::Day, 'day'])]
#[TestWith([Unit::Week, 'WEEK'])]
#[TestWith([Unit::Month, 'Month'])]
#[TestWith([Unit::Quarter, 'quarters'])]
#[TestWith([Unit::Year, 'year'])]
#[TestWith([Unit::Decade, 'decade'])]
#[TestWith([Unit::Century, 'centuries'])]
#[TestWith([Unit::Millennium, 'millennia'])]
#[TestWith([Unit::Day, 'day'])]
#[TestWith([Unit::Day, 'day'])]
#[TestWith([Unit::Day, 'jour', 'fr_BE'])]
#[TestWith([Unit::Day, 'JOUR', 'fr'])]
#[TestWith([Unit::Month, 'Monaten', 'de'])]
#[TestWith([Unit::Month, 'monaten', 'de'])]
public function testFromName(Unit $unit, string $name, ?string $locale = null): void
{
$this->assertSame($unit, Unit::fromName($name, $locale));
}
public function testSingular(): void
{
$this->assertSame('day', Unit::Day->singular());
$this->assertSame('century', Unit::Century->singular());
$this->assertSame('jour', Unit::Day->singular('fr'));
$this->assertSame('Tag', Unit::Day->singular('de'));
$this->assertSame('siècle', Unit::Century->singular('fr'));
}
public function testPlural(): void
{
$this->assertSame('days', Unit::Day->plural());
$this->assertSame('centuries', Unit::Century->plural());
$this->assertSame('jours', Unit::Day->plural('fr'));
$this->assertSame('Tage', Unit::Day->plural('de'));
$this->assertSame('siècles', Unit::Century->plural('fr'));
}
public function testInterval(): void
{
$interval = Unit::Day->interval(2);
$this->assertInstanceOf(CarbonInterval::class, $interval);
$this->assertSame(['days' => 2], array_filter($interval->toArray()));
}
public function testLocale(): void
{
$interval = Unit::Day->locale('fr');
$this->assertInstanceOf(CarbonInterval::class, $interval);
$this->assertSame(['days' => 1], array_filter($interval->toArray()));
$this->assertSame('1 jour', $interval->forHumans());
}
public function testToPeriod(): void
{
CarbonImmutable::setTestNow('2023-12-09 11:47:53');
$days = Unit::Day->toPeriod(WeekDay::Monday, WeekDay::Friday);
$this->assertInstanceOf(CarbonPeriodImmutable::class, $days);
$this->assertSame('Every 1 day from 2023-12-11 to 2023-12-15', (string) $days);
}
public function testStepBy(): void
{
CarbonImmutable::setTestNow('2023-12-09 11:47:53');
$days = Unit::Week->stepBy(Unit::Day);
$this->assertInstanceOf(CarbonPeriodImmutable::class, $days);
$this->assertSame('Every 1 day from 2023-12-09 11:47:53 to 2023-12-16 11:47:53', (string) $days);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/LocalizationTest.php | tests/Carbon/LocalizationTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\CarbonInterface;
use Carbon\CarbonInterval;
use Carbon\Language;
use Carbon\Translator;
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\TestWith;
use Symfony\Component\Translation\IdentityTranslator;
use Symfony\Component\Translation\Loader\ArrayLoader;
use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\Translator as SymfonyTranslator;
use Tests\AbstractTestCase;
use Tests\Carbon\Fixtures\MyCarbon;
use Tests\Carbon\Fixtures\NoLocaleTranslator;
#[Group('localization')]
class LocalizationTest extends AbstractTestCase
{
public function testGetTranslator()
{
/** @var Translator $t */
$t = Carbon::getTranslator();
$this->assertNotNull($t);
$this->assertSame('en', $t->getLocale());
}
public function testResetTranslator()
{
/** @var Translator $t */
$t = MyCarbon::getTranslator();
$this->assertNotNull($t);
$this->assertSame('en', $t->getLocale());
}
#[TestWith([
'fr',
['fr_FR.UTF-8', 'fr_FR.utf8', 'fr_FR', 'fr'],
'il y a 2 secondes',
])]
#[TestWith([
'sr',
['sr_ME.UTF-8', 'sr_ME.utf8', 'sr_ME', 'sr'],
['pre 2 sekunde' /* sr */, 'prije 2 sekunde' /* sr_ME */],
])]
#[TestWith([
'zh',
['zh_TW.UTF-8', 'zh_TW.utf8', 'zh_TW', 'zh'],
'2秒前',
])]
public function testSetLocaleToAutoFromSupportedLocale(string $language, array $locales, array|string $twoSecondsAgo)
{
$currentLocale = setlocale(LC_ALL, '0');
$this->setLocaleOrSkip(...$locales);
try {
Carbon::setLocale('auto');
$locale = Carbon::getLocale();
$diff = Carbon::now()->subSeconds(2)->diffForHumans();
} finally {
setlocale(LC_ALL, $currentLocale);
}
$this->assertStringStartsWith($language, $locale);
$this->assertContains($diff, (array) $twoSecondsAgo);
}
public function testSetLocaleToAutoFromUnsupportedLocale()
{
$currentLocale = setlocale(LC_ALL, '0');
$this->setLocaleOrSkip('ar_AE.UTF-8', 'ar_AE.utf8', 'ar_AE', 'ar');
/** @var Translator $translator */
$translator = Carbon::getTranslator();
$translator->resetMessages();
$translator->setLocale('en');
$directories = $translator->getDirectories();
$directory = sys_get_temp_dir().'/carbon'.mt_rand(0, 9999999);
mkdir($directory);
foreach (glob(__DIR__.'/../../src/Carbon/Lang/*.php') as $file) {
copy($file, "$directory/".basename($file));
}
try {
$translator->setDirectories([$directory]);
Carbon::setLocale('auto');
$locale = Carbon::getLocale();
$diff = Carbon::now()->subSeconds(2)->diffForHumans();
} finally {
$translator->setDirectories([$directory]);
setlocale(LC_ALL, $currentLocale);
$this->remove($directory);
$translator->setDirectories($directories);
}
$this->assertStringStartsWith('ar', $locale);
$this->assertSame('منذ ثانيتين', $diff);
}
public function testSetLocaleToAutoFallback()
{
$currentLocale = setlocale(LC_ALL, '0');
/** @var Translator $translator */
$translator = Carbon::getTranslator();
$translator->resetMessages();
$translator->setLocale('en');
$directories = $translator->getDirectories();
$directory = sys_get_temp_dir().'/carbon'.mt_rand(0, 9999999);
try {
$this->setLocaleOrSkip('fr_FR.UTF-8', 'fr_FR.utf8', 'fr_FR', 'fr');
mkdir($directory);
$files = [
'en',
'zh_Hans',
'zh',
'fr',
'fr_CA',
];
foreach ($files as $file) {
copy(__DIR__."/../../src/Carbon/Lang/$file.php", "$directory/$file.php");
}
$translator->setDirectories([$directory]);
/** @var Translator $translator */
$translator = Carbon::getTranslator();
$translator->resetMessages();
Carbon::setLocale('auto');
$locale = Carbon::getLocale();
$diff = Carbon::now()->subSeconds(2)->diffForHumans();
setlocale(LC_ALL, $currentLocale);
$this->assertSame('fr', $locale);
$this->assertSame('il y a 2 secondes', $diff);
$this->setLocaleOrSkip('zh_CN.UTF-8', 'zh_CN.utf8', 'zh_CN', 'zh');
/** @var Translator $translator */
$translator = Carbon::getTranslator();
$translator->resetMessages();
Carbon::setLocale('auto');
$locale = Carbon::getLocale();
$diff = Carbon::now()->subSeconds(2)->diffForHumans();
setlocale(LC_ALL, $currentLocale);
$this->assertSame('zh', $locale);
$this->assertSame('2秒前', $diff);
$this->setLocaleOrSkip('yo_NG.UTF-8', 'yo_NG.utf8', 'yo_NG', 'yo');
/** @var Translator $translator */
$translator = Carbon::getTranslator();
$translator->resetMessages();
Carbon::setLocale('en');
Carbon::setLocale('auto');
$locale = Carbon::getLocale();
$diff = Carbon::now()->subSeconds(2)->diffForHumans();
setlocale(LC_ALL, $currentLocale);
$this->assertSame('en', $locale);
$this->assertSame('2 seconds ago', $diff);
} finally {
setlocale(LC_ALL, $currentLocale);
$translator->setDirectories($directories);
$this->remove($directory);
}
}
/**
* @see \Tests\Carbon\LocalizationTest::testSetLocale
* @see \Tests\Carbon\LocalizationTest::testSetTranslator
*/
public static function dataForLocales(): array
{
return [
'af' => ['af'],
'ar' => ['ar'],
'ar_DZ' => ['ar_DZ'],
'ar_KW' => ['ar_KW'],
'ar_LY' => ['ar_LY'],
'ar_MA' => ['ar_MA'],
'ar_SA' => ['ar_SA'],
'ar_Shakl' => ['ar_Shakl'],
'ar_TN' => ['ar_TN'],
'az' => ['az'],
'be' => ['be'],
'bg' => ['bg'],
'bm' => ['bm'],
'bn' => ['bn'],
'bo' => ['bo'],
'br' => ['br'],
'bs' => ['bs'],
'bs_BA' => ['bs_BA'],
'ca' => ['ca'],
'cs' => ['cs'],
'cv' => ['cv'],
'cy' => ['cy'],
'da' => ['da'],
'de' => ['de'],
'de_AT' => ['de_AT'],
'de_CH' => ['de_CH'],
'dv' => ['dv'],
'dv_MV' => ['dv_MV'],
'el' => ['el'],
'en' => ['en'],
'en_AU' => ['en_AU'],
'en_CA' => ['en_CA'],
'en_GB' => ['en_GB'],
'en_IE' => ['en_IE'],
'en_IL' => ['en_IL'],
'en_NZ' => ['en_NZ'],
'eo' => ['eo'],
'es' => ['es'],
'es_DO' => ['es_DO'],
'es_US' => ['es_US'],
'et' => ['et'],
'eu' => ['eu'],
'fa' => ['fa'],
'fi' => ['fi'],
'fo' => ['fo'],
'fr' => ['fr'],
'fr_CA' => ['fr_CA'],
'fr_CH' => ['fr_CH'],
'fy' => ['fy'],
'gd' => ['gd'],
'gl' => ['gl'],
'gom_Latn' => ['gom_Latn'],
'gu' => ['gu'],
'he' => ['he'],
'hi' => ['hi'],
'hr' => ['hr'],
'hu' => ['hu'],
'hy' => ['hy'],
'hy_AM' => ['hy_AM'],
'id' => ['id'],
'is' => ['is'],
'it' => ['it'],
'ja' => ['ja'],
'jv' => ['jv'],
'ka' => ['ka'],
'kk' => ['kk'],
'km' => ['km'],
'kn' => ['kn'],
'ko' => ['ko'],
'ku' => ['ku'],
'ky' => ['ky'],
'lb' => ['lb'],
'lo' => ['lo'],
'lt' => ['lt'],
'lv' => ['lv'],
'me' => ['me'],
'mi' => ['mi'],
'mk' => ['mk'],
'ml' => ['ml'],
'mn' => ['mn'],
'mr' => ['mr'],
'ms' => ['ms'],
'ms_MY' => ['ms_MY'],
'mt' => ['mt'],
'my' => ['my'],
'nb' => ['nb'],
'ne' => ['ne'],
'nl' => ['nl'],
'nl_BE' => ['nl_BE'],
'nn' => ['nn'],
'no' => ['no'],
'oc' => ['oc'],
'pa_IN' => ['pa_IN'],
'pl' => ['pl'],
'ps' => ['ps'],
'pt' => ['pt'],
'pt_BR' => ['pt_BR'],
'ro' => ['ro'],
'ru' => ['ru'],
'sd' => ['sd'],
'se' => ['se'],
'sh' => ['sh'],
'si' => ['si'],
'sk' => ['sk'],
'sl' => ['sl'],
'sq' => ['sq'],
'sr' => ['sr'],
'sr_Cyrl' => ['sr_Cyrl'],
'sr_Cyrl_ME' => ['sr_Cyrl_ME'],
'sr_Latn_ME' => ['sr_Latn_ME'],
'sr_ME' => ['sr_ME'],
'ss' => ['ss'],
'sv' => ['sv'],
'sw' => ['sw'],
'ta' => ['ta'],
'te' => ['te'],
'tet' => ['tet'],
'tg' => ['tg'],
'th' => ['th'],
'tl_PH' => ['tl_PH'],
'tlh' => ['tlh'],
'tr' => ['tr'],
'tzl' => ['tzl'],
'tzm' => ['tzm'],
'tzm_Latn' => ['tzm_Latn'],
'ug_CN' => ['ug_CN'],
'uk' => ['uk'],
'ur' => ['ur'],
'uz' => ['uz'],
'uz_Latn' => ['uz_Latn'],
'vi' => ['vi'],
'yo' => ['yo'],
'zh' => ['zh'],
'zh_CN' => ['zh_CN'],
'zh_HK' => ['zh_HK'],
'zh_TW' => ['zh_TW'],
];
}
#[DataProvider('dataForLocales')]
public function testSetLocale(string $locale)
{
Carbon::setLocale($locale);
$this->assertTrue($this->areSameLocales($locale, Carbon::getLocale()));
}
#[DataProvider('dataForLocales')]
public function testSetTranslator(string $locale)
{
$ori = Carbon::getTranslator();
$t = new Translator($locale);
$t->addLoader('array', new ArrayLoader());
Carbon::setTranslator($t);
/** @var Translator $t */
$t = Carbon::getTranslator();
$this->assertNotNull($t);
$this->assertTrue($this->areSameLocales($locale, $t->getLocale()));
$this->assertTrue($this->areSameLocales($locale, Carbon::now()->locale()));
Carbon::setTranslator($ori);
}
public function testSetLocaleWithKnownLocale()
{
Carbon::setLocale('fr');
$this->assertSame('fr', Carbon::getLocale());
}
#[TestWith(['DE'])]
#[TestWith(['pt-BR'])]
#[TestWith(['pt-br'])]
#[TestWith(['PT-br'])]
#[TestWith(['PT-BR'])]
#[TestWith(['pt_br'])]
#[TestWith(['PT_br'])]
#[TestWith(['PT_BR'])]
public function testSetLocaleWithMalformedLocale(string $malformedLocale)
{
Carbon::setLocale($malformedLocale);
$split = preg_split('/[-_]/', $malformedLocale);
$this->assertSame(
strtolower($split[0]).(\count($split) === 1 ? '' : '_'.strtoupper($split[1])),
Carbon::getLocale(),
);
}
public function testSetLocaleWithNonExistingLocale()
{
Carbon::setLocale('pt-XX');
$this->assertSame('pt', Carbon::getLocale());
}
public function testSetLocaleWithUnknownLocale()
{
Carbon::setLocale('zz');
$this->assertSame('en', Carbon::getLocale());
}
public function testCustomTranslation()
{
Carbon::setLocale('en');
/** @var Translator $translator */
$translator = Carbon::getTranslator();
/** @var MessageCatalogue $messages */
$messages = $translator->getCatalogue('en');
$resources = $messages->all('messages');
$resources['day'] = '1 boring day|%count% boring days';
$translator->addResource('array', $resources, 'en');
$diff = Carbon::create(2018, 1, 1, 0, 0, 0)
->diffForHumans(Carbon::create(2018, 1, 4, 4, 0, 0), true, false, 2);
$this->assertSame('3 boring days 4 hours', $diff);
Carbon::setLocale('en');
}
public function testCustomLocalTranslation()
{
$boringLanguage = 'en_Overboring';
$translator = Translator::get($boringLanguage);
$translator->setTranslations([
'day' => ':count boring day|:count boring days',
]);
$date1 = Carbon::create(2018, 1, 1, 0, 0, 0);
$date2 = Carbon::create(2018, 1, 4, 4, 0, 0);
$this->assertSame('3 boring days before', $date1->locale($boringLanguage)->diffForHumans($date2));
$translator->setTranslations([
'before' => function ($time) {
return '['.strtoupper($time).']';
},
]);
$this->assertSame('[3 BORING DAYS]', $date1->locale($boringLanguage)->diffForHumans($date2));
$meridiem = Translator::get('ru')->trans('meridiem', [
'hours' => 9,
'minutes' => 30,
'seconds' => 0,
]);
$this->assertSame('утра', $meridiem);
}
public function testAddCustomTranslation()
{
$enBoring = [
'day' => '1 boring day|%count% boring days',
];
Carbon::setLocale('en');
$this->assertSame('en', Carbon::getLocale());
/** @var Translator $translator */
$translator = Carbon::getTranslator();
$translator->setMessages('en', $enBoring);
$diff = Carbon::create(2018, 1, 1, 0, 0, 0)
->diffForHumans(Carbon::create(2018, 1, 4, 4, 0, 0), true, false, 2);
$this->assertSame('3 boring days 4 hours', $diff);
$translator->resetMessages('en');
$diff = Carbon::create(2018, 1, 1, 0, 0, 0)
->diffForHumans(Carbon::create(2018, 1, 4, 4, 0, 0), true, false, 2);
$this->assertSame('3 days 4 hours', $diff);
$translator->setMessages('en_Boring', $enBoring);
$this->assertSame($enBoring, $translator->getMessages('en_Boring'));
$messages = $translator->getMessages();
$this->assertArrayHasKey('en', $messages);
$this->assertArrayHasKey('en_Boring', $messages);
$this->assertSame($enBoring, $messages['en_Boring']);
Carbon::setLocale('en_Boring');
$this->assertSame('en_Boring', Carbon::getLocale());
$diff = Carbon::create(2018, 1, 1, 0, 0, 0)
->diffForHumans(Carbon::create(2018, 1, 4, 4, 0, 0), true, false, 2);
// en_Boring inherit en because it starts with "en", see symfony-translation behavior
$this->assertSame('3 boring days 4 hours', $diff);
Carbon::setLocale('en');
$diff = Carbon::parse('2018-01-01')
->diffForHumans('2018-01-04 04:00', [
'syntax' => CarbonInterface::DIFF_ABSOLUTE,
'parts' => 2,
'locale' => 'de',
]);
$this->assertSame('3 Tage 4 Stunden', $diff);
$translator->resetMessages();
$diff = Carbon::parse('2018-01-01')
->diffForHumans('2018-01-04 04:00', [
'syntax' => CarbonInterface::DIFF_ABSOLUTE,
'parts' => 2,
'locale' => 'de',
]);
$this->assertSame('3 Tage 4 Stunden', $diff);
$this->assertSame([], $translator->getMessages());
$this->assertSame('en', Carbon::getLocale());
}
public function testLocaleOption()
{
$translator = Translator::get('en_Boring');
$translator->setTranslations([
'day' => ':count boring day|:count boring days',
]);
$diff = Carbon::parse('2018-01-01')
->diffForHumans('2018-01-04 04:00', [
'syntax' => CarbonInterface::DIFF_ABSOLUTE,
'parts' => 2,
'locale' => 'en_Boring',
]);
$translator->setLocale('en');
$translator->resetMessages();
$this->assertSame('3 boring days 4 hours', $diff);
}
public function testCustomWeekStart()
{
Carbon::setLocale('ru');
/** @var Translator $translator */
$translator = Carbon::getTranslator();
$translator->setMessages('ru', [
'first_day_of_week' => 1,
]);
$calendar = Carbon::parse('2018-07-07 00:00:00')->addDays(3)->calendar(Carbon::parse('2018-07-07 00:00:00'));
$this->assertSame('В следующий вторник, в 0:00', $calendar);
$calendar = Carbon::parse('2018-07-12 00:00:00')->addDays(3)->calendar(Carbon::parse('2018-07-12 00:00:00'));
$this->assertSame('В воскресенье, в 0:00', $calendar);
$translator->setMessages('ru', [
'first_day_of_week' => 5,
]);
$calendar = Carbon::parse('2018-07-07 00:00:00')->addDays(3)->calendar(Carbon::parse('2018-07-07 00:00:00'));
$this->assertSame('Во вторник, в 0:00', $calendar);
$calendar = Carbon::parse('2018-07-12 00:00:00')->addDays(3)->calendar(Carbon::parse('2018-07-12 00:00:00'));
$this->assertSame('В следующее воскресенье, в 0:00', $calendar);
$translator->resetMessages('ru');
Carbon::setLocale('en');
}
public function testAddAndRemoveDirectory()
{
$directory = sys_get_temp_dir().'/carbon'.mt_rand(0, 9999999);
mkdir($directory);
copy(__DIR__.'/../../src/Carbon/Lang/fr.php', "$directory/foo.php");
copy(__DIR__.'/../../src/Carbon/Lang/fr.php', "$directory/bar.php");
/** @var Translator $translator */
$translator = Carbon::getTranslator();
Carbon::setLocale('en');
Carbon::setLocale('foo');
$this->assertSame('Saturday', Carbon::parse('2018-07-07 00:00:00')->isoFormat('dddd'));
$translator->addDirectory($directory);
Carbon::setLocale('foo');
$this->assertSame('samedi', Carbon::parse('2018-07-07 00:00:00')->isoFormat('dddd'));
Carbon::setLocale('en');
$translator->removeDirectory($directory);
Carbon::setLocale('bar');
$this->assertSame('Saturday', Carbon::parse('2018-07-07 00:00:00')->isoFormat('dddd'));
Carbon::setLocale('foo');
$this->assertSame('samedi', Carbon::parse('2018-07-07 00:00:00')->isoFormat('dddd'));
Carbon::setLocale('en');
}
public function testLocaleHasShortUnits()
{
$withShortUnit = [
'year' => 'foo',
'y' => 'bar',
];
$withShortHourOnly = [
'year' => 'foo',
'y' => 'foo',
'day' => 'foo',
'd' => 'foo',
'hour' => 'foo',
'h' => 'bar',
];
$withoutShortUnit = [
'year' => 'foo',
];
$withSameShortUnit = [
'year' => 'foo',
'y' => 'foo',
];
$withShortHourOnlyLocale = 'zz_'.ucfirst(strtolower('withShortHourOnly'));
$withShortUnitLocale = 'zz_'.ucfirst(strtolower('withShortUnit'));
$withoutShortUnitLocale = 'zz_'.ucfirst(strtolower('withoutShortUnit'));
$withSameShortUnitLocale = 'zz_'.ucfirst(strtolower('withSameShortUnit'));
/** @var Translator $translator */
$translator = Carbon::getTranslator();
$translator->setMessages($withShortUnitLocale, $withShortUnit);
$translator->setMessages($withShortHourOnlyLocale, $withShortHourOnly);
$translator->setMessages($withoutShortUnitLocale, $withoutShortUnit);
$translator->setMessages($withSameShortUnitLocale, $withSameShortUnit);
$this->assertTrue(Carbon::localeHasShortUnits($withShortUnitLocale));
$this->assertTrue(Carbon::localeHasShortUnits($withShortHourOnlyLocale));
$this->assertFalse(Carbon::localeHasShortUnits($withoutShortUnitLocale));
$this->assertFalse(Carbon::localeHasShortUnits($withSameShortUnitLocale));
}
public function testLocaleHasDiffSyntax()
{
$withDiffSyntax = [
'year' => 'foo',
'ago' => ':time ago',
'from_now' => ':time from now',
'after' => ':time after',
'before' => ':time before',
];
$withoutDiffSyntax = [
'year' => 'foo',
];
$withDiffSyntaxLocale = 'zz_'.ucfirst(strtolower('withDiffSyntax'));
$withoutDiffSyntaxLocale = 'zz_'.ucfirst(strtolower('withoutDiffSyntax'));
/** @var Translator $translator */
$translator = Carbon::getTranslator();
$translator->setMessages($withDiffSyntaxLocale, $withDiffSyntax);
$translator->setMessages($withoutDiffSyntaxLocale, $withoutDiffSyntax);
$this->assertTrue(Carbon::localeHasDiffSyntax($withDiffSyntaxLocale));
$this->assertFalse(Carbon::localeHasDiffSyntax($withoutDiffSyntaxLocale));
$this->assertTrue(Carbon::localeHasDiffSyntax('ka'));
$this->assertFalse(Carbon::localeHasDiffSyntax('foobar'));
}
public function testLocaleHasDiffOneDayWords()
{
$withOneDayWords = [
'year' => 'foo',
'diff_now' => 'just now',
'diff_yesterday' => 'yesterday',
'diff_tomorrow' => 'tomorrow',
];
$withoutOneDayWords = [
'year' => 'foo',
];
$withOneDayWordsLocale = 'zz_'.ucfirst(strtolower('withOneDayWords'));
$withoutOneDayWordsLocale = 'zz_'.ucfirst(strtolower('withoutOneDayWords'));
/** @var Translator $translator */
$translator = Carbon::getTranslator();
$translator->setMessages($withOneDayWordsLocale, $withOneDayWords);
$translator->setMessages($withoutOneDayWordsLocale, $withoutOneDayWords);
$this->assertTrue(Carbon::localeHasDiffOneDayWords($withOneDayWordsLocale));
$this->assertFalse(Carbon::localeHasDiffOneDayWords($withoutOneDayWordsLocale));
}
public function testLocaleHasDiffTwoDayWords()
{
$withTwoDayWords = [
'year' => 'foo',
'diff_before_yesterday' => 'before yesterday',
'diff_after_tomorrow' => 'after tomorrow',
];
$withoutTwoDayWords = [
'year' => 'foo',
];
$withTwoDayWordsLocale = 'zz_'.ucfirst(strtolower('withTwoDayWords'));
$withoutTwoDayWordsLocale = 'zz_'.ucfirst(strtolower('withoutTwoDayWords'));
/** @var Translator $translator */
$translator = Carbon::getTranslator();
$translator->setMessages($withTwoDayWordsLocale, $withTwoDayWords);
$translator->setMessages($withoutTwoDayWordsLocale, $withoutTwoDayWords);
$this->assertTrue(Carbon::localeHasDiffTwoDayWords($withTwoDayWordsLocale));
$this->assertFalse(Carbon::localeHasDiffTwoDayWords($withoutTwoDayWordsLocale));
}
public function testLocaleHasPeriodSyntax()
{
$withPeriodSyntax = [
'year' => 'foo',
'period_recurrences' => 'once|%count% times',
'period_interval' => 'every :interval',
'period_start_date' => 'from :date',
'period_end_date' => 'to :date',
];
$withoutPeriodSyntax = [
'year' => 'foo',
];
$withPeriodSyntaxLocale = 'zz_'.ucfirst(strtolower('withPeriodSyntax'));
$withoutPeriodSyntaxLocale = 'zz_'.ucfirst(strtolower('withoutPeriodSyntax'));
/** @var Translator $translator */
$translator = Carbon::getTranslator();
$translator->setMessages($withPeriodSyntaxLocale, $withPeriodSyntax);
$translator->setMessages($withoutPeriodSyntaxLocale, $withoutPeriodSyntax);
$this->assertTrue(Carbon::localeHasPeriodSyntax($withPeriodSyntaxLocale));
$this->assertFalse(Carbon::localeHasPeriodSyntax($withoutPeriodSyntaxLocale));
$this->assertTrue(Carbon::localeHasPeriodSyntax('nl'));
}
public function testGetAvailableLocales()
{
$this->assertCount(\count(glob(__DIR__.'/../../src/Carbon/Lang/*.php')), Carbon::getAvailableLocales());
/** @var Translator $translator */
$translator = Carbon::getTranslator();
$translator->setMessages('zz_ZZ', []);
$this->assertContains('zz_ZZ', Carbon::getAvailableLocales());
Carbon::setTranslator(new SymfonyTranslator('en'));
$this->assertSame(['en'], Carbon::getAvailableLocales());
}
public function testGetAvailableLocalesInfo()
{
$infos = Carbon::getAvailableLocalesInfo();
$this->assertCount(\count(Carbon::getAvailableLocales()), Carbon::getAvailableLocalesInfo());
$this->assertArrayHasKey('en', $infos);
$this->assertInstanceOf(Language::class, $infos['en']);
$this->assertSame('English', $infos['en']->getIsoName());
}
public function testGeorgianSpecialFromNowTranslation()
{
$diff = Carbon::now()->locale('ka')->addWeeks(3)->diffForHumans();
$this->assertSame('3 კვირაში', $diff);
}
public function testSinhaleseSpecialAfterTranslation()
{
$diff = Carbon::now()->locale('si')->addDays(3)->diffForHumans(Carbon::now());
$this->assertSame('දින 3 න්', $diff);
}
public function testWeekDayMultipleForms()
{
$date = Carbon::parse('2018-10-10')->locale('ru');
$this->assertSame('в среду', $date->isoFormat('[в] dddd'));
$this->assertSame('среда, 10 октября 2018', $date->isoFormat('dddd, D MMMM YYYY'));
$this->assertSame('среда', $date->dayName);
$this->assertSame('ср', $date->isoFormat('dd'));
$date = Carbon::parse('2018-10-10')->locale('uk');
$this->assertSame('середа, 10', $date->isoFormat('dddd, D'));
$this->assertSame('в середу', $date->isoFormat('[в] dddd'));
$this->assertSame('минулої середи', $date->isoFormat('[минулої] dddd'));
}
public function testTranslationCustomWithCustomTranslator()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Translator does not implement Symfony\Contracts\Translation\TranslatorInterface '.
'and Symfony\Component\Translation\TranslatorBagInterface. '.
'Symfony\Component\Translation\IdentityTranslator has been given.',
));
$date = Carbon::create(2018, 1, 1, 0, 0, 0);
$date->setLocalTranslator(new IdentityTranslator());
$date->getTranslationMessage('foo');
}
public function testNoLocaleTranslator()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Tests\Carbon\Fixtures\NoLocaleTranslator does neither implements '.
'Symfony\Contracts\Translation\LocaleAwareInterface nor getLocale() method.',
);
$date = Carbon::create(2018, 1, 1, 0, 0, 0);
$date->setLocalTranslator(new NoLocaleTranslator());
$date->locale;
}
public function testTranslateTimeStringTo()
{
$date = Carbon::parse('2019-07-05')->locale('de');
$baseString = $date->isoFormat('LLLL');
$this->assertSame('Freitag, 5. Juli 2019 00:00', $baseString);
$this->assertSame('Friday, 5. July 2019 00:00', $date->translateTimeStringTo($baseString));
$this->assertSame('vendredi, 5. juillet 2019 00:00', $date->translateTimeStringTo($baseString, 'fr'));
}
public function testFallbackLocales()
{
// /!\ Used for backward compatibility, please avoid this method
// @see testMultiLocales() as preferred method
$myDialect = 'xx_MY_Dialect';
$secondChoice = 'xy_MY_Dialect';
$thirdChoice = 'it_CH';
/** @var Translator $translator */
$translator = Carbon::getTranslator();
$translator->setMessages($myDialect, [
'day' => ':count yub yub',
]);
$translator->setMessages($secondChoice, [
'day' => ':count buza',
'hour' => ':count ohto',
]);
Carbon::setLocale($myDialect);
$this->assertNull(Carbon::getFallbackLocale());
Carbon::setFallbackLocale($thirdChoice);
$this->assertSame($thirdChoice, Carbon::getFallbackLocale());
$this->assertSame('3 yub yub e 5 ora fa', Carbon::now()->subDays(3)->subHours(5)->ago([
'parts' => 2,
'join' => true,
]));
Carbon::setTranslator(new Translator('en'));
/** @var Translator $translator */
$translator = Carbon::getTranslator();
$translator->setMessages($myDialect, [
'day' => ':count yub yub',
]);
$translator->setMessages($secondChoice, [
'day' => ':count buza',
'hour' => ':count ohto',
]);
Carbon::setLocale($myDialect);
Carbon::setFallbackLocale($secondChoice);
Carbon::setFallbackLocale($thirdChoice);
$this->assertSame($thirdChoice, Carbon::getFallbackLocale());
$this->assertSame('3 yub yub e 5 ohto fa', Carbon::now()->subDays(3)->subHours(5)->ago([
'parts' => 2,
'join' => true,
]));
Carbon::setTranslator(new IdentityTranslator());
$this->assertNull(Carbon::getFallbackLocale());
Carbon::setTranslator(new Translator('en'));
}
public function testMultiLocales()
{
$myDialect = 'xx_MY_Dialect';
$secondChoice = 'xy_MY_Dialect';
$thirdChoice = 'it_CH';
Translator::get($myDialect)->setTranslations([
'day' => ':count yub yub',
]);
Translator::get($secondChoice)->setTranslations([
'day' => ':count buza',
'hour' => ':count ohto',
]);
$date = Carbon::now()->subDays(3)->subHours(5)->locale($myDialect, $secondChoice, $thirdChoice);
$this->assertSame('3 yub yub e 5 ohto fa', $date->ago([
'parts' => 2,
'join' => true,
]));
}
public function testStandAloneMonthsInLLLFormat()
{
$this->assertSame(
'29 февраля 2020 г., 12:24',
Carbon::parse('2020-02-29 12:24:00')->locale('ru_RU')->isoFormat('LLL'),
'Use "months" for date formatting',
);
}
public function testStandAloneMonthName()
{
$this->assertSame(
'февраль',
Carbon::parse('2020-02-29 12:24:00')->locale('ru_RU')->monthName,
'Use "months_standalone" the month alone',
);
}
public function testShortMonthNameInFormat()
{
$this->assertSame(
'29. мая',
Carbon::parse('2020-05-29 12:24:00')->locale('ru_RU')->isoFormat('D. MMM'),
'Use "months_short" for date formatting',
);
$this->assertSame(
'май',
Carbon::parse('2020-05-29 12:24:00')->locale('ru_RU')->isoFormat('MMM'),
'Use "months_short" for date formatting',
);
}
public function testStandAloneShortMonthName()
{
$this->assertSame(
'май',
Carbon::parse('2020-05-29 12:24:00')->locale('ru_RU')->shortMonthName,
'Use "months_short_standalone" the month alone',
);
}
public function testAgoDeclension()
{
$this->assertSame(
'година',
CarbonInterval::hour()->locale('uk')->forHumans(['aUnit' => true]),
);
$this->assertSame(
'годину тому',
Carbon::now()->subHour()->locale('uk')->diffForHumans(['aUnit' => true]),
);
}
public function testAustriaGermanJanuary()
{
$this->assertSame(
'Jänner',
Carbon::parse('2020-01-15')->locale('de_AT')->monthName,
);
$this->assertSame(
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | true |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/StrictModeTest.php | tests/Carbon/StrictModeTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use BadMethodCallException;
use Carbon\Carbon;
use InvalidArgumentException;
use Tests\AbstractTestCase;
class StrictModeTest extends AbstractTestCase
{
public function testSafeCreateDateTimeZoneWithStrictMode1()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Invalid offset timezone -15',
));
Carbon::createFromDate(2001, 1, 1, -15);
}
public function testSafeCreateDateTimeZoneWithStrictMode2()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Unknown or bad timezone (foobar)',
));
Carbon::createFromDate(2001, 1, 1, 'foobar');
}
public function testSetWithStrictMode()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Unknown setter \'foobar\'',
));
/** @var mixed $date */
$date = Carbon::now();
$date->foobar = 'biz';
}
public function testGetWithStrictMode()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Unknown getter \'foobar\'',
));
/** @var mixed $date */
$date = Carbon::now();
$date->foobar;
}
public function testSetAndGetWithoutStrictMode()
{
Carbon::useStrictMode(false);
/** @var mixed $date */
$date = Carbon::now();
@$date->foobar = 'biz';
$this->assertSame('biz', $date->foobar);
}
public function testIsSameUnitWithStrictMode()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Bad comparison unit: \'foobar\'',
));
Carbon::now()->isSameUnit('foobar', 'now');
}
public function testIsSameUnitWithoutStrictMode()
{
Carbon::useStrictMode(false);
$this->assertFalse(Carbon::now()->isSameUnit('foobar', 'now'));
}
public function testAddRealUnitWithStrictMode()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Invalid unit for real timestamp add/sub: \'foobar\'',
));
Carbon::now()->addRealUnit('foobar');
}
public function testAddRealUnitWithoutStrictMode()
{
Carbon::useStrictMode(false);
$d = Carbon::create(2000, 1, 2, 3, 4, 5)->addRealUnit('foobar');
$this->assertCarbon($d, 2000, 1, 2, 3, 4, 5);
}
public function testCallWithStrictMode()
{
$this->expectExceptionObject(new BadMethodCallException(
'Method foobar does not exist.',
));
/** @var mixed $date */
$date = Carbon::now();
$date->foobar();
}
public function testCallWithoutStrictMode()
{
Carbon::useStrictMode(false);
/** @var mixed $date */
$date = Carbon::now();
$this->assertNull($date->foobar());
}
public function testStaticCallWithStrictMode()
{
$this->expectExceptionObject(new BadMethodCallException(
'Method Carbon\Carbon::foobar does not exist.',
));
Carbon::foobar();
}
public function testStaticCallWithoutStrictMode()
{
Carbon::useStrictMode(false);
$this->assertNull(Carbon::foobar());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/ConstructTest.php | tests/Carbon/ConstructTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\Exceptions\InvalidTimeZoneException;
use DateTime;
use DateTimeInterface;
use DateTimeZone;
use SubCarbon;
use Tests\AbstractTestCase;
class ConstructTest extends AbstractTestCase
{
public function testCreatesAnInstanceDefaultToNow()
{
$c = new Carbon();
$now = Carbon::now();
$this->assertInstanceOfCarbon($c);
$this->assertInstanceOf(DateTime::class, $c);
$this->assertInstanceOf(DateTimeInterface::class, $c);
$this->assertSame($now->tzName, $c->tzName);
$this->assertCarbon($c, $now->year, $now->month, $now->day, $now->hour, $now->minute, $now->second);
}
public function testCreatesAnInstanceFromADateTime()
{
$c = new Carbon(Carbon::parse('2009-09-09 09:09:09'));
$this->assertSame('2009-09-09 09:09:09 America/Toronto', $c->format('Y-m-d H:i:s e'));
$c = new Carbon(new DateTime('2009-09-09 09:09:09'));
$this->assertSame('2009-09-09 09:09:09 America/Toronto', $c->format('Y-m-d H:i:s e'));
$c = new Carbon(new DateTime('2009-09-09 09:09:09', new DateTimeZone('Europe/Paris')));
$this->assertSame('2009-09-09 09:09:09 Europe/Paris', $c->format('Y-m-d H:i:s e'));
$c = new Carbon(new DateTime('2009-09-09 09:09:09'), 'Europe/Paris');
$this->assertSame('2009-09-09 15:09:09 Europe/Paris', $c->format('Y-m-d H:i:s e'));
$c = new Carbon(new DateTime('2009-09-09 09:09:09', new DateTimeZone('Asia/Tokyo')), 'Europe/Paris');
$this->assertSame('2009-09-09 02:09:09 Europe/Paris', $c->format('Y-m-d H:i:s e'));
}
public function testCreatesAnInstanceFromADateTimeException()
{
$this->expectException(InvalidTimeZoneException::class);
Carbon::useStrictMode(false);
new Carbon(
new DateTime('2009-09-09 09:09:09', new DateTimeZone('Asia/Tokyo')),
'¤¤ Incorrect Timezone ¤¤',
);
}
public function testParseWithEmptyStringCreatesAnInstanceDefaultToNow()
{
$c = Carbon::parse('');
$now = Carbon::now();
$this->assertInstanceOfCarbon($c);
$this->assertSame($now->tzName, $c->tzName);
$this->assertCarbon($c, $now->year, $now->month, $now->day, $now->hour, $now->minute, $now->second);
$c = new Carbon('');
$now = Carbon::now();
$this->assertInstanceOfCarbon($c);
$this->assertSame($now->tzName, $c->tzName);
$this->assertCarbon($c, $now->year, $now->month, $now->day, $now->hour, $now->minute, $now->second);
}
public function testParseZeroCreatesAnInstanceDefaultToUnixAreaStartUtc()
{
$c = Carbon::parse(0);
$now = Carbon::createFromTimestamp(0, '+00:00');
$this->assertInstanceOfCarbon($c);
$this->assertSame($now->tzName, $c->tzName);
$this->assertCarbon($c, $now->year, $now->month, $now->day, $now->hour, $now->minute, $now->second);
$c = new Carbon(0);
$now = Carbon::createFromTimestamp(0, '+00:00');
$this->assertInstanceOfCarbon($c);
$this->assertSame($now->tzName, $c->tzName);
$this->assertCarbon($c, $now->year, $now->month, $now->day, $now->hour, $now->minute, $now->second);
}
public function testWithFancyString()
{
Carbon::setTestNowAndTimezone(Carbon::today());
$c = new Carbon('first day of January 2008');
$this->assertCarbon($c, 2008, 1, 1, 0, 0, 0);
}
public function testParseWithFancyString()
{
Carbon::setTestNowAndTimezone(Carbon::today());
$c = Carbon::parse('first day of January 2008');
$this->assertCarbon($c, 2008, 1, 1, 0, 0, 0);
}
public function testParseWithYYYMMDD()
{
$c = Carbon::parse('20201128');
$this->assertCarbon($c, 2020, 11, 28, 0, 0, 0);
}
public function testParseWithYYYMMDDHHMMSS()
{
$c = Carbon::parse('20201128192533');
$this->assertCarbon($c, 2020, 11, 28, 19, 25, 33);
}
public function testDefaultTimezone()
{
$c = new Carbon('now');
$this->assertSame('America/Toronto', $c->tzName);
}
public function testParseWithDefaultTimezone()
{
$c = Carbon::parse('now');
$this->assertSame('America/Toronto', $c->tzName);
}
public function testSettingTimezone()
{
$timezone = 'Europe/London';
$dtz = new DateTimeZone($timezone);
$dt = new DateTime('now', $dtz);
$dayLightSavingTimeOffset = (int) $dt->format('I');
$c = new Carbon('now', $dtz);
$this->assertSame($timezone, $c->tzName);
$this->assertSame($dayLightSavingTimeOffset, $c->offsetHours);
}
public function testParseSettingTimezone()
{
$timezone = 'Europe/London';
$dtz = new DateTimeZone($timezone);
$dt = new DateTime('now', $dtz);
$dayLightSavingTimeOffset = (int) $dt->format('I');
$c = Carbon::parse('now', $dtz);
$this->assertSame($timezone, $c->tzName);
$this->assertSame($dayLightSavingTimeOffset, $c->offsetHours);
}
public function testSettingTimezoneWithString()
{
$timezone = 'Asia/Tokyo';
$dtz = new DateTimeZone($timezone);
$dt = new DateTime('now', $dtz);
$dayLightSavingTimeOffset = (int) $dt->format('I');
$c = new Carbon('now', $timezone);
$this->assertSame($timezone, $c->tzName);
$this->assertSame(9 + $dayLightSavingTimeOffset, $c->offsetHours);
}
public function testParseSettingTimezoneWithString()
{
$timezone = 'Asia/Tokyo';
$dtz = new DateTimeZone($timezone);
$dt = new DateTime('now', $dtz);
$dayLightSavingTimeOffset = (int) $dt->format('I');
$c = Carbon::parse('now', $timezone);
$this->assertSame($timezone, $c->tzName);
$this->assertSame(9 + $dayLightSavingTimeOffset, $c->offsetHours);
}
public function testSettingTimezoneWithInteger()
{
Carbon::useStrictMode(false);
$timezone = 5;
$c = new Carbon('2019-02-12 23:00:00', $timezone);
$this->assertSame('+05:00', $c->tzName);
}
public function testMockingWithMicroseconds()
{
$c = new Carbon(Carbon::now()->toDateTimeString().'.123456');
Carbon::setTestNow($c);
$mockedC = Carbon::now();
$this->assertTrue($c->eq($mockedC));
Carbon::setTestNow();
}
public function testTimestamp()
{
$date = new Carbon(1367186296);
$this->assertSame('Sunday 28 April 2013 21:58:16.000000', $date->format('l j F Y H:i:s.u'));
$date = new Carbon(123);
$this->assertSame('Thursday 1 January 1970 00:02:03.000000', $date->format('l j F Y H:i:s.u'));
}
public function testFloatTimestamp()
{
$date = new Carbon(1367186296.654321);
$this->assertSame('Sunday 28 April 2013 21:58:16.654321', $date->format('l j F Y H:i:s.u'));
$date = new Carbon(123.5);
$this->assertSame('Thursday 1 January 1970 00:02:03.500000', $date->format('l j F Y H:i:s.u'));
}
public function testDifferentType()
{
require_once __DIR__.'/../Fixtures/SubCarbon.php';
$subCarbon = new SubCarbon('2024-01-24 00:00');
$carbon = new Carbon('2024-01-24 00:00');
$this->assertTrue($subCarbon->equalTo($carbon));
$this->assertTrue($carbon->equalTo($subCarbon));
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/StringsTest.php | tests/Carbon/StringsTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\CarbonInterface;
use Carbon\Factory;
use DateTime;
use InvalidArgumentException;
use Tests\AbstractTestCase;
use Tests\Carbon\Fixtures\BadIsoCarbon;
use Tests\Carbon\Fixtures\MyCarbon;
class StringsTest extends AbstractTestCase
{
public function testToStringCast()
{
$d = Carbon::now();
$this->assertSame(Carbon::now()->toDateTimeString(), ''.$d);
}
public function testToString()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('Thu Dec 25 1975 14:15:16 GMT-0500', $d->toString());
}
public function testToISOString()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('1975-12-25T19:15:16.000000Z', $d->toISOString());
$d = Carbon::create(21975, 12, 25, 14, 15, 16);
$this->assertSame('+021975-12-25T19:15:16.000000Z', $d->toISOString());
$d = Carbon::create(-75, 12, 25, 14, 15, 16);
$this->assertStringStartsWith('-000075-', $d->toISOString());
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('1975-12-25T14:15:16.000000-05:00', $d->toISOString(true));
$d = Carbon::create(21975, 12, 25, 14, 15, 16);
$this->assertSame('+021975-12-25T14:15:16.000000-05:00', $d->toISOString(true));
$d = Carbon::create(-75, 12, 25, 14, 15, 16);
$this->assertStringStartsWith('-000075-', $d->toISOString(true));
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('1975-12-25T19:15:16.000000Z', $d->toJSON());
$d = Carbon::create(21975, 12, 25, 14, 15, 16);
$this->assertSame('+021975-12-25T19:15:16.000000Z', $d->toJSON());
$d = Carbon::create(-75, 12, 25, 14, 15, 16);
$this->assertStringStartsWith('-000075-', $d->toJSON());
$d = Carbon::create(0);
$this->assertNull($d->toISOString());
}
public function testSetToStringFormatString()
{
Carbon::setToStringFormat('jS \o\f F, Y g:i:s a');
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('25th of December, 1975 2:15:16 pm', ''.$d);
}
public function testSetToStringFormatClosure()
{
Carbon::setToStringFormat(function (CarbonInterface $d) {
$format = $d->year === 1976 ?
'jS \o\f F g:i:s a' :
'jS \o\f F, Y g:i:s a';
return $d->format($format);
});
$d = Carbon::create(1976, 12, 25, 14, 15, 16);
$this->assertSame('25th of December 2:15:16 pm', ''.$d);
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('25th of December, 1975 2:15:16 pm', ''.$d);
}
public function testSetToStringFormatViaSettings()
{
$factory = new Factory([
'toStringFormat' => function (CarbonInterface $d) {
return $d->isoFormat('dddd');
},
]);
$d = $factory->create(1976, 12, 25, 14, 15, 16);
$this->assertSame('Saturday', ''.$d);
}
public function testResetToStringFormat()
{
$d = Carbon::now();
Carbon::setToStringFormat('123');
Carbon::resetToStringFormat();
$this->assertSame($d->toDateTimeString(), ''.$d);
}
public function testExtendedClassToString()
{
$d = MyCarbon::now();
$this->assertSame($d->toDateTimeString(), ''.$d);
}
public function testToDateString()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('1975-12-25', $d->toDateString());
}
public function testToDateTimeLocalString()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16.615342);
$this->assertSame('1975-12-25T14:15:16', $d->toDateTimeLocalString());
$this->assertSame('1975-12-25T14:15', $d->toDateTimeLocalString('minute'));
$this->assertSame('1975-12-25T14:15:16', $d->toDateTimeLocalString('second'));
$this->assertSame('1975-12-25T14:15:16.615', $d->toDateTimeLocalString('millisecond'));
$this->assertSame('1975-12-25T14:15:16.615342', $d->toDateTimeLocalString('µs'));
$message = null;
try {
$d->toDateTimeLocalString('hour');
} catch (InvalidArgumentException $exception) {
$message = $exception->getMessage();
}
$this->assertSame('Precision unit expected among: minute, second, millisecond and microsecond.', $message);
}
public function testToFormattedDateString()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('Dec 25, 1975', $d->toFormattedDateString());
}
public function testToTimeString()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('14:15:16', $d->toTimeString());
}
public function testToDateTimeString()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('1975-12-25 14:15:16', $d->toDateTimeString());
}
public function testToDateTimeStringWithPaddedZeroes()
{
$d = Carbon::create(2000, 5, 2, 4, 3, 4);
$this->assertSame('2000-05-02 04:03:04', $d->toDateTimeString());
}
public function testToDayDateTimeString()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('Thu, Dec 25, 1975 2:15 PM', $d->toDayDateTimeString());
}
public function testToDayDateString()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('Thu, Dec 25, 1975', $d->toFormattedDayDateString());
}
public function testToAtomString()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('1975-12-25T14:15:16-05:00', $d->toAtomString());
}
public function testToCOOKIEString()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame(
DateTime::COOKIE === 'l, d-M-y H:i:s T'
? 'Thursday, 25-Dec-75 14:15:16 EST'
: 'Thursday, 25-Dec-1975 14:15:16 EST',
$d->toCookieString(),
);
}
public function testToIso8601String()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('1975-12-25T14:15:16-05:00', $d->toIso8601String());
}
public function testToIso8601ZuluString()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('1975-12-25T19:15:16Z', $d->toIso8601ZuluString());
}
public function testToRC822String()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('Thu, 25 Dec 75 14:15:16 -0500', $d->toRfc822String());
}
public function testToRfc850String()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('Thursday, 25-Dec-75 14:15:16 EST', $d->toRfc850String());
}
public function testToRfc1036String()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('Thu, 25 Dec 75 14:15:16 -0500', $d->toRfc1036String());
}
public function testToRfc1123String()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('Thu, 25 Dec 1975 14:15:16 -0500', $d->toRfc1123String());
}
public function testToRfc2822String()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('Thu, 25 Dec 1975 14:15:16 -0500', $d->toRfc2822String());
}
public function testToRfc3339String()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('1975-12-25T14:15:16-05:00', $d->toRfc3339String());
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('1975-12-25T14:15:16.000-05:00', $d->toRfc3339String(true));
}
public function testToRssString()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('Thu, 25 Dec 1975 14:15:16 -0500', $d->toRssString());
}
public function testToW3cString()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('1975-12-25T14:15:16-05:00', $d->toW3cString());
}
public function testToRfc7231String()
{
$d = Carbon::create(1975, 12, 25, 14, 15, 16, 'GMT');
$this->assertSame('Thu, 25 Dec 1975 14:15:16 GMT', $d->toRfc7231String());
$d = Carbon::create(1975, 12, 25, 14, 15, 16);
$this->assertSame('Thu, 25 Dec 1975 19:15:16 GMT', $d->toRfc7231String());
}
public function testIsoFormat()
{
$d = Carbon::parse('midnight');
$this->assertSame('24', $d->isoFormat('k'));
$d = Carbon::parse('2017-01-01');
$this->assertSame('2017', $d->isoFormat('g'));
$this->assertSame('2017', $d->locale('en_US')->isoFormat('g'));
$this->assertSame('2016', $d->locale('fr')->isoFormat('g'));
$this->assertSame('2016', $d->isoFormat('G'));
$this->assertSame('2016', $d->locale('en_US')->isoFormat('G'));
$this->assertSame('2016', $d->locale('fr')->isoFormat('G'));
$d = Carbon::parse('2015-12-31');
$this->assertSame('2016', $d->isoFormat('g'));
$this->assertSame('2016', $d->locale('en_US')->isoFormat('g'));
$this->assertSame('2015', $d->locale('fr')->isoFormat('g'));
$this->assertSame('2015', $d->isoFormat('G'));
$this->assertSame('2015', $d->locale('en_US')->isoFormat('G'));
$this->assertSame('2015', $d->locale('fr')->isoFormat('G'));
$d = Carbon::parse('2017-01-01 22:25:24.182937');
$this->assertSame('1 18 182 1829 18293 182937 1829370 18293700 182937000', $d->isoFormat('S SS SSS SSSS SSSSS SSSSSS SSSSSSS SSSSSSSS SSSSSSSSS'));
$this->assertSame('02017 +002017', $d->isoFormat('YYYYY YYYYYY'));
$this->assertSame(-117, Carbon::create(-117, 1, 1)->year);
$this->assertSame('-00117 -000117', Carbon::create(-117, 1, 1)->isoFormat('YYYYY YYYYYY'));
$this->assertSame('M01', $d->isoFormat('\\MMM'));
$this->assertSame('Jan', $d->isoFormat('MMM'));
$this->assertSame('janv.', $d->locale('fr')->isoFormat('MMM'));
$this->assertSame('ene.', $d->locale('es')->isoFormat('MMM'));
$this->assertSame('1 de enero de 2017', $d->locale('es')->isoFormat('LL'));
$this->assertSame('1 de ene. de 2017', $d->locale('es')->isoFormat('ll'));
$this->assertSame('1st', Carbon::parse('2018-06-01')->isoFormat('Do'));
$this->assertSame('11th', Carbon::parse('2018-06-11')->isoFormat('Do'));
$this->assertSame('21st', Carbon::parse('2018-06-21')->isoFormat('Do'));
$this->assertSame('15th', Carbon::parse('2018-06-15')->isoFormat('Do'));
}
public function testBadIsoFormat()
{
$d = BadIsoCarbon::parse('midnight');
$this->assertSame('', $d->isoFormat('MMM'));
}
public function testTranslatedFormat()
{
$this->assertSame('1st', Carbon::parse('01-01-01')->translatedFormat('jS'));
$this->assertSame('1er', Carbon::parse('01-01-01')->locale('fr')->translatedFormat('jS'));
$this->assertSame('31 мая', Carbon::parse('2019-05-15')->locale('ru')->translatedFormat('t F'));
$this->assertSame('5 май', Carbon::parse('2019-05-15')->locale('ru')->translatedFormat('n F'));
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/CreateStrictTest.php | tests/Carbon/CreateStrictTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\Exceptions\OutOfRangeException;
use Tests\AbstractTestCase;
use TypeError;
class CreateStrictTest extends AbstractTestCase
{
public function testCreateStrictThrowsExceptionForSecondLowerThanZero()
{
$this->expectExceptionObject(new OutOfRangeException('second', 0, 99, -1));
Carbon::createStrict(null, null, null, null, null, -1);
}
public function testCreateStrictThrowsExceptionForMonthOverRange()
{
$this->expectExceptionObject(new OutOfRangeException('month', 0, 99, 9001));
Carbon::createStrict(null, 9001);
}
public function testCreateStrictDoesNotAllowFormatString()
{
$this->expectException(TypeError::class);
Carbon::createStrict('2021-05-25', 'Y-m-d');
}
public function testCreateStrictResetsStrictModeOnSuccess()
{
Carbon::useStrictMode(false);
$this->assertInstanceOfCarbon(Carbon::createStrict());
$this->assertFalse(Carbon::isStrictModeEnabled());
}
public function testCreateStrictResetsStrictModeOnFailure()
{
Carbon::useStrictMode(false);
$exception = null;
try {
Carbon::createStrict(null, -1);
} catch (OutOfRangeException $e) {
$exception = $e;
}
$this->assertInstanceOf(OutOfRangeException::class, $exception);
$this->assertFalse(Carbon::isStrictModeEnabled());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/GenericMacroTest.php | tests/Carbon/GenericMacroTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use BadMethodCallException;
use Carbon\Carbon;
use Tests\AbstractTestCaseWithOldNow;
use Throwable;
class GenericMacroTest extends AbstractTestCaseWithOldNow
{
public function testGenericMacro()
{
Carbon::genericMacro(function ($method) {
$time = preg_replace('/[A-Z]/', ' $0', $method);
try {
return self::this()->modify($time);
} catch (Throwable $exception) {
if (preg_match('(Could not modify with|Failed to parse)', $exception->getMessage())) {
throw new BadMethodCallException('Try next macro', 0, $exception);
}
throw $exception;
}
});
/** @var mixed $now */
$now = Carbon::now();
$this->assertSame('2017-07-02', $now->nextSunday()->format('Y-m-d'));
$this->assertSame('2017-06-26', Carbon::lastMonday()->format('Y-m-d'));
$message = null;
try {
Carbon::fooBar();
} catch (BadMethodCallException $exception) {
$message = $exception->getMessage();
}
$this->assertSame('Method '.Carbon::class.'::fooBar does not exist.', $message);
$message = null;
try {
$now->barBiz();
} catch (BadMethodCallException $exception) {
$message = $exception->getMessage();
}
$this->assertSame('Method barBiz does not exist.', $message);
}
public function testGenericMacroPriority()
{
Carbon::genericMacro(function ($method) {
if (!str_starts_with($method, 'myPrefix')) {
throw new BadMethodCallException('Try next macro', 0);
}
return 'first';
});
Carbon::genericMacro(function ($method) {
if (!str_starts_with($method, 'myPrefix')) {
throw new BadMethodCallException('Try next macro', 0);
}
return 'second';
}, 1);
Carbon::genericMacro(function ($method) {
if (!str_starts_with($method, 'myPrefix')) {
throw new BadMethodCallException('Try next macro', 0);
}
return 'third';
}, -1);
Carbon::macro('myPrefixFooBar', function () {
return 'myPrefixFooBar';
});
/** @var mixed $now */
$now = Carbon::now();
$this->assertSame('second', $now->myPrefixSomething());
$this->assertSame('second', Carbon::myPrefixSomething());
$this->assertSame('myPrefixFooBar', $now->myPrefixFooBar());
$this->assertSame('myPrefixFooBar', Carbon::myPrefixFooBar());
}
public function testLocalGenericMacroPriority()
{
Carbon::genericMacro(function ($method) {
if (!str_starts_with($method, 'mlp')) {
throw new BadMethodCallException('Try next macro', 0);
}
return 'first';
});
Carbon::genericMacro(function ($method) {
if (!str_starts_with($method, 'mlp')) {
throw new BadMethodCallException('Try next macro', 0);
}
return 'second';
}, 1);
Carbon::genericMacro(function ($method) {
if (!str_starts_with($method, 'mlp')) {
throw new BadMethodCallException('Try next macro', 0);
}
return 'third';
}, -1);
Carbon::macro('mlpFooBar', function () {
return 'mlpFooBar';
});
/** @var mixed $date */
$date = Carbon::now()->settings([
'genericMacros' => [
function ($method) {
if (!str_starts_with($method, 'mlp')) {
throw new BadMethodCallException('Try next macro', 0);
}
return 'local-first';
},
function ($method) {
if (!str_starts_with($method, 'mlp')) {
throw new BadMethodCallException('Try next macro', 0);
}
return 'local-second';
},
],
]);
/** @var mixed $now */
$now = Carbon::now();
$this->assertSame('local-first', $date->mlpSomething());
$this->assertSame('second', $now->mlpSomething());
$this->assertSame('second', Carbon::mlpSomething());
$this->assertSame('mlpFooBar', $date->mlpFooBar());
$this->assertSame('mlpFooBar', $now->mlpFooBar());
$this->assertSame('mlpFooBar', Carbon::mlpFooBar());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/NowDerivativesTest.php | tests/Carbon/NowDerivativesTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Tests\AbstractTestCase;
class NowDerivativesTest extends AbstractTestCase
{
public function testNowWithSameTimezone()
{
$dt = Carbon::now('Europe/London');
$dt2 = $dt->nowWithSameTz();
$this->assertSame($dt2->toDateTimeString(), $dt->toDateTimeString());
$this->assertSame($dt2->tzName, $dt->tzName);
Carbon::setTestNow(new Carbon('2017-07-29T07:57:27.123456Z'));
$dt = Carbon::createFromTime(13, 40, 00, 'Africa/Asmara');
$dt2 = $dt->nowWithSameTz();
Carbon::setTestNow();
$this->assertSame($dt->format('H:i'), '13:40');
$this->assertSame($dt2->format('H:i'), '10:57');
$this->assertSame($dt2->tzName, $dt->tzName);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/ExpressiveComparisonTest.php | tests/Carbon/ExpressiveComparisonTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Tests\AbstractTestCase;
class ExpressiveComparisonTest extends AbstractTestCase
{
public function testEqualToTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 1)->equalTo(Carbon::createFromDate(2000, 1, 1)));
}
public function testEqualToFalse()
{
$this->assertFalse(Carbon::createFromDate(2000, 1, 1)->equalTo(Carbon::createFromDate(2000, 1, 2)));
}
public function testEqualWithTimezoneTrue()
{
$this->assertTrue(Carbon::create(2000, 1, 1, 12, 0, 0, 'America/Toronto')->equalTo(Carbon::create(2000, 1, 1, 9, 0, 0, 'America/Vancouver')));
}
public function testNotEqualToTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 1)->notEqualTo(Carbon::createFromDate(2000, 1, 2)));
}
public function testNotEqualToFalse()
{
$this->assertFalse(Carbon::createFromDate(2000, 1, 1)->notEqualTo(Carbon::createFromDate(2000, 1, 1)));
}
public function testGreaterThanTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 1)->greaterThan(Carbon::createFromDate(1999, 12, 31)));
$this->assertTrue(Carbon::createFromDate(2000, 1, 1)->isAfter(Carbon::createFromDate(1999, 12, 31)));
}
public function testGreaterThanFalse()
{
$this->assertFalse(Carbon::createFromDate(2000, 1, 1)->greaterThan(Carbon::createFromDate(2000, 1, 2)));
$this->assertFalse(Carbon::createFromDate(2000, 1, 1)->isAfter(Carbon::createFromDate(2000, 1, 2)));
}
public function testGreaterThanWithTimezoneTrue()
{
$dt1 = Carbon::create(2000, 1, 1, 12, 0, 0, 'America/Toronto');
$dt2 = Carbon::create(2000, 1, 1, 8, 59, 59, 'America/Vancouver');
$this->assertTrue($dt1->greaterThan($dt2));
}
public function testGreaterThanWithTimezoneFalse()
{
$dt1 = Carbon::create(2000, 1, 1, 12, 0, 0, 'America/Toronto');
$dt2 = Carbon::create(2000, 1, 1, 9, 0, 1, 'America/Vancouver');
$this->assertFalse($dt1->greaterThan($dt2));
}
public function testGreaterThanOrEqualTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 1)->greaterThanOrEqualTo(Carbon::createFromDate(1999, 12, 31)));
}
public function testGreaterThanOrEqualTrueEqual()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 1)->greaterThanOrEqualTo(Carbon::createFromDate(2000, 1, 1)));
}
public function testGreaterThanOrEqualFalse()
{
$this->assertFalse(Carbon::createFromDate(2000, 1, 1)->greaterThanOrEqualTo(Carbon::createFromDate(2000, 1, 2)));
}
public function testLessThanTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 1)->lessThan(Carbon::createFromDate(2000, 1, 2)));
$this->assertTrue(Carbon::createFromDate(2000, 1, 1)->isBefore(Carbon::createFromDate(2000, 1, 2)));
}
public function testLessThanFalse()
{
$this->assertFalse(Carbon::createFromDate(2000, 1, 1)->lessThan(Carbon::createFromDate(1999, 12, 31)));
$this->assertFalse(Carbon::createFromDate(2000, 1, 1)->isBefore(Carbon::createFromDate(1999, 12, 31)));
}
public function testLessThanOrEqualTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 1)->lessThanOrEqualTo(Carbon::createFromDate(2000, 1, 2)));
}
public function testLessThanOrEqualTrueEqual()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 1)->lessThanOrEqualTo(Carbon::createFromDate(2000, 1, 1)));
}
public function testLessThanOrEqualFalse()
{
$this->assertFalse(Carbon::createFromDate(2000, 1, 1)->lessThanOrEqualTo(Carbon::createFromDate(1999, 12, 31)));
}
public function testBetweenEqualTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->between(Carbon::createFromDate(2000, 1, 1), Carbon::createFromDate(2000, 1, 31), true));
}
public function testBetweenNotEqualTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->between(Carbon::createFromDate(2000, 1, 1), Carbon::createFromDate(2000, 1, 31), false));
}
public function testBetweenEqualFalse()
{
$this->assertFalse(Carbon::createFromDate(1999, 12, 31)->between(Carbon::createFromDate(2000, 1, 1), Carbon::createFromDate(2000, 1, 31), true));
}
public function testBetweenNotEqualFalse()
{
$this->assertFalse(Carbon::createFromDate(2000, 1, 1)->between(Carbon::createFromDate(2000, 1, 1), Carbon::createFromDate(2000, 1, 31), false));
}
public function testBetweenEqualSwitchTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->between(Carbon::createFromDate(2000, 1, 31), Carbon::createFromDate(2000, 1, 1), true));
}
public function testBetweenNotEqualSwitchTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->between(Carbon::createFromDate(2000, 1, 31), Carbon::createFromDate(2000, 1, 1), false));
}
public function testBetweenEqualSwitchFalse()
{
$this->assertFalse(Carbon::createFromDate(1999, 12, 31)->between(Carbon::createFromDate(2000, 1, 31), Carbon::createFromDate(2000, 1, 1), true));
}
public function testBetweenNotEqualSwitchFalse()
{
$this->assertFalse(Carbon::createFromDate(2000, 1, 1)->between(Carbon::createFromDate(2000, 1, 31), Carbon::createFromDate(2000, 1, 1), false));
}
public function testMinIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->minimum());
}
public function testMinWithNow()
{
$dt = Carbon::create(2012, 1, 1, 0, 0, 0)->minimum();
$this->assertCarbon($dt, 2012, 1, 1, 0, 0, 0);
}
public function testMinWithInstance()
{
$dt1 = Carbon::create(2013, 12, 31, 23, 59, 59);
$dt2 = Carbon::create(2012, 1, 1, 0, 0, 0)->minimum($dt1);
$this->assertCarbon($dt2, 2012, 1, 1, 0, 0, 0);
}
public function testMaxIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->maximum());
}
public function testMaxWithNow()
{
$dt = Carbon::create(2099, 12, 31, 23, 59, 59)->maximum();
$this->assertCarbon($dt, 2099, 12, 31, 23, 59, 59);
}
public function testMaxWithInstance()
{
$dt1 = Carbon::create(2012, 1, 1, 0, 0, 0);
$dt2 = Carbon::create(2099, 12, 31, 23, 59, 59)->maximum($dt1);
$this->assertCarbon($dt2, 2099, 12, 31, 23, 59, 59);
}
public function testIsBirthday()
{
$dt1 = Carbon::createFromDate(1987, 4, 23);
$dt2 = Carbon::createFromDate(2014, 9, 26);
$dt3 = Carbon::createFromDate(2014, 4, 23);
$this->assertFalse($dt2->isBirthday($dt1));
$this->assertTrue($dt3->isBirthday($dt1));
}
public function testIsLastOfMonth()
{
$dt1 = Carbon::createFromDate(2017, 1, 31);
$dt2 = Carbon::createFromDate(2016, 2, 28);
$dt3 = Carbon::createFromDate(2016, 2, 29);
$dt4 = Carbon::createFromDate(2018, 5, 5);
$this->assertTrue($dt1->isLastOfMonth());
$this->assertFalse($dt2->isLastOfMonth());
$this->assertTrue($dt3->isLastOfMonth());
$this->assertFalse($dt4->isLastOfMonth());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/ObjectsTest.php | tests/Carbon/ObjectsTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\CarbonInterface;
use DateTime;
use DateTimeImmutable;
use stdClass;
use Tests\AbstractTestCase;
class ObjectsTest extends AbstractTestCase
{
public function testToObject()
{
$dt = Carbon::now();
$dtToObject = $dt->toObject();
$this->assertInstanceOf(stdClass::class, $dtToObject);
$this->assertObjectHasProperty('year', $dtToObject);
$this->assertSame($dt->year, $dtToObject->year);
$this->assertObjectHasProperty('month', $dtToObject);
$this->assertSame($dt->month, $dtToObject->month);
$this->assertObjectHasProperty('day', $dtToObject);
$this->assertSame($dt->day, $dtToObject->day);
$this->assertObjectHasProperty('dayOfWeek', $dtToObject);
$this->assertSame($dt->dayOfWeek, $dtToObject->dayOfWeek);
$this->assertObjectHasProperty('dayOfYear', $dtToObject);
$this->assertSame($dt->dayOfYear, $dtToObject->dayOfYear);
$this->assertObjectHasProperty('hour', $dtToObject);
$this->assertSame($dt->hour, $dtToObject->hour);
$this->assertObjectHasProperty('minute', $dtToObject);
$this->assertSame($dt->minute, $dtToObject->minute);
$this->assertObjectHasProperty('second', $dtToObject);
$this->assertSame($dt->second, $dtToObject->second);
$this->assertObjectHasProperty('micro', $dtToObject);
$this->assertSame($dt->micro, $dtToObject->micro);
$this->assertObjectHasProperty('timestamp', $dtToObject);
$this->assertSame($dt->timestamp, $dtToObject->timestamp);
$this->assertObjectHasProperty('timezone', $dtToObject);
$this->assertEquals($dt->timezone, $dtToObject->timezone);
$this->assertObjectHasProperty('formatted', $dtToObject);
$this->assertSame($dt->format(Carbon::DEFAULT_TO_STRING_FORMAT), $dtToObject->formatted);
}
public function testToDateTime()
{
$dt = Carbon::create(2000, 3, 26);
$date = $dt->toDateTime();
$this->assertInstanceOf(DateTime::class, $date);
$this->assertNotInstanceOf(Carbon::class, $date);
$this->assertNotInstanceOf(CarbonInterface::class, $date);
$this->assertSame('2000-03-26', $date->format('Y-m-d'));
$date = $dt->toDate();
$this->assertInstanceOf(DateTime::class, $date);
$this->assertNotInstanceOf(Carbon::class, $date);
$this->assertNotInstanceOf(CarbonInterface::class, $date);
$this->assertSame('2000-03-26', $date->format('Y-m-d'));
// Check it keeps timezone offset during DST
$date = Carbon::create(2290, 11, 2, 1, 10, 10 + 888480 / 1000000, 'America/Toronto');
$this->assertSame(
'2290-11-02 01:10:10.888480 America/Toronto -0400',
$date->toDateTime()->format('Y-m-d H:i:s.u e O'),
);
$this->assertSame(
'2290-11-02 01:10:10.888480 America/Toronto -0500',
$date->copy()->addHour()->toDateTime()->format('Y-m-d H:i:s.u e O'),
);
}
public function testToDateTimeImmutable()
{
$dt = Carbon::create(2000, 3, 26);
$date = $dt->toDateTimeImmutable();
$this->assertInstanceOf(DateTimeImmutable::class, $date);
$this->assertSame('2000-03-26', $date->format('Y-m-d'));
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/SubTest.php | tests/Carbon/SubTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\CarbonInterval;
use Carbon\Unit;
use DateTime;
use Tests\AbstractTestCase;
class SubTest extends AbstractTestCase
{
public function testSubMethod()
{
$this->assertSame(1973, Carbon::createFromDate(1975)->sub(2, 'year')->year);
$this->assertSame(1973, Carbon::createFromDate(1975)->sub('year', 2)->year);
$this->assertSame(1973, Carbon::createFromDate(1975)->sub(2, Unit::Year)->year);
$this->assertSame(1973, Carbon::createFromDate(1975)->sub(Unit::Year, 2)->year);
$this->assertSame(1973, Carbon::createFromDate(1975)->sub('2 years')->year);
$lastNegated = null;
$date = Carbon::createFromDate(1975)->sub(
function (DateTime $date, bool $negated = false) use (&$lastNegated): DateTime {
$lastNegated = $negated;
return new DateTime($date->format('Y-m-d H:i:s').' - 2 years');
},
);
$this->assertInstanceOf(Carbon::class, $date);
$this->assertSame(1973, $date->year);
$this->assertSame(1973, Carbon::createFromDate(1975)->subtract(2, 'year')->year);
$this->assertSame(1973, Carbon::createFromDate(1975)->subtract('year', 2)->year);
$this->assertSame(1973, Carbon::createFromDate(1975)->subtract(2, Unit::Year)->year);
$this->assertSame(1973, Carbon::createFromDate(1975)->subtract(Unit::Year, 2)->year);
$this->assertSame(1973, Carbon::createFromDate(1975)->subtract('2 years')->year);
$lastNegated = null;
$this->assertSame(1973, Carbon::createFromDate(1975)->subtract(
function (DateTime $date, bool $negated = false) use (&$lastNegated): DateTime {
$lastNegated = $negated;
return new DateTime($date->format('Y-m-d H:i:s').' - 2 years');
},
)->year);
/** @var CarbonInterval $interval */
$interval = include __DIR__.'/../Fixtures/dynamicInterval.php';
$originalDate = Carbon::parse('2020-06-08');
$date = $originalDate->sub($interval);
$this->assertInstanceOf(Carbon::class, $date);
$this->assertSame('2020-05-31', $date->format('Y-m-d'));
$this->assertSame($originalDate, $date);
$date = Carbon::parse('2020-07-16')->subtract($interval);
$this->assertInstanceOf(Carbon::class, $date);
$this->assertSame('2020-06-30', $date->format('Y-m-d'));
}
public function testSubYearsPositive()
{
$this->assertSame(1974, Carbon::createFromDate(1975)->subYears(1)->year);
}
public function testSubYearsZero()
{
$this->assertSame(1975, Carbon::createFromDate(1975)->subYears(0)->year);
}
public function testSubYearsNegative()
{
$this->assertSame(1976, Carbon::createFromDate(1975)->subYears(-1)->year);
}
public function testSubYear()
{
$this->assertSame(1974, Carbon::createFromDate(1975)->subYear()->year);
$this->assertSame(1973, Carbon::createFromDate(1975)->sub(2, 'year')->year);
$this->assertSame(1973, Carbon::createFromDate(1975)->sub(2, 'years')->year);
$this->assertSame(1973, Carbon::createFromDate(1975)->sub(CarbonInterval::years(2))->year);
$this->assertSame(1973, Carbon::createFromDate(1975)->subtract(2, 'year')->year);
$this->assertSame(1973, Carbon::createFromDate(1975)->subtract(2, 'years')->year);
$this->assertSame(1973, Carbon::createFromDate(1975)->subtract(CarbonInterval::years(2))->year);
}
public function testSubMonthsPositive()
{
$this->assertSame(12, Carbon::createFromDate(1975, 1, 1)->subMonths(1)->month);
}
public function testSubMonthsZero()
{
$this->assertSame(1, Carbon::createFromDate(1975, 1, 1)->subMonths(0)->month);
}
public function testSubMonthsNegative()
{
$this->assertSame(2, Carbon::createFromDate(1975, 1, 1)->subMonths(-1)->month);
}
public function testSubMonth()
{
$this->assertSame(12, Carbon::createFromDate(1975, 1, 1)->subMonth()->month);
}
public function testSubDaysPositive()
{
$this->assertSame(30, Carbon::createFromDate(1975, 5, 1)->subDays(1)->day);
}
public function testSubDaysZero()
{
$this->assertSame(1, Carbon::createFromDate(1975, 5, 1)->subDays(0)->day);
}
public function testSubDaysNegative()
{
$this->assertSame(2, Carbon::createFromDate(1975, 5, 1)->subDays(-1)->day);
}
public function testSubDay()
{
$this->assertSame(30, Carbon::createFromDate(1975, 5, 1)->subDay()->day);
}
public function testSubWeekdaysPositive()
{
$this->assertSame(22, Carbon::createFromDate(2012, 1, 4)->subWeekdays(9)->day);
}
public function testSubWeekdaysZero()
{
$this->assertSame(4, Carbon::createFromDate(2012, 1, 4)->subWeekdays(0)->day);
}
public function testSubWeekdaysNegative()
{
$this->assertSame(13, Carbon::createFromDate(2012, 1, 31)->subWeekdays(-9)->day);
}
public function testSubWeekday()
{
$this->assertSame(6, Carbon::createFromDate(2012, 1, 9)->subWeekday()->day);
}
public function testSubWeekdayDuringWeekend()
{
$this->assertSame(6, Carbon::createFromDate(2012, 1, 8)->subWeekday()->day);
}
public function testSubWeeksPositive()
{
$this->assertSame(14, Carbon::createFromDate(1975, 5, 21)->subWeeks(1)->day);
}
public function testSubWeeksZero()
{
$this->assertSame(21, Carbon::createFromDate(1975, 5, 21)->subWeeks(0)->day);
}
public function testSubWeeksNegative()
{
$this->assertSame(28, Carbon::createFromDate(1975, 5, 21)->subWeeks(-1)->day);
}
public function testSubWeek()
{
$this->assertSame(14, Carbon::createFromDate(1975, 5, 21)->subWeek()->day);
}
public function testSubHoursPositive()
{
$this->assertSame(23, Carbon::createFromTime(0)->subHours(1)->hour);
}
public function testSubHoursZero()
{
$this->assertSame(0, Carbon::createFromTime(0)->subHours(0)->hour);
}
public function testSubHoursNegative()
{
$this->assertSame(1, Carbon::createFromTime(0)->subHours(-1)->hour);
}
public function testSubHour()
{
$this->assertSame(23, Carbon::createFromTime(0)->subHour()->hour);
}
public function testSubMinutesPositive()
{
$this->assertSame(59, Carbon::createFromTime(0, 0)->subMinutes(1)->minute);
}
public function testSubMinutesZero()
{
$this->assertSame(0, Carbon::createFromTime(0, 0)->subMinutes(0)->minute);
}
public function testSubMinutesNegative()
{
$this->assertSame(1, Carbon::createFromTime(0, 0)->subMinutes(-1)->minute);
}
public function testSubMinute()
{
$this->assertSame(59, Carbon::createFromTime(0, 0)->subMinute()->minute);
}
public function testSubSecondsPositive()
{
$this->assertSame(59, Carbon::createFromTime(0, 0, 0)->subSeconds(1)->second);
}
public function testSubSecondsZero()
{
$this->assertSame(0, Carbon::createFromTime(0, 0, 0)->subSeconds(0)->second);
}
public function testSubSecondsNegative()
{
$this->assertSame(1, Carbon::createFromTime(0, 0, 0)->subSeconds(-1)->second);
}
public function testSubSecond()
{
$this->assertSame(59, Carbon::createFromTime(0, 0, 0)->subSecond()->second);
}
/**
* Test non plural methods with non default args.
*/
public function testSubYearPassingArg()
{
// subYear should ideally be used without argument
/** @var mixed $date */
$date = Carbon::createFromDate(1975);
$this->assertSame(1973, $date->subYear(2)->year);
}
public function testSubMonthPassingArg()
{
// subMonth should ideally be used without argument
/** @var mixed $date */
$date = Carbon::createFromDate(1975, 5, 1);
$this->assertSame(3, $date->subMonth(2)->month);
}
public function testSubMonthNoOverflowPassingArg()
{
// subMonthNoOverflow should ideally be used without argument
/** @var mixed $date */
$date = Carbon::createFromDate(2011, 4, 30);
$date = $date->subMonthNoOverflow(2);
$this->assertSame(2, $date->month);
$this->assertSame(28, $date->day);
}
public function testSubDayPassingArg()
{
// subDay should ideally be used without argument
/** @var mixed $date */
$date = Carbon::createFromDate(1975, 5, 10);
$this->assertSame(8, $date->subDay(2)->day);
}
public function testSubHourPassingArg()
{
// subHour should ideally be used without argument
/** @var mixed $date */
$date = Carbon::createFromTime(0);
$this->assertSame(22, $date->subHour(2)->hour);
}
public function testSubMinutePassingArg()
{
// subMinute should ideally be used without argument
/** @var mixed $date */
$date = Carbon::createFromTime(0);
$this->assertSame(58, $date->subMinute(2)->minute);
}
public function testSubSecondPassingArg()
{
// subSecond should ideally be used without argument
/** @var mixed $date */
$date = Carbon::createFromTime(0);
$this->assertSame(58, $date->subSecond(2)->second);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/CreateSafeTest.php | tests/Carbon/CreateSafeTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\Exceptions\InvalidDateException;
use Tests\AbstractTestCase;
class CreateSafeTest extends AbstractTestCase
{
public function testInvalidDateExceptionProperties()
{
$e = new InvalidDateException('day', 'foo');
$this->assertSame('day', $e->getField());
$this->assertSame('foo', $e->getValue());
}
public function testCreateSafeThrowsExceptionForSecondLowerThanZero()
{
$this->expectExceptionObject(new InvalidDateException('second', -1));
Carbon::createSafe(null, null, null, null, null, -1);
}
public function testCreateSafeThrowsExceptionForSecondLowerThanZeroInStrictMode()
{
Carbon::useStrictMode(false);
$this->assertNull(Carbon::createSafe(null, null, null, null, null, -1));
}
public function testCreateSafeThrowsExceptionForSecondGreaterThan59()
{
$this->expectExceptionObject(new InvalidDateException('second', 60));
Carbon::createSafe(null, null, null, null, null, 60);
}
public function testCreateSafeThrowsExceptionForMinuteLowerThanZero()
{
$this->expectExceptionObject(new InvalidDateException('minute', -1));
Carbon::createSafe(null, null, null, null, -1);
}
public function testCreateSafeThrowsExceptionForMinuteGreaterThan59()
{
$this->expectExceptionObject(new InvalidDateException('minute', 60));
Carbon::createSafe(null, null, null, null, 60, 25);
}
public function testCreateSafeThrowsExceptionForHourLowerThanZero()
{
$this->expectExceptionObject(new InvalidDateException('hour', -6));
Carbon::createSafe(null, null, null, -6);
}
public function testCreateSafeThrowsExceptionForHourGreaterThan24()
{
$this->expectExceptionObject(new InvalidDateException('hour', 25));
Carbon::createSafe(null, null, null, 25, 16, 15);
}
public function testCreateSafeThrowsExceptionForDayLowerThanZero()
{
$this->expectExceptionObject(new InvalidDateException('day', -5));
Carbon::createSafe(null, null, -5);
}
public function testCreateSafeThrowsExceptionForDayGreaterThan31()
{
$this->expectExceptionObject(new InvalidDateException('day', 32));
Carbon::createSafe(null, null, 32, 17, 16, 15);
}
public function testCreateSafeThrowsExceptionForMonthLowerThanZero()
{
$this->expectExceptionObject(new InvalidDateException('month', -4));
Carbon::createSafe(null, -4);
}
public function testCreateSafeThrowsExceptionForMonthGreaterThan12()
{
$this->expectExceptionObject(new InvalidDateException('month', 13));
Carbon::createSafe(null, 13, 5, 17, 16, 15);
}
public function testCreateSafeThrowsExceptionForYearEqualToZero()
{
$this->expectExceptionObject(new InvalidDateException('year', 0));
Carbon::createSafe(0);
}
public function testCreateSafeThrowsExceptionForYearLowerThanZero()
{
$this->expectExceptionObject(new InvalidDateException('year', -5));
Carbon::createSafe(-5);
}
public function testCreateSafeThrowsExceptionForYearGreaterThan12()
{
$this->expectExceptionObject(new InvalidDateException('year', 10000));
Carbon::createSafe(10000, 12, 5, 17, 16, 15);
}
public function testCreateSafeThrowsExceptionForInvalidDayInShortMonth()
{
$this->expectExceptionObject(new InvalidDateException('day', 31));
// 30 days in April
Carbon::createSafe(2016, 4, 31, 17, 16, 15);
}
public function testCreateSafeThrowsExceptionForInvalidDayForFebruaryInLeapYear()
{
$this->expectExceptionObject(new InvalidDateException('day', 30));
// 29 days in February for a leap year
$this->assertTrue(Carbon::create(2016, 2)->isLeapYear());
Carbon::createSafe(2016, 2, 30, 17, 16, 15);
}
public function testCreateSafeThrowsExceptionForInvalidDayForFebruaryInLeapYearInStrictMode()
{
Carbon::useStrictMode(false);
$this->assertNull(Carbon::createSafe(2016, 2, 30, 17, 16, 15));
}
public function testCreateSafePassesForFebruaryInLeapYear()
{
// 29 days in February for a leap year
$this->assertSame(29, Carbon::createSafe(2016, 2, 29, 17, 16, 15)->day);
}
public function testCreateSafeThrowsExceptionForInvalidDayForFebruaryInNonLeapYear()
{
$this->expectExceptionObject(new InvalidDateException('day', 29));
// 28 days in February for a non-leap year
$this->assertFalse(Carbon::create(2015, 2)->isLeapYear());
Carbon::createSafe(2015, 2, 29, 17, 16, 15);
}
public function testCreateSafePassesForInvalidDSTTime()
{
$message = '';
try {
// 1h jumped to 2h because of the DST, so 1h30 is not a safe date in PHP 5.4+
Carbon::createSafe(2014, 3, 30, 1, 30, 0, 'Europe/London');
} catch (InvalidDateException $exception) {
$message = $exception->getMessage();
}
$this->assertStringContainsString('hour : 1 is not a valid value.', $message);
}
public function testCreateSafePassesForValidDSTTime()
{
$this->assertSame(0, Carbon::createSafe(2014, 3, 30, 0, 30, 0, 'Europe/London')->hour);
$this->assertSame(2, Carbon::createSafe(2014, 3, 30, 2, 30, 0, 'Europe/London')->hour);
$this->assertSame(1, Carbon::createSafe(2014, 3, 30, 1, 30, 0, 'UTC')->hour);
}
public function testCreateSafeThrowsExceptionForWithNonIntegerValue()
{
$this->expectExceptionObject(new InvalidDateException('second', 15.1));
Carbon::createSafe(2015, 2, 10, 17, 16, 15.1);
}
public function testCreateSafePassesForFebruaryInNonLeapYear()
{
// 28 days in February for a non-leap year
$this->assertSame(28, Carbon::createSafe(2015, 2, 28, 17, 16, 15)->day);
}
public function testCreateSafePasses()
{
$sd = Carbon::createSafe(2015, 2, 15, 17, 16, 15);
$d = Carbon::create(2015, 2, 15, 17, 16, 15);
$this->assertEquals($d, $sd);
$this->assertCarbon($sd, 2015, 2, 15, 17, 16, 15);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/GettersTest.php | tests/Carbon/GettersTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\AbstractTestCase;
class GettersTest extends AbstractTestCase
{
public function testGettersThrowExceptionOnUnknownGetter()
{
$this->expectExceptionObject(new InvalidArgumentException(
"Unknown getter 'doesNotExit'",
));
/** @var mixed $d */
$d = Carbon::create(1234, 5, 6, 7, 8, 9);
$d->doesNotExit;
}
public function testGet()
{
$d = Carbon::create(1234, 5, 6, 7, 8, 9);
$this->assertSame(5, $d->get('month'));
}
public function testMillenniumGetter()
{
$d = Carbon::create(1234, 5, 6, 7, 8, 9);
$this->assertSame(2, $d->millennium);
$d = Carbon::create(2000, 5, 6, 7, 8, 9);
$this->assertSame(2, $d->millennium);
$d = Carbon::create(2001, 5, 6, 7, 8, 9);
$this->assertSame(3, $d->millennium);
$d = Carbon::create(1, 5, 6, 7, 8, 9);
$this->assertSame(1, $d->millennium);
$d = Carbon::create(-1, 5, 6, 7, 8, 9);
$this->assertSame(-1, $d->millennium);
$d = Carbon::create(-100, 5, 6, 7, 8, 9);
$this->assertSame(-1, $d->millennium);
$d = Carbon::create(-101, 5, 6, 7, 8, 9);
$this->assertSame(-1, $d->millennium);
$d = Carbon::create(-1000, 5, 6, 7, 8, 9);
$this->assertSame(-1, $d->millennium);
$d = Carbon::create(-1001, 5, 6, 7, 8, 9);
$this->assertSame(-2, $d->millennium);
}
public function testCenturyGetter()
{
$d = Carbon::create(1234, 5, 6, 7, 8, 9);
$this->assertSame(13, $d->century);
$d = Carbon::create(2000, 5, 6, 7, 8, 9);
$this->assertSame(20, $d->century);
$d = Carbon::create(2001, 5, 6, 7, 8, 9);
$this->assertSame(21, $d->century);
$d = Carbon::create(1, 5, 6, 7, 8, 9);
$this->assertSame(1, $d->century);
$d = Carbon::create(-1, 5, 6, 7, 8, 9);
$this->assertSame(-1, $d->century);
$d = Carbon::create(-100, 5, 6, 7, 8, 9);
$this->assertSame(-1, $d->century);
$d = Carbon::create(-101, 5, 6, 7, 8, 9);
$this->assertSame(-2, $d->century);
}
public function testDecadeGetter()
{
$d = Carbon::create(1234, 5, 6, 7, 8, 9);
$this->assertSame(124, $d->decade);
}
public function testYearGetter()
{
$d = Carbon::create(1234, 5, 6, 7, 8, 9);
$this->assertSame(1234, $d->year);
}
public function testYearIsoGetter()
{
$d = Carbon::createFromDate(2012, 12, 31);
$this->assertSame(2013, $d->yearIso);
}
public function testMonthGetter()
{
$d = Carbon::create(1234, 5, 6, 7, 8, 9);
$this->assertSame(5, $d->month);
}
public function testDayGetter()
{
$d = Carbon::create(1234, 5, 6, 7, 8, 9);
$this->assertSame(6, $d->day);
}
public function testHourGetter()
{
$d = Carbon::create(1234, 5, 6, 7, 8, 9);
$this->assertSame(7, $d->hour);
}
public function testMinuteGetter()
{
$d = Carbon::create(1234, 5, 6, 7, 8, 9);
$this->assertSame(8, $d->minute);
}
public function testSecondGetter()
{
$d = Carbon::create(1234, 5, 6, 7, 8, 9);
$this->assertSame(9, $d->second);
}
public function testMicroGetter()
{
$micro = 345678;
$d = Carbon::parse('2014-01-05 12:34:11.'.$micro);
$this->assertSame($micro, $d->micro);
}
public function testMicroGetterWithDefaultNow()
{
$now = Carbon::getTestNow();
Carbon::setTestNow(null);
$start = microtime(true);
usleep(10000);
$d = Carbon::now();
usleep(10000);
$end = microtime(true);
$microTime = $d->getTimestamp() + $d->micro / 1000000;
$this->assertGreaterThan($start, $microTime);
$this->assertLessThan($end, $microTime);
Carbon::setTestNow($now);
}
public function testDayOfWeekGetter()
{
$d = Carbon::create(2012, 5, 7, 7, 8, 9);
$this->assertSame(Carbon::MONDAY, $d->dayOfWeek);
$d = Carbon::create(2012, 5, 8, 7, 8, 9);
$this->assertSame(Carbon::TUESDAY, $d->dayOfWeek);
$d = Carbon::create(2012, 5, 9, 7, 8, 9);
$this->assertSame(Carbon::WEDNESDAY, $d->dayOfWeek);
$d = Carbon::create(2012, 5, 10, 0, 0, 0);
$this->assertSame(Carbon::THURSDAY, $d->dayOfWeek);
$d = Carbon::create(2012, 5, 11, 23, 59, 59);
$this->assertSame(Carbon::FRIDAY, $d->dayOfWeek);
$d = Carbon::create(2012, 5, 12, 12, 0, 0);
$this->assertSame(Carbon::SATURDAY, $d->dayOfWeek);
$d = Carbon::create(2012, 5, 13, 12, 0, 0);
$this->assertSame(Carbon::SUNDAY, $d->dayOfWeek);
}
public function testDayOfWeekIsoGetter()
{
$d = Carbon::create(2012, 5, 7, 7, 8, 9);
$this->assertSame(1, $d->dayOfWeekIso);
$d = Carbon::create(2012, 5, 8, 7, 8, 9);
$this->assertSame(2, $d->dayOfWeekIso);
$d = Carbon::create(2012, 5, 9, 7, 8, 9);
$this->assertSame(3, $d->dayOfWeekIso);
$d = Carbon::create(2012, 5, 10, 0, 0, 0);
$this->assertSame(4, $d->dayOfWeekIso);
$d = Carbon::create(2012, 5, 11, 23, 59, 59);
$this->assertSame(5, $d->dayOfWeekIso);
$d = Carbon::create(2012, 5, 12, 12, 0, 0);
$this->assertSame(6, $d->dayOfWeekIso);
$d = Carbon::create(2012, 5, 13, 12, 0, 0);
$this->assertSame(7, $d->dayOfWeekIso);
}
public function testStringGetters()
{
$d = Carbon::create(2012, 1, 9, 7, 8, 9);
$this->assertSame('Monday', $d->englishDayOfWeek);
$this->assertSame('Mon', $d->shortEnglishDayOfWeek);
$this->assertSame('January', $d->englishMonth);
$this->assertSame('Jan', $d->shortEnglishMonth);
}
public function testLocalizedGetters()
{
Carbon::setLocale('fr');
$d = Carbon::create(2019, 7, 15, 7, 8, 9);
$this->assertSame('lundi', $d->localeDayOfWeek);
$this->assertSame('lun.', $d->shortLocaleDayOfWeek);
$this->assertSame('juillet', $d->localeMonth);
$this->assertSame('juil.', $d->shortLocaleMonth);
}
public function testDayOfYearGetter()
{
$d = Carbon::createFromDate(2012, 5, 7);
$this->assertSame(128, $d->dayOfYear);
}
public function testDaysInMonthGetter()
{
$d = Carbon::createFromDate(2012, 5, 7);
$this->assertSame(31, $d->daysInMonth);
}
public function testTimestampGetter()
{
$d = Carbon::create();
$d->setTimezone('GMT');
$this->assertSame(0, $d->setDateTime(1970, 1, 1, 0, 0, 0)->timestamp);
}
public function testGetAge()
{
$d = Carbon::now();
$this->assertSame(0, $d->age);
}
public function testGetAgeWithRealAge()
{
$d = Carbon::createFromDate(1975, 5, 21);
$age = (int) (substr((string) ((int) (date('Ymd')) - (int) (date('Ymd', $d->timestamp))), 0, -4));
$this->assertSame($age, $d->age);
}
public function testAgeWithBirthdayTomorrowAndLeapYear()
{
Carbon::setTestNow('2024-07-15 22:15');
$this->assertSame(3, Carbon::parse('2020-07-16')->age);
}
public static function dataForTestQuarter(): array
{
return [
[1, 1],
[2, 1],
[3, 1],
[4, 2],
[5, 2],
[6, 2],
[7, 3],
[8, 3],
[9, 3],
[10, 4],
[11, 4],
[12, 4],
];
}
#[DataProvider('dataForTestQuarter')]
public function testQuarterFirstOfMonth(int $month, int $quarter)
{
$c = Carbon::create(2015, $month, 1)->startOfMonth();
$this->assertSame($quarter, $c->quarter);
}
#[DataProvider('dataForTestQuarter')]
public function testQuarterMiddleOfMonth(int $month, int $quarter)
{
$c = Carbon::create(2015, $month, 15, 12, 13, 14);
$this->assertSame($quarter, $c->quarter);
}
#[DataProvider('dataForTestQuarter')]
public function testQuarterLastOfMonth(int $month, int $quarter)
{
$c = Carbon::create(2015, $month, 1)->endOfMonth();
$this->assertSame($quarter, $c->quarter);
}
public function testGetLocalTrue()
{
// Default timezone has been set to America/Toronto in AbstractTestCase.php
// @see : https://en.wikipedia.org/wiki/List_of_UTC_time_offsets
$this->assertTrue(Carbon::createFromDate(2012, 1, 1, 'America/Toronto')->local);
$this->assertTrue(Carbon::createFromDate(2012, 1, 1, 'America/Toronto')->isLocal());
$this->assertTrue(Carbon::createFromDate(2012, 1, 1, 'America/New_York')->local);
$this->assertTrue(Carbon::createFromDate(2012, 1, 1, 'America/New_York')->isLocal());
}
public function testGetLocalFalse()
{
$this->assertFalse(Carbon::createFromDate(2012, 7, 1, 'UTC')->local);
$this->assertFalse(Carbon::createFromDate(2012, 7, 1, 'UTC')->isLocal());
$this->assertFalse(Carbon::createFromDate(2012, 7, 1, 'Europe/London')->local);
$this->assertFalse(Carbon::createFromDate(2012, 7, 1, 'Europe/London')->isLocal());
}
public function testGetUtcFalse()
{
$this->assertFalse(Carbon::createFromDate(2013, 1, 1, 'America/Toronto')->utc);
$this->assertFalse(Carbon::createFromDate(2013, 1, 1, 'America/Toronto')->isUtc());
/** @var object $date */
$date = Carbon::createFromDate(2013, 1, 1, 'America/Toronto');
$this->assertFalse($date->isUTC());
$this->assertFalse(Carbon::createFromDate(2013, 1, 1, 'Europe/Paris')->utc);
$this->assertFalse(Carbon::createFromDate(2013, 1, 1, 'Europe/Paris')->isUtc());
/** @var object $date */
$date = Carbon::createFromDate(2013, 1, 1, 'Europe/Paris');
$this->assertFalse($date->isUTC());
}
public function testGetUtcTrue()
{
$this->assertTrue(Carbon::createFromDate(2013, 1, 1, 'Atlantic/Reykjavik')->utc);
$this->assertTrue(Carbon::createFromDate(2013, 1, 1, 'Atlantic/Reykjavik')->isUtc());
$this->assertTrue(Carbon::createFromDate(2013, 1, 1, 'Europe/Lisbon')->utc);
$this->assertTrue(Carbon::createFromDate(2013, 1, 1, 'Europe/Lisbon')->isUtc());
$this->assertTrue(Carbon::createFromDate(2013, 1, 1, 'Africa/Casablanca')->utc);
$this->assertTrue(Carbon::createFromDate(2013, 1, 1, 'Africa/Casablanca')->isUtc());
$this->assertTrue(Carbon::createFromDate(2013, 1, 1, 'Africa/Dakar')->utc);
$this->assertTrue(Carbon::createFromDate(2013, 1, 1, 'Africa/Dakar')->isUtc());
$this->assertTrue(Carbon::createFromDate(2013, 1, 1, 'Europe/Dublin')->utc);
$this->assertTrue(Carbon::createFromDate(2013, 1, 1, 'Europe/Dublin')->isUtc());
$this->assertTrue(Carbon::createFromDate(2013, 1, 1, 'Europe/London')->utc);
$this->assertTrue(Carbon::createFromDate(2013, 1, 1, 'Europe/London')->isUtc());
$this->assertTrue(Carbon::createFromDate(2013, 1, 1, 'UTC')->utc);
$this->assertTrue(Carbon::createFromDate(2013, 1, 1, 'UTC')->isUtc());
$this->assertTrue(Carbon::createFromDate(2013, 1, 1, 'GMT')->utc);
$this->assertTrue(Carbon::createFromDate(2013, 1, 1, 'GMT')->isUtc());
}
public function testGetDstFalse()
{
$this->assertFalse(Carbon::createFromDate(2012, 1, 1, 'America/Toronto')->dst);
$this->assertFalse(Carbon::createFromDate(2012, 1, 1, 'America/Toronto')->isDST());
}
public function testGetDstTrue()
{
$this->assertTrue(Carbon::createFromDate(2012, 7, 1, 'America/Toronto')->dst);
$this->assertTrue(Carbon::createFromDate(2012, 7, 1, 'America/Toronto')->isDST());
}
public function testGetMidDayAt()
{
$d = Carbon::now();
$this->assertSame(12, $d->getMidDayAt());
}
public function testOffsetForTorontoWithDST()
{
$this->assertSame(-18000, Carbon::createFromDate(2012, 1, 1, 'America/Toronto')->offset);
}
public function testOffsetForTorontoNoDST()
{
$this->assertSame(-14400, Carbon::createFromDate(2012, 6, 1, 'America/Toronto')->offset);
}
public function testOffsetForGMT()
{
$this->assertSame(0, Carbon::createFromDate(2012, 6, 1, 'GMT')->offset);
}
public function testOffsetHoursForTorontoWithDST()
{
$this->assertSame(-5, Carbon::createFromDate(2012, 1, 1, 'America/Toronto')->offsetHours);
}
public function testOffsetHoursForTorontoNoDST()
{
$this->assertSame(-4, Carbon::createFromDate(2012, 6, 1, 'America/Toronto')->offsetHours);
}
public function testOffsetHoursForGMT()
{
$this->assertSame(0, Carbon::createFromDate(2012, 6, 1, 'GMT')->offsetHours);
}
public function testIsLeapYearTrue()
{
$this->assertTrue(Carbon::createFromDate(2012, 1, 1)->isLeapYear());
}
public function testIsLeapYearFalse()
{
$this->assertFalse(Carbon::createFromDate(2011, 1, 1)->isLeapYear());
}
public function testIsLongYearTrue()
{
$this->assertTrue(Carbon::createFromDate(2015, 1, 1)->isLongYear());
$this->assertTrue(Carbon::createFromDate(2020, 1, 1)->isLongYear());
}
public function testIsLongIsoYearTrue()
{
$this->assertTrue(Carbon::createFromDate(2015, 1, 1)->isLongIsoYear());
$this->assertTrue(Carbon::createFromDate(2016, 1, 1)->isLongIsoYear());
$this->assertTrue(Carbon::createFromDate(2019, 12, 30)->isLongIsoYear());
}
public function testIsLongYearFalse()
{
$this->assertFalse(Carbon::createFromDate(2016, 1, 1)->isLongYear());
$this->assertFalse(Carbon::createFromDate(2019, 12, 29)->isLongYear());
$this->assertFalse(Carbon::createFromDate(2019, 12, 30)->isLongYear());
}
public function testIsLongIsoYearFalse()
{
$this->assertTrue(Carbon::createFromDate(2016, 1, 3)->isLongIsoYear());
$this->assertFalse(Carbon::createFromDate(2019, 12, 29)->isLongIsoYear());
$this->assertFalse(Carbon::createFromDate(2018, 12, 31)->isLongIsoYear());
}
public function testWeekOfMonth()
{
$this->assertSame(5, Carbon::createFromDate(2012, 9, 30)->weekOfMonth);
$this->assertSame(4, Carbon::createFromDate(2012, 9, 28)->weekOfMonth);
$this->assertSame(3, Carbon::createFromDate(2012, 9, 20)->weekOfMonth);
$this->assertSame(2, Carbon::createFromDate(2012, 9, 8)->weekOfMonth);
$this->assertSame(1, Carbon::createFromDate(2012, 9, 1)->weekOfMonth);
}
public function testWeekNumberInMonthIsNotFromTheBeginning()
{
$this->assertSame(5, Carbon::createFromDate(2017, 2, 28)->weekNumberInMonth);
$this->assertSame(5, Carbon::createFromDate(2017, 2, 27)->weekNumberInMonth);
$this->assertSame(4, Carbon::createFromDate(2017, 2, 26)->weekNumberInMonth);
$this->assertSame(4, Carbon::createFromDate(2017, 2, 20)->weekNumberInMonth);
$this->assertSame(3, Carbon::createFromDate(2017, 2, 19)->weekNumberInMonth);
$this->assertSame(3, Carbon::createFromDate(2017, 2, 13)->weekNumberInMonth);
$this->assertSame(2, Carbon::createFromDate(2017, 2, 12)->weekNumberInMonth);
$this->assertSame(2, Carbon::createFromDate(2017, 2, 6)->weekNumberInMonth);
$this->assertSame(1, Carbon::createFromDate(2017, 2, 1)->weekNumberInMonth);
$this->assertSame(1, Carbon::createFromDate(2018, 7, 1)->weekNumberInMonth);
$this->assertSame(2, Carbon::createFromDate(2018, 7, 2)->weekNumberInMonth);
$this->assertSame(2, Carbon::createFromDate(2018, 7, 5)->weekNumberInMonth);
$this->assertSame(2, Carbon::createFromDate(2018, 7, 8)->weekNumberInMonth);
$this->assertSame(3, Carbon::createFromDate(2018, 7, 9)->weekNumberInMonth);
$this->assertSame(5, Carbon::createFromDate(2018, 7, 29)->weekNumberInMonth);
$this->assertSame(6, Carbon::createFromDate(2018, 7, 30)->weekNumberInMonth);
}
public function testWeekOfYearFirstWeek()
{
$this->assertSame(52, Carbon::createFromDate(2012, 1, 1)->weekOfYear);
$this->assertSame(1, Carbon::createFromDate(2012, 1, 2)->weekOfYear);
}
public function testWeekOfYearLastWeek()
{
$this->assertSame(52, Carbon::createFromDate(2012, 12, 30)->weekOfYear);
$this->assertSame(1, Carbon::createFromDate(2012, 12, 31)->weekOfYear);
}
public function testGetTimezone()
{
$dt = Carbon::createFromDate(2000, 1, 1, 'America/Toronto');
$this->assertSame('America/Toronto', $dt->timezone->getName());
$dt = Carbon::createFromDate(2000, 1, 1, -5);
$this->assertSame('America/Chicago', $dt->timezone->getName());
$dt = Carbon::createFromDate(2000, 1, 1, '-5');
$this->assertSame('-05:00', $dt->timezone->getName());
}
public function testGetTz()
{
$dt = Carbon::createFromDate(2000, 1, 1, 'America/Toronto');
$this->assertSame('America/Toronto', $dt->tz->getName());
$dt = Carbon::createFromDate(2000, 1, 1, -5);
$this->assertSame('America/Chicago', $dt->tz->getName());
$dt = Carbon::createFromDate(2000, 1, 1, '-5');
$this->assertSame('-05:00', $dt->tz->getName());
}
public function testGetTimezoneName()
{
$dt = Carbon::createFromDate(2000, 1, 1, 'America/Toronto');
$this->assertSame('America/Toronto', $dt->timezoneName);
$dt = Carbon::createFromDate(2000, 1, 1, -5);
$this->assertSame('America/Chicago', $dt->timezoneName);
$dt = Carbon::createFromDate(2000, 1, 1, '-5');
$this->assertSame('-05:00', $dt->timezoneName);
}
public function testGetTzName()
{
$dt = Carbon::createFromDate(2000, 1, 1, 'America/Toronto');
$this->assertSame('America/Toronto', $dt->tzName);
$dt = Carbon::createFromDate(2000, 1, 1, -5);
$this->assertSame('America/Chicago', $dt->timezoneName);
$dt = Carbon::createFromDate(2000, 1, 1, '-5');
$this->assertSame('-05:00', $dt->timezoneName);
}
public function testShortDayName()
{
$dt = Carbon::createFromDate(2018, 8, 6);
$this->assertSame('Mon', $dt->shortDayName);
$this->assertSame('lun.', $dt->locale('fr')->shortDayName);
}
public function testMinDayName()
{
$dt = Carbon::createFromDate(2018, 8, 6);
$this->assertSame('Mo', $dt->minDayName);
$this->assertSame('lu', $dt->locale('fr')->minDayName);
}
public function testShortMonthName()
{
$dt = Carbon::createFromDate(2018, 7, 6);
$this->assertSame('Jul', $dt->shortMonthName);
$this->assertSame('juil.', $dt->locale('fr')->shortMonthName);
}
public function testGetDays()
{
$days = [
Carbon::SUNDAY => 'Sunday',
Carbon::MONDAY => 'Monday',
Carbon::TUESDAY => 'Tuesday',
Carbon::WEDNESDAY => 'Wednesday',
Carbon::THURSDAY => 'Thursday',
Carbon::FRIDAY => 'Friday',
Carbon::SATURDAY => 'Saturday',
];
$this->assertSame($days, Carbon::getDays());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/CreateFromTimestampTest.php | tests/Carbon/CreateFromTimestampTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use DateTimeZone;
use Tests\AbstractTestCase;
class CreateFromTimestampTest extends AbstractTestCase
{
public function testCreateReturnsDatingInstance()
{
$d = Carbon::createFromTimestamp(Carbon::create(1975, 5, 21, 22, 32, 5, 'UTC')->timestamp);
$this->assertCarbon($d, 1975, 5, 21, 22, 32, 5);
}
public function testCreateFromTimestampMs()
{
$baseTimestamp = Carbon::create(1975, 5, 21, 22, 32, 5, 'UTC')->timestamp * 1000;
$timestamp = $baseTimestamp + 321;
$d = Carbon::createFromTimestampMs($timestamp);
$this->assertCarbon($d, 1975, 5, 21, 22, 32, 5, 321000);
$timestamp = $baseTimestamp + 321.8;
$d = Carbon::createFromTimestampMs($timestamp);
$this->assertCarbon($d, 1975, 5, 21, 22, 32, 5, 321800);
$timestamp = $baseTimestamp + 321.84;
$d = Carbon::createFromTimestampMs($timestamp);
$this->assertCarbon($d, 1975, 5, 21, 22, 32, 5, 321840);
$timestamp = $baseTimestamp + 321.847;
$d = Carbon::createFromTimestampMs($timestamp);
$this->assertCarbon($d, 1975, 5, 21, 22, 32, 5, 321847);
$timestamp = $baseTimestamp + 321.8474;
$d = Carbon::createFromTimestampMs($timestamp);
$this->assertCarbon($d, 1975, 5, 21, 22, 32, 5, 321847);
$timestamp = $baseTimestamp + 321.8479;
$d = Carbon::createFromTimestampMs($timestamp);
$this->assertCarbon($d, 1975, 5, 21, 22, 32, 5, 321848);
}
public function testCreateFromTimestampMsUTC()
{
// Toronto is GMT-04:00 in May
$baseTimestamp = Carbon::create(1975, 5, 21, 22, 32, 5)->timestamp * 1000;
$timestamp = $baseTimestamp + 321;
$d = Carbon::createFromTimestampMsUTC($timestamp);
$this->assertCarbon($d, 1975, 5, 22, 2, 32, 5, 321000);
$timestamp = $baseTimestamp + 321.8;
$d = Carbon::createFromTimestampMsUTC($timestamp);
$this->assertCarbon($d, 1975, 5, 22, 2, 32, 5, 321800);
$timestamp = $baseTimestamp + 321.84;
$d = Carbon::createFromTimestampMsUTC($timestamp);
$this->assertCarbon($d, 1975, 5, 22, 2, 32, 5, 321840);
$timestamp = $baseTimestamp + 321.847;
$d = Carbon::createFromTimestampMsUTC($timestamp);
$this->assertCarbon($d, 1975, 5, 22, 2, 32, 5, 321847);
$timestamp = $baseTimestamp + 321.8474;
$d = Carbon::createFromTimestampMsUTC($timestamp);
$this->assertCarbon($d, 1975, 5, 22, 2, 32, 5, 321847);
$timestamp = $baseTimestamp + 321.8479;
$d = Carbon::createFromTimestampMsUTC($timestamp);
$this->assertCarbon($d, 1975, 5, 22, 2, 32, 5, 321848);
$d = Carbon::createFromTimestampMsUTC(1);
$this->assertCarbon($d, 1970, 1, 1, 0, 0, 0, 1000);
$d = Carbon::createFromTimestampMsUTC(60);
$this->assertCarbon($d, 1970, 1, 1, 0, 0, 0, 60000);
$d = Carbon::createFromTimestampMsUTC(1000);
$this->assertCarbon($d, 1970, 1, 1, 0, 0, 1, 0);
$d = Carbon::createFromTimestampMsUTC(-0.04);
$this->assertCarbon($d, 1969, 12, 31, 23, 59, 59, 999960);
}
public function testComaDecimalSeparatorLocale()
{
$date = new Carbon('2017-07-29T13:57:27.123456Z');
$this->assertSame('2017-07-29 13:57:27.123456 Z', $date->format('Y-m-d H:i:s.u e'));
$date = Carbon::createFromFormat('Y-m-d\TH:i:s.uT', '2017-07-29T13:57:27.123456Z');
$this->assertSame('2017-07-29 13:57:27.123456 Z', $date->format('Y-m-d H:i:s.u e'));
$timestamp = Carbon::create(1975, 5, 21, 22, 32, 5, 'UTC')->timestamp * 1000 + 321;
$d = Carbon::createFromTimestampMs($timestamp);
$this->assertCarbon($d, 1975, 5, 21, 22, 32, 5, 321000);
$locale = setlocale(LC_ALL, '0');
if (setlocale(LC_ALL, 'fr_FR.UTF-8', 'fr_FR.utf8', 'French_France.UTF8') === false) {
$this->markTestSkipped('testComaDecimalSeparatorLocale test need fr_FR.UTF-8.');
}
$timestamp = Carbon::create(1975, 5, 21, 22, 32, 5, 'UTC')->timestamp * 1000 + 321;
$d = Carbon::createFromTimestampMs($timestamp);
$this->assertCarbon($d, 1975, 5, 21, 22, 32, 5, 321000);
$date = new Carbon('2017-07-29T13:57:27.123456Z');
$this->assertSame('2017-07-29 13:57:27.123456 Z', $date->format('Y-m-d H:i:s.u e'));
$date = Carbon::createFromFormat('Y-m-d\TH:i:s.uT', '2017-07-29T13:57:27.123456Z');
$this->assertSame('2017-07-29 13:57:27.123456 Z', $date->format('Y-m-d H:i:s.u e'));
$timestamp = Carbon::create(1975, 5, 21, 22, 32, 5, 'UTC')->timestamp * 1000 + 321;
$d = Carbon::createFromTimestampMs($timestamp);
$this->assertCarbon($d, 1975, 5, 21, 22, 32, 5, 321000);
setlocale(LC_ALL, $locale);
}
public function testCreateFromTimestampWithTimezone()
{
$carbon = Carbon::createFromTimestamp((int) '468370800', '+0100');
$this->assertSame(468370800, $carbon->getTimestamp());
$this->assertSame('+01:00', $carbon->tzName);
}
public function testCreateFromTimestampUsesDefaultTimezone()
{
$d = Carbon::createFromTimestamp(0, 'America/Toronto');
// We know Toronto is -5 since no DST in Jan
$this->assertSame(1969, $d->year);
$this->assertSame(-5 * 3600, $d->offset);
}
public function testCreateFromTimestampWithDateTimeZone()
{
$d = Carbon::createFromTimestamp(0, new DateTimeZone('UTC'));
$this->assertSame('UTC', $d->tzName);
$this->assertCarbon($d, 1970, 1, 1, 0, 0, 0);
}
public function testCreateFromTimestampWithString()
{
$d = Carbon::createFromTimestamp(0, 'UTC');
$this->assertCarbon($d, 1970, 1, 1, 0, 0, 0);
$this->assertSame(0, $d->offset);
$this->assertSame('UTC', $d->tzName);
}
public function testCreateFromTimestampGMTDoesNotUseDefaultTimezone()
{
$d = Carbon::createFromTimestampUTC(0);
$this->assertCarbon($d, 1970, 1, 1, 0, 0, 0);
$this->assertSame(0, $d->offset);
}
/**
* Ensures DST php bug does not affect createFromTimestamp in DST change.
*
* @see https://github.com/briannesbitt/Carbon/issues/1951
*/
public function testCreateFromTimestampInDstChange()
{
$this->assertSame(
'2019-11-03T01:00:00-04:00',
Carbon::createFromTimestamp(1572757200, 'America/New_York')->toIso8601String(),
);
$this->assertSame(
'2019-11-03T01:00:00-05:00',
Carbon::createFromTimestamp(1572757200 + 3600, 'America/New_York')->toIso8601String(),
);
$this->assertSame(
'2019-11-03T01:00:00-04:00',
Carbon::createFromTimestampMs(1572757200000, 'America/New_York')->toIso8601String(),
);
$this->assertSame(
'2019-11-03T01:00:00-05:00',
Carbon::createFromTimestampMs(1572757200000 + 3600000, 'America/New_York')->toIso8601String(),
);
}
public function testCreateFromMicrotimeFloat()
{
$microtime = 1600887164.88952298;
$d = Carbon::createFromTimestamp($microtime, 'America/Toronto');
$this->assertSame('America/Toronto', $d->tzName);
$this->assertSame('2020-09-23 14:52:44.889523', $d->format('Y-m-d H:i:s.u'));
$this->assertSame('1600887164.889523', $d->format('U.u'));
}
public function testCreateFromMicrotimeStrings()
{
$microtime = '0.88951247 1600887164';
$d = Carbon::createFromTimestamp($microtime, 'America/Toronto');
$this->assertSame('America/Toronto', $d->tzName);
$this->assertSame('2020-09-23 14:52:44.889512', $d->format('Y-m-d H:i:s.u'));
$this->assertSame('1600887164.889512', $d->format('U.u'));
$microtime = '0.88951247/1600887164/12.56';
$d = Carbon::createFromTimestamp($microtime, 'America/Toronto');
$this->assertSame('America/Toronto', $d->tzName);
$this->assertSame('2020-09-23 14:52:57.449512', $d->format('Y-m-d H:i:s.u'));
$this->assertSame('1600887177.449512', $d->format('U.u'));
$d = Carbon::createFromTimestamp('-10.6', 'America/Toronto');
$this->assertSame('1969-12-31 18:59:49.400000 -05:00', $d->format('Y-m-d H:i:s.u P'));
$d = new Carbon('@-10.6');
$this->assertSame('1969-12-31 23:59:49.400000 +00:00', $d->format('Y-m-d H:i:s.u P'));
}
public function testCreateFromMicrotimeUTCFloat()
{
$microtime = 1600887164.88952298;
$d = Carbon::createFromTimestampUTC($microtime);
$this->assertSame('+00:00', $d->tzName);
$this->assertSame('2020-09-23 18:52:44.889523', $d->format('Y-m-d H:i:s.u'));
$this->assertSame('1600887164.889523', $d->format('U.u'));
}
public function testCreateFromMicrotimeUTCStrings()
{
$microtime = '0.88951247 1600887164';
$d = Carbon::createFromTimestampUTC($microtime);
$this->assertSame('+00:00', $d->tzName);
$this->assertSame('2020-09-23 18:52:44.889512', $d->format('Y-m-d H:i:s.u'));
$this->assertSame('1600887164.889512', $d->format('U.u'));
$microtime = '0.88951247/1600887164/12.56';
$d = Carbon::createFromTimestampUTC($microtime);
$this->assertSame('+00:00', $d->tzName);
$this->assertSame('2020-09-23 18:52:57.449512', $d->format('Y-m-d H:i:s.u'));
$this->assertSame('1600887177.449512', $d->format('U.u'));
}
public function testNegativeIntegerTimestamp()
{
$this->assertSame(
'1969-12-31 18:59:59.000000 -05:00',
Carbon::createFromTimestamp(-1, 'America/Toronto')->format('Y-m-d H:i:s.u P'),
);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/PhpBug72338Test.php | tests/Carbon/PhpBug72338Test.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Tests\AbstractTestCase;
/**
* The problem is, that $date->setTimezone($tz) with $tz in 'HH:MM' notation (["timezone_type"]=>int(1)) put DateTime object
* on inconsistent state. It looks like internal timestamp becomes changed and it affects to such functions:
*
* * $date->modify() uses changed timestamp and result is wrong
*
* * $date->setTimezone($tz) settle this changed timestamp, even in case if $tz is not in 'HH:MM' format
*
* * $date->format('U') returns changed timestamp
*
* @link https://bugs.php.net/bug.php?id=72338 This bug on bugs.php.net
*
* @internal I use days changing in tests because using seconds|minute|hours may run setTimezone within.
*/
class PhpBug72338Test extends AbstractTestCase
{
/**
* Ensures that modify don't use changed timestamp
*/
public function testModify()
{
$date = Carbon::createFromTimestamp(0);
$date->setTimezone('+02:00');
$date->modify('+1 day');
$this->assertSame('86400', $date->format('U'));
}
/**
* Ensures that $date->format('U') returns unchanged timestamp
*/
public function testTimestamp()
{
$date = Carbon::createFromTimestamp(0);
$date->setTimezone('+02:00');
$this->assertSame('0', $date->format('U'));
}
/**
* Ensures that date created from string with timezone and with same timezone set by setTimezone() is equal
*/
public function testEqualSetAndCreate()
{
$date = Carbon::createFromTimestamp(0);
$date->setTimezone('+02:00');
$date1 = new Carbon('1970-01-01T02:00:00+02:00');
$this->assertSame($date->format('U'), $date1->format('U'));
}
/**
* Ensures that second call to setTimezone() don't changing timestamp
*/
public function testSecondSetTimezone()
{
$date = Carbon::createFromTimestamp(0);
$date->setTimezone('+02:00');
$date->setTimezone('Europe/Moscow');
$this->assertSame('0', $date->format('U'));
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/CreateTest.php | tests/Carbon/CreateTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\Exceptions\InvalidTimeZoneException;
use Carbon\Exceptions\OutOfRangeException;
use DateTime;
use DateTimeZone;
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use Tests\AbstractTestCase;
class CreateTest extends AbstractTestCase
{
public function testCreateReturnsDatingInstance()
{
$d = Carbon::create();
$this->assertInstanceOfCarbon($d);
}
public function testCreateWithDefaults()
{
$d = Carbon::create();
$this->assertSame($d->getTimestamp(), Carbon::create('0000-01-01 00:00:00')->getTimestamp());
}
public function testCreateWithNull()
{
$d = Carbon::create(null, null, null, null, null, null);
$this->assertSame($d->getTimestamp(), Carbon::now()->getTimestamp());
}
public function testCreateWithYear()
{
$d = Carbon::create(2012);
$this->assertSame(2012, $d->year);
}
public function testCreateHandlesNegativeYear()
{
$c = Carbon::create(-1, 10, 12, 1, 2, 3);
$this->assertCarbon($c, -1, 10, 12, 1, 2, 3);
}
public function testCreateHandlesFiveDigitsPositiveYears()
{
$c = Carbon::create(999999999, 10, 12, 1, 2, 3);
$this->assertCarbon($c, 999999999, 10, 12, 1, 2, 3);
}
public function testCreateHandlesFiveDigitsNegativeYears()
{
$c = Carbon::create(-999999999, 10, 12, 1, 2, 3);
$this->assertCarbon($c, -999999999, 10, 12, 1, 2, 3);
}
public function testCreateWithMonth()
{
$d = Carbon::create(null, 3);
$this->assertSame(3, $d->month);
}
public function testCreateWithInvalidMonth()
{
$this->expectExceptionObject(new InvalidArgumentException(
'month must be between 0 and 99, -5 given',
));
Carbon::create(null, -5);
}
public function testOutOfRangeException()
{
/** @var OutOfRangeException $error */
$error = null;
try {
Carbon::create(null, -5);
} catch (OutOfRangeException $exception) {
$error = $exception;
}
$this->assertInstanceOf(OutOfRangeException::class, $error);
$this->assertSame('month', $error->getUnit());
$this->assertSame(-5, $error->getValue());
$this->assertSame(0, $error->getMin());
$this->assertSame(99, $error->getMax());
}
public function testCreateWithInvalidMonthNonStrictMode()
{
Carbon::useStrictMode(false);
$this->assertFalse(Carbon::isStrictModeEnabled());
$this->assertNull(Carbon::create(null, -5));
Carbon::useStrictMode(true);
$this->assertTrue(Carbon::isStrictModeEnabled());
}
public function testCreateMonthWraps()
{
$d = Carbon::create(2011, 0, 1, 0, 0, 0);
$this->assertCarbon($d, 2010, 12, 1, 0, 0, 0);
}
public function testCreateWithDay()
{
$d = Carbon::create(null, null, 21);
$this->assertSame(21, $d->day);
}
public function testCreateWithInvalidDay()
{
$this->expectExceptionObject(new InvalidArgumentException(
'day must be between 0 and 99, -4 given',
));
Carbon::create(null, null, -4);
}
public function testCreateDayWraps()
{
$d = Carbon::create(2011, 1, 40, 0, 0, 0);
$this->assertCarbon($d, 2011, 2, 9, 0, 0, 0);
}
public function testCreateWithHourAndDefaultMinSecToZero()
{
$d = Carbon::create(null, null, null, 14);
$this->assertSame(14, $d->hour);
$this->assertSame(0, $d->minute);
$this->assertSame(0, $d->second);
}
public function testCreateWithInvalidHour()
{
$this->expectExceptionObject(new InvalidArgumentException(
'hour must be between 0 and 99, -1 given',
));
Carbon::create(null, null, null, -1);
}
public function testCreateHourWraps()
{
$d = Carbon::create(2011, 1, 1, 24, 0, 0);
$this->assertCarbon($d, 2011, 1, 2, 0, 0, 0);
}
public function testCreateWithMinute()
{
$d = Carbon::create(null, null, null, null, 58);
$this->assertSame(58, $d->minute);
}
public function testCreateWithInvalidMinute()
{
$this->expectExceptionObject(new InvalidArgumentException(
'minute must be between 0 and 99, -2 given',
));
Carbon::create(2011, 1, 1, 0, -2, 0);
}
public function testCreateMinuteWraps()
{
$d = Carbon::create(2011, 1, 1, 0, 62, 0);
$this->assertCarbon($d, 2011, 1, 1, 1, 2, 0);
}
public function testCreateWithSecond()
{
$d = Carbon::create(null, null, null, null, null, 59);
$this->assertSame(59, $d->second);
}
public function testCreateWithInvalidSecond()
{
$this->expectExceptionObject(new InvalidArgumentException(
'second must be between 0 and 99, -2 given',
));
Carbon::create(null, null, null, null, null, -2);
}
public function testCreateSecondsWrap()
{
$d = Carbon::create(2012, 1, 1, 0, 0, 61);
$this->assertCarbon($d, 2012, 1, 1, 0, 1, 1);
}
public function testCreateWithDateTimeZone()
{
$d = Carbon::create(2012, 1, 1, 0, 0, 0, new DateTimeZone('Europe/London'));
$this->assertCarbon($d, 2012, 1, 1, 0, 0, 0);
$this->assertSame('Europe/London', $d->tzName);
}
public function testCreateWithTimeZoneString()
{
$d = Carbon::create(2012, 1, 1, 0, 0, 0, 'Europe/London');
$this->assertCarbon($d, 2012, 1, 1, 0, 0, 0);
$this->assertSame('Europe/London', $d->tzName);
}
public function testMake()
{
$this->assertCarbon(Carbon::make('2017-01-05'), 2017, 1, 5, 0, 0, 0);
$this->assertCarbon(Carbon::make(new DateTime('2017-01-05')), 2017, 1, 5, 0, 0, 0);
$this->assertCarbon(Carbon::make(new Carbon('2017-01-05')), 2017, 1, 5, 0, 0, 0);
$this->assertNull(Carbon::make(3));
}
public function testCreateWithInvalidTimezoneOffset()
{
$this->expectExceptionObject(new InvalidTimeZoneException(
'Unknown or bad timezone (-28236)',
));
Carbon::createFromDate(2000, 1, 1, -28236);
}
public function testCreateWithValidTimezoneOffset()
{
$dt = Carbon::createFromDate(2000, 1, 1, -4);
$this->assertSame('America/New_York', $dt->tzName);
$dt = Carbon::createFromDate(2000, 1, 1, '-4');
$this->assertSame('-04:00', $dt->tzName);
}
public function testParseFromLocale()
{
$dateToday = Carbon::parseFromLocale('now', 'en');
$dateTest = Carbon::parseFromLocale('à l\'instant', 'fr');
$this->assertSame($dateToday->format('Y-m-d H:i:s'), $dateTest->format('Y-m-d H:i:s'));
$dateToday = Carbon::parseFromLocale('today', 'en');
$dateTest = Carbon::parseFromLocale('Aujourd\'hui', 'fr');
$this->assertSame($dateToday->format('Y-m-d'), $dateTest->format('Y-m-d'));
$dateTest = Carbon::parseFromLocale('Aujourd\'hui à 19:34', 'fr');
$this->assertSame($dateToday->format('Y-m-d').' 19:34', $dateTest->format('Y-m-d H:i'));
$dateTest = Carbon::parseFromLocale('Heute', 'de');
$this->assertSame($dateToday->format('Y-m-d'), $dateTest->format('Y-m-d'));
$dateTest = Carbon::parseFromLocale('Heute um 19:34', 'de');
$this->assertSame($dateToday->format('Y-m-d').' 19:34', $dateTest->format('Y-m-d H:i'));
$date = date('Y-m-d', strtotime($dateToday.' + 1 days'));
$dateTest = Carbon::parseFromLocale('demain', 'fr');
$this->assertSame($date, $dateTest->format('Y-m-d'));
$date = date('Y-m-d', strtotime($dateToday.' + 2 days'));
$dateTest = Carbon::parseFromLocale('après-demain', 'fr');
$this->assertSame($date, $dateTest->format('Y-m-d'));
$date = date('Y-m-d', strtotime($dateToday.' - 1 days'));
$dateTest = Carbon::parseFromLocale('hier', 'fr');
$this->assertSame($date, $dateTest->format('Y-m-d'));
$date = date('Y-m-d', strtotime($dateToday.' - 2 days'));
$dateTest = Carbon::parseFromLocale('avant-hier', 'fr');
$this->assertSame($date, $dateTest->format('Y-m-d'));
$date = Carbon::parseFromLocale('23 Okt 2019', 'de');
$this->assertSame('Wednesday, October 23, 2019 12:00 AM America/Toronto', $date->isoFormat('LLLL zz'));
$date = Carbon::parseFromLocale('23 Okt 2019', 'de', 'Europe/Berlin')->locale('de');
$this->assertSame('Mittwoch, 23. Oktober 2019 00:00 Europe/Berlin', $date->isoFormat('LLLL zz'));
$date = Carbon::parseFromLocale('23 červenec 2019', 'cs');
$this->assertSame('2019-07-23', $date->format('Y-m-d'));
$date = Carbon::parseFromLocale('23 červen 2019', 'cs');
$this->assertSame('2019-06-23', $date->format('Y-m-d'));
Carbon::setTestNow('2021-01-26 15:45:13');
$date = Carbon::parseFromLocale('завтра', 'ru');
$this->assertSame('2021-01-27 00:00:00', $date->format('Y-m-d H:i:s'));
}
#[Group('localization')]
#[DataProvider('dataForLocales')]
public function testParseFromLocaleForEachLocale($locale)
{
$expectedDate = Carbon::parse('today 4:26');
$date = Carbon::parseFromLocale($expectedDate->locale($locale)->calendar(), $locale);
$this->assertSame($expectedDate->format('Y-m-d H:i'), $date->format('Y-m-d H:i'));
}
public function testParseFromLocaleWithDefaultLocale()
{
Carbon::setLocale('fr');
$date = Carbon::parseFromLocale('Dimanche');
$this->assertSame('dimanche', $date->dayName);
$date = Carbon::parseFromLocale('Lundi');
$this->assertSame('lundi', $date->dayName);
$date = Carbon::parseFromLocale('à l’instant');
$this->assertEquals(Carbon::now(), $date);
$date = Carbon::parseFromLocale('après-demain');
$this->assertEquals(Carbon::today()->addDays(2), $date);
}
public function testCreateFromLocaleFormat()
{
$date = Carbon::createFromLocaleFormat('Y M d H,i,s', 'zh_CN', '2019 四月 4 12,04,21');
$this->assertSame('Thursday, April 4, 2019 12:04 PM America/Toronto', $date->isoFormat('LLLL zz'));
$date = Carbon::createFromLocaleFormat('Y M d H,i,s', 'zh_TW', '2019 四月 4 12,04,21', 'Asia/Shanghai')->locale('zh');
$this->assertSame('2019年4月4日星期四 中午 12点04分 Asia/Shanghai', $date->isoFormat('LLLL zz'));
$this->assertSame(
'2022-12-05 America/Mexico_City',
Carbon::createFromLocaleFormat('d * F * Y', 'es', '05 de diciembre de 2022', 'America/Mexico_City')
->format('Y-m-d e')
);
$this->assertSame(
'2022-12-05 America/Mexico_City',
Carbon::createFromLocaleFormat('d \of F \of Y', 'es', '05 de diciembre de 2022', 'America/Mexico_City')
->format('Y-m-d e')
);
$this->assertSame(
'2022-12-05 America/Mexico_City',
Carbon::createFromLocaleFormat('d \o\f F \o\f Y', 'es', '05 de diciembre de 2022', 'America/Mexico_City')
->format('Y-m-d e')
);
$this->assertSame(
'2022-12-05 America/Mexico_City',
Carbon::createFromLocaleFormat('d \d\e F \d\e Y', 'es', '05 de diciembre de 2022', 'America/Mexico_City')
->format('Y-m-d e')
);
$this->assertSame(
'2022-12-05 America/Mexico_City',
Carbon::createFromLocaleFormat('d \n\o\t F \n\o\t Y', 'es', '05 not diciembre not 2022', 'America/Mexico_City')
->format('Y-m-d e')
);
}
public function testCreateFromIsoFormat()
{
$date = Carbon::createFromIsoFormat('!YYYYY MMMM D', '2019 April 4');
$this->assertSame('Thursday, April 4, 2019 12:00 AM America/Toronto', $date->isoFormat('LLLL zz'));
}
public function testCreateFromIsoFormatException()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Format wo not supported for creation.',
));
Carbon::createFromIsoFormat('YY D wo', '2019 April 4');
}
public function testCreateFromLocaleIsoFormat()
{
$date = Carbon::createFromLocaleIsoFormat('YYYY MMMM D HH,mm,ss', 'zh_TW', '2019 四月 4 12,04,21');
$this->assertSame('Thursday, April 4, 2019 12:04 PM America/Toronto', $date->isoFormat('LLLL zz'));
$date = Carbon::createFromLocaleIsoFormat('LLL zz', 'zh', '2019年4月4日 下午 2点04分 Asia/Shanghai');
$this->assertSame('Thursday, April 4, 2019 2:04 PM Asia/Shanghai', $date->isoFormat('LLLL zz'));
$this->assertSame('2019年4月4日星期四 下午 2点04分 Asia/Shanghai', $date->locale('zh')->isoFormat('LLLL zz'));
$date = Carbon::createFromLocaleIsoFormat('llll', 'fr_CA', 'mar. 24 juil. 2018 08:34');
$this->assertSame('2018-07-24 08:34', $date->format('Y-m-d H:i'));
}
public static function dataForLocales(): array
{
$locales = [
'aa_ER',
'aa_ER@saaho',
'aa_ET',
'af',
'af_NA',
'af_ZA',
'agq',
'agr',
'agr_PE',
'ak',
'ak_GH',
'am',
'am_ET',
'an',
'an_ES',
'anp',
'anp_IN',
'ar',
'ar_AE',
'ar_BH',
'ar_DJ',
'ar_DZ',
'ar_EG',
'ar_EH',
'ar_ER',
'ar_IL',
'ar_IN',
'ar_IQ',
'ar_JO',
'ar_KM',
'ar_KW',
'ar_LB',
'ar_LY',
'ar_MA',
'ar_MR',
'ar_OM',
'ar_PS',
'ar_QA',
'ar_SA',
'ar_SD',
'ar_SO',
'ar_SS',
'ar_SY',
'ar_Shakl',
'ar_TD',
'ar_TN',
'ar_YE',
'as',
'as_IN',
'asa',
'ast',
'ast_ES',
'ayc',
'ayc_PE',
'az',
'az_AZ',
'az_Cyrl',
'az_Latn',
'bas',
'be',
'be_BY',
'bem',
'bem_ZM',
'ber',
'ber_DZ',
'ber_MA',
'bez',
'bg',
'bg_BG',
'bhb',
'bhb_IN',
'bho',
'bho_IN',
'bi',
'bi_VU',
'bm',
'bo_IN',
'br',
'br_FR',
'brx',
'brx_IN',
'bs',
'bs_BA',
'bs_Cyrl',
'bs_Latn',
'ca',
'ca_AD',
'ca_ES',
'ca_ES_Valencia',
'ca_FR',
'ca_IT',
'ccp',
'ccp_IN',
'ce',
'ce_RU',
'cgg',
'chr',
'chr_US',
'cmn',
'cmn_TW',
'crh',
'crh_UA',
'cu',
'cy',
'cy_GB',
'da',
'da_DK',
'da_GL',
'dav',
'dje',
'doi',
'doi_IN',
'dsb',
'dsb_DE',
'dua',
'dv',
'dv_MV',
'dyo',
'dz',
'dz_BT',
'ebu',
'ee_TG',
'el',
'el_CY',
'el_GR',
'en',
'en_001',
'en_150',
'en_AG',
'en_AI',
'en_AS',
'en_AT',
'en_AU',
'en_BB',
'en_BE',
'en_BI',
'en_BM',
'en_BS',
'en_BW',
'en_BZ',
'en_CA',
'en_CC',
'en_CH',
'en_CK',
'en_CM',
'en_CX',
'en_CY',
'en_DE',
'en_DG',
'en_DK',
'en_DM',
'en_ER',
'en_FI',
'en_FJ',
'en_FK',
'en_FM',
'en_GB',
'en_GD',
'en_GG',
'en_GH',
'en_GI',
'en_GM',
'en_GU',
'en_GY',
'en_HK',
'en_IE',
'en_IL',
'en_IM',
'en_IN',
'en_IO',
'en_ISO',
'en_JE',
'en_JM',
'en_KE',
'en_KI',
'en_KN',
'en_KY',
'en_LC',
'en_LR',
'en_LS',
'en_MG',
'en_MH',
'en_MO',
'en_MP',
'en_MS',
'en_MT',
'en_MU',
'en_MW',
'en_MY',
'en_NA',
'en_NF',
'en_NG',
'en_NL',
'en_NR',
'en_NU',
'en_NZ',
'en_PG',
'en_PH',
'en_PK',
'en_PN',
'en_PR',
'en_PW',
'en_RW',
'en_SB',
'en_SC',
'en_SD',
'en_SE',
'en_SG',
'en_SH',
'en_SI',
'en_SL',
'en_SS',
'en_SX',
'en_SZ',
'en_TC',
'en_TK',
'en_TO',
'en_TT',
'en_TV',
'en_TZ',
'en_UG',
'en_UM',
'en_US',
'en_US_Posix',
'en_VC',
'en_VG',
'en_VI',
'en_VU',
'en_WS',
'en_ZA',
'en_ZM',
'en_ZW',
'eo',
'es',
'es_419',
'es_AR',
'es_BO',
'es_BR',
'es_BZ',
'es_CL',
'es_CO',
'es_CR',
'es_CU',
'es_DO',
'es_EA',
'es_EC',
'es_ES',
'es_GQ',
'es_GT',
'es_HN',
'es_IC',
'es_MX',
'es_NI',
'es_PA',
'es_PE',
'es_PH',
'es_PR',
'es_PY',
'es_SV',
'es_US',
'es_UY',
'es_VE',
'et',
'et_EE',
'ewo',
'ff',
'ff_CM',
'ff_GN',
'ff_MR',
'ff_SN',
'fil',
'fil_PH',
'fo',
'fo_DK',
'fo_FO',
'fr',
'fr_BE',
'fr_BF',
'fr_BI',
'fr_BJ',
'fr_BL',
'fr_CA',
'fr_CD',
'fr_CF',
'fr_CG',
'fr_CH',
'fr_CI',
'fr_CM',
'fr_DJ',
'fr_DZ',
'fr_FR',
'fr_GA',
'fr_GF',
'fr_GN',
'fr_GP',
'fr_GQ',
'fr_HT',
'fr_KM',
'fr_LU',
'fr_MA',
'fr_MC',
'fr_MF',
'fr_MG',
'fr_ML',
'fr_MQ',
'fr_MR',
'fr_MU',
'fr_NC',
'fr_NE',
'fr_PF',
'fr_PM',
'fr_RE',
'fr_RW',
'fr_SC',
'fr_SN',
'fr_SY',
'fr_TD',
'fr_TG',
'fr_TN',
'fr_VU',
'fr_WF',
'fr_YT',
'fy',
'fy_NL',
'ga',
'ga_IE',
'gd',
'gd_GB',
'gez',
'gez_ER',
'gez_ET',
'gl',
'gl_ES',
'guz',
'gv',
'gv_GB',
'ha',
'ha_GH',
'ha_NE',
'ha_NG',
'hak',
'hak_TW',
'haw',
'he',
'he_IL',
'hif',
'hif_FJ',
'hne',
'hne_IN',
'hr',
'hr_BA',
'hr_HR',
'hsb',
'hsb_DE',
'ht',
'ht_HT',
'hy',
'hy_AM',
'ia',
'ia_FR',
'id',
'id_ID',
'ig',
'ig_NG',
'ii',
'ik',
'ik_CA',
'in',
'it',
'it_CH',
'it_IT',
'it_SM',
'it_VA',
'iu',
'iu_CA',
'iw',
'ja',
'ja_JP',
'jgo',
'jmc',
'jv',
'kab',
'kab_DZ',
'kam',
'kde',
'kea',
'khq',
'ki',
'kk',
'kk_KZ',
'kkj',
'kl',
'kl_GL',
'kln',
'km',
'km_KH',
'kok',
'kok_IN',
'ks',
'ks_IN',
'ks_IN@devanagari',
'ksb',
'ksf',
'ksh',
'kw',
'kw_GB',
'ky',
'ky_KG',
'lag',
'lg',
'lg_UG',
'li',
'li_NL',
'lij',
'lij_IT',
'lkt',
'ln',
'ln_AO',
'ln_CD',
'ln_CF',
'ln_CG',
'lo',
'lo_LA',
'lrc',
'lrc_IQ',
'lt',
'lt_LT',
'lu',
'luo',
'luy',
'lzh',
'lzh_TW',
'mag',
'mag_IN',
'mai',
'mai_IN',
'mas',
'mas_TZ',
'mer',
'mfe',
'mfe_MU',
'mg',
'mg_MG',
'mgh',
'mgo',
'mhr',
'mhr_RU',
'mi',
'mi_NZ',
'miq',
'miq_NI',
'mjw',
'mjw_IN',
'mk',
'mk_MK',
'mni',
'mni_IN',
'mo',
'ms',
'ms_BN',
'ms_MY',
'ms_SG',
'mt',
'mt_MT',
'mua',
'mzn',
'nan',
'nan_TW',
'nan_TW@latin',
'naq',
'nb',
'nb_NO',
'nb_SJ',
'nd',
'nds',
'nds_DE',
'nds_NL',
'ne_IN',
'nhn',
'nhn_MX',
'niu',
'niu_NU',
'nl',
'nl_AW',
'nl_BE',
'nl_BQ',
'nl_CW',
'nl_NL',
'nl_SR',
'nl_SX',
'nmg',
'nn',
'nn_NO',
'nnh',
'no',
'nr',
'nr_ZA',
'nso',
'nso_ZA',
'nus',
'nyn',
'oc',
'oc_FR',
'om',
'om_ET',
'om_KE',
'os',
'os_RU',
'pa_Arab',
'pa_Guru',
'pl',
'pl_PL',
'prg',
'pt',
'pt_AO',
'pt_BR',
'pt_CH',
'pt_CV',
'pt_GQ',
'pt_GW',
'pt_LU',
'pt_MO',
'pt_MZ',
'pt_PT',
'pt_ST',
'pt_TL',
'qu',
'qu_BO',
'qu_EC',
'quz',
'quz_PE',
'raj',
'raj_IN',
'rm',
'rn',
'ro',
'ro_MD',
'ro_RO',
'rof',
'ru',
'ru_BY',
'ru_KG',
'ru_KZ',
'ru_MD',
'ru_RU',
'ru_UA',
'rw',
'rw_RW',
'rwk',
'sa',
'sa_IN',
'sah',
'sah_RU',
'saq',
'sat',
'sat_IN',
'sbp',
'sd',
'sd_IN',
'sd_IN@devanagari',
'se',
'se_FI',
'se_NO',
'se_SE',
'seh',
'ses',
'sg',
'sgs',
'sgs_LT',
'shi',
'shi_Latn',
'shi_Tfng',
'shn',
'shn_MM',
'shs',
'shs_CA',
'sid',
'sid_ET',
'sl',
'sl_SI',
'sm',
'sm_WS',
'smn',
'sn',
'so',
'so_DJ',
'so_ET',
'so_KE',
'so_SO',
'sq',
'sq_AL',
'sq_MK',
'sq_XK',
'sr',
'sr_Cyrl',
'sr_Cyrl_BA',
'sr_Cyrl_ME',
'sr_Cyrl_XK',
'sr_Latn',
'sr_Latn_BA',
'sr_Latn_ME',
'sr_Latn_XK',
'sr_ME',
'sr_RS',
'sr_RS@latin',
'ss',
'ss_ZA',
'st',
'st_ZA',
'sv',
'sv_AX',
'sv_FI',
'sv_SE',
'sw',
'sw_CD',
'sw_KE',
'sw_TZ',
'sw_UG',
'szl',
'szl_PL',
'ta',
'ta_IN',
'ta_LK',
'tcy',
'tcy_IN',
'teo',
'teo_KE',
'tet',
'tg',
'tg_TJ',
'th',
'th_TH',
'the',
'the_NP',
'ti',
'ti_ER',
'ti_ET',
'tk',
'tk_TM',
'tlh',
'tn',
'tn_ZA',
'to',
'to_TO',
'tpi',
'tpi_PG',
'tr',
'tr_TR',
'ts',
'ts_ZA',
'tt_RU@iqtelif',
'twq',
'tzl',
'tzm',
'tzm_Latn',
'ug',
'ug_CN',
'uk',
'uk_UA',
'unm',
'unm_US',
'ur',
'ur_IN',
'ur_PK',
'uz_Arab',
'vai',
'vai_Vaii',
've',
've_ZA',
'vi',
'vi_VN',
'vo',
'vun',
'wa',
'wa_BE',
'wae',
'wae_CH',
'wal',
'wal_ET',
'xh',
'xh_ZA',
'xog',
'yav',
'yi',
'yi_US',
'yo',
'yo_BJ',
'yo_NG',
'yue',
'yue_HK',
'yue_Hans',
'yue_Hant',
'yuw',
'yuw_PG',
'zh',
'zh_CN',
'zh_HK',
'zh_Hans',
'zh_Hans_HK',
'zh_Hans_MO',
'zh_Hans_SG',
'zh_Hant',
'zh_Hant_HK',
'zh_Hant_MO',
'zh_Hant_TW',
'zh_MO',
'zh_SG',
'zh_TW',
'zh_YUE',
'zu',
'zu_ZA',
];
return array_combine(
$locales,
array_map(
static fn (string $locale) => [$locale],
$locales,
),
);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/DayOfWeekModifiersTest.php | tests/Carbon/DayOfWeekModifiersTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Tests\AbstractTestCase;
class DayOfWeekModifiersTest extends AbstractTestCase
{
public function testGetWeekendDays()
{
$this->assertSame([Carbon::SATURDAY, Carbon::SUNDAY], Carbon::getWeekendDays());
}
public function testSetWeekendDays()
{
Carbon::setWeekendDays([Carbon::THURSDAY, Carbon::FRIDAY]);
$this->assertSame([Carbon::THURSDAY, Carbon::FRIDAY], Carbon::getWeekendDays());
$this->assertTrue(Carbon::createFromDate(2018, 2, 16)->isWeekend());
Carbon::setWeekendDays([Carbon::SATURDAY, Carbon::SUNDAY]);
$this->assertSame([Carbon::SATURDAY, Carbon::SUNDAY], Carbon::getWeekendDays());
$this->assertFalse(Carbon::createFromDate(2018, 2, 16)->isWeekend());
}
public function testStartOfWeek()
{
$d = Carbon::create(1980, 8, 7, 12, 11, 9)->startOfWeek();
$this->assertCarbon($d, 1980, 8, 4, 0, 0, 0);
Carbon::setLocale('en_UM');
$this->assertSame('Sunday', Carbon::now()->startOfWeek()->dayName);
Carbon::setLocale('en');
$this->assertSame('Monday', Carbon::now()->startOfWeek()->dayName);
Carbon::setLocale('es_US');
$this->assertSame('domingo', Carbon::now()->startOfWeek()->dayName);
Carbon::setLocale('en_GB');
$this->assertSame('Monday', Carbon::now()->startOfWeek()->dayName);
}
public function testStartOfWeekFromWeekStart()
{
$d = Carbon::createFromDate(1980, 8, 4)->startOfWeek();
$this->assertCarbon($d, 1980, 8, 4, 0, 0, 0);
}
public function testStartOfWeekCrossingYearBoundary()
{
$d = Carbon::createFromDate(2013, 12, 31, 'GMT');
$d->startOfWeek();
$this->assertCarbon($d, 2013, 12, 30, 0, 0, 0);
}
public function testEndOfWeek()
{
$d = Carbon::create(1980, 8, 7, 11, 12, 13)->endOfWeek();
$this->assertCarbon($d, 1980, 8, 10, 23, 59, 59);
}
public function testEndOfWeekFromWeekEnd()
{
$d = Carbon::createFromDate(1980, 8, 9)->endOfWeek();
$this->assertCarbon($d, 1980, 8, 10, 23, 59, 59);
}
public function testEndOfWeekCrossingYearBoundary()
{
$d = Carbon::createFromDate(2013, 12, 31, 'GMT');
$d->endOfWeek();
$this->assertCarbon($d, 2014, 1, 5, 23, 59, 59);
}
/**
* @see https://github.com/briannesbitt/Carbon/issues/735
*/
public function testStartOrEndOfWeekFromWeekWithUTC()
{
$d = Carbon::create(2016, 7, 27, 17, 13, 7, 'UTC');
$this->assertCarbon($d->copy()->startOfWeek(), 2016, 7, 25, 0, 0, 0);
$this->assertCarbon($d->copy()->endOfWeek(), 2016, 7, 31, 23, 59, 59);
}
/**
* @see https://github.com/briannesbitt/Carbon/issues/735
*/
public function testStartOrEndOfWeekFromWeekWithOtherTimezone()
{
$d = Carbon::create(2016, 7, 27, 17, 13, 7, 'America/New_York');
$this->assertCarbon($d->copy()->startOfWeek(), 2016, 7, 25, 0, 0, 0);
$this->assertCarbon($d->copy()->endOfWeek(), 2016, 7, 31, 23, 59, 59);
}
public function testNext()
{
$d = Carbon::createFromDate(1975, 5, 21)->next();
$this->assertCarbon($d, 1975, 5, 28, 0, 0, 0);
}
public function testNextMonday()
{
$d = Carbon::createFromDate(1975, 5, 21)->next(Carbon::MONDAY);
$this->assertCarbon($d, 1975, 5, 26, 0, 0, 0);
$d = Carbon::createFromDate(1975, 5, 21)->next('Monday');
$this->assertCarbon($d, 1975, 5, 26, 0, 0, 0);
}
public function testNextSaturday()
{
$d = Carbon::createFromDate(1975, 5, 21)->next(6);
$this->assertCarbon($d, 1975, 5, 24, 0, 0, 0);
}
public function testNextTimestamp()
{
$d = Carbon::createFromDate(1975, 11, 14)->next();
$this->assertCarbon($d, 1975, 11, 21, 0, 0, 0);
}
public function testPrevious()
{
$d = Carbon::createFromDate(1975, 5, 21)->previous();
$this->assertCarbon($d, 1975, 5, 14, 0, 0, 0);
}
public function testPreviousMonday()
{
$d = Carbon::createFromDate(1975, 5, 21)->previous(Carbon::MONDAY);
$this->assertCarbon($d, 1975, 5, 19, 0, 0, 0);
}
public function testPreviousSaturday()
{
$d = Carbon::createFromDate(1975, 5, 21)->previous(6);
$this->assertCarbon($d, 1975, 5, 17, 0, 0, 0);
}
public function testPreviousTimestamp()
{
$d = Carbon::createFromDate(1975, 11, 28)->previous();
$this->assertCarbon($d, 1975, 11, 21, 0, 0, 0);
}
public function testFirstDayOfMonth()
{
$d = Carbon::createFromDate(1975, 11, 21)->firstOfMonth();
$this->assertCarbon($d, 1975, 11, 1, 0, 0, 0);
}
public function testFirstWednesdayOfMonth()
{
$d = Carbon::createFromDate(1975, 11, 21)->firstOfMonth(Carbon::WEDNESDAY);
$this->assertCarbon($d, 1975, 11, 5, 0, 0, 0);
}
public function testFirstFridayOfMonth()
{
$d = Carbon::createFromDate(1975, 11, 21)->firstOfMonth(5);
$this->assertCarbon($d, 1975, 11, 7, 0, 0, 0);
}
public function testLastDayOfMonth()
{
$d = Carbon::createFromDate(1975, 12, 5)->lastOfMonth();
$this->assertCarbon($d, 1975, 12, 31, 0, 0, 0);
}
public function testLastTuesdayOfMonth()
{
$d = Carbon::createFromDate(1975, 12, 1)->lastOfMonth(Carbon::TUESDAY);
$this->assertCarbon($d, 1975, 12, 30, 0, 0, 0);
}
public function testLastFridayOfMonth()
{
$d = Carbon::createFromDate(1975, 12, 5)->lastOfMonth(5);
$this->assertCarbon($d, 1975, 12, 26, 0, 0, 0);
}
public function testNthOfMonthOutsideScope()
{
$this->assertFalse(Carbon::createFromDate(1975, 12, 5)->nthOfMonth(6, Carbon::MONDAY));
}
public function testNthOfMonthOutsideYear()
{
$this->assertFalse(Carbon::createFromDate(1975, 12, 5)->nthOfMonth(55, Carbon::MONDAY));
}
public function test2ndMondayOfMonth()
{
$d = Carbon::createFromDate(1975, 12, 5)->nthOfMonth(2, Carbon::MONDAY);
$this->assertCarbon($d, 1975, 12, 8, 0, 0, 0);
}
public function test3rdWednesdayOfMonth()
{
$d = Carbon::createFromDate(1975, 12, 5)->nthOfMonth(3, 3);
$this->assertCarbon($d, 1975, 12, 17, 0, 0, 0);
}
public function testFirstDayOfQuarter()
{
$d = Carbon::createFromDate(1975, 11, 21)->firstOfQuarter();
$this->assertCarbon($d, 1975, 10, 1, 0, 0, 0);
}
public function testFirstWednesdayOfQuarter()
{
$d = Carbon::createFromDate(1975, 11, 21)->firstOfQuarter(Carbon::WEDNESDAY);
$this->assertCarbon($d, 1975, 10, 1, 0, 0, 0);
}
public function testFirstFridayOfQuarter()
{
$d = Carbon::createFromDate(1975, 11, 21)->firstOfQuarter(5);
$this->assertCarbon($d, 1975, 10, 3, 0, 0, 0);
}
public function testFirstOfQuarterFromADayThatWillNotExistInTheFirstMonth()
{
$d = Carbon::createFromDate(2014, 5, 31)->firstOfQuarter();
$this->assertCarbon($d, 2014, 4, 1, 0, 0, 0);
}
public function testLastDayOfQuarter()
{
$d = Carbon::createFromDate(1975, 8, 5)->lastOfQuarter();
$this->assertCarbon($d, 1975, 9, 30, 0, 0, 0);
}
public function testLastTuesdayOfQuarter()
{
$d = Carbon::createFromDate(1975, 8, 1)->lastOfQuarter(Carbon::TUESDAY);
$this->assertCarbon($d, 1975, 9, 30, 0, 0, 0);
}
public function testLastFridayOfQuarter()
{
$d = Carbon::createFromDate(1975, 7, 5)->lastOfQuarter(5);
$this->assertCarbon($d, 1975, 9, 26, 0, 0, 0);
}
public function testLastOfQuarterFromADayThatWillNotExistInTheLastMonth()
{
$d = Carbon::createFromDate(2014, 5, 31)->lastOfQuarter();
$this->assertCarbon($d, 2014, 6, 30, 0, 0, 0);
}
public function testNthOfQuarterOutsideScope()
{
$this->assertFalse(Carbon::createFromDate(1975, 1, 5)->nthOfQuarter(20, Carbon::MONDAY));
}
public function testNthOfQuarterOutsideYear()
{
$this->assertFalse(Carbon::createFromDate(1975, 1, 5)->nthOfQuarter(55, Carbon::MONDAY));
}
public function testNthOfQuarterFromADayThatWillNotExistInTheFirstMonth()
{
$d = Carbon::createFromDate(2014, 5, 31)->nthOfQuarter(2, Carbon::MONDAY);
$this->assertCarbon($d, 2014, 4, 14, 0, 0, 0);
}
public function test2ndMondayOfQuarter()
{
$d = Carbon::createFromDate(1975, 8, 5)->nthOfQuarter(2, Carbon::MONDAY);
$this->assertCarbon($d, 1975, 7, 14, 0, 0, 0);
}
public function test3rdWednesdayOfQuarter()
{
$d = Carbon::createFromDate(1975, 8, 5)->nthOfQuarter(3, 3);
$this->assertCarbon($d, 1975, 7, 16, 0, 0, 0);
}
public function testFirstDayOfYear()
{
$d = Carbon::createFromDate(1975, 11, 21)->firstOfYear();
$this->assertCarbon($d, 1975, 1, 1, 0, 0, 0);
}
public function testFirstWednesdayOfYear()
{
$d = Carbon::createFromDate(1975, 11, 21)->firstOfYear(Carbon::WEDNESDAY);
$this->assertCarbon($d, 1975, 1, 1, 0, 0, 0);
}
public function testFirstFridayOfYear()
{
$d = Carbon::createFromDate(1975, 11, 21)->firstOfYear(5);
$this->assertCarbon($d, 1975, 1, 3, 0, 0, 0);
}
public function testLastDayOfYear()
{
$d = Carbon::createFromDate(1975, 8, 5)->lastOfYear();
$this->assertCarbon($d, 1975, 12, 31, 0, 0, 0);
}
public function testLastTuesdayOfYear()
{
$d = Carbon::createFromDate(1975, 8, 1)->lastOfYear(Carbon::TUESDAY);
$this->assertCarbon($d, 1975, 12, 30, 0, 0, 0);
}
public function testLastFridayOfYear()
{
$d = Carbon::createFromDate(1975, 7, 5)->lastOfYear(5);
$this->assertCarbon($d, 1975, 12, 26, 0, 0, 0);
}
public function testNthOfYearOutsideScope()
{
$this->assertFalse(Carbon::createFromDate(1975, 1, 5)->nthOfYear(55, Carbon::MONDAY));
}
public function test2ndMondayOfYear()
{
$d = Carbon::createFromDate(1975, 8, 5)->nthOfYear(2, Carbon::MONDAY);
$this->assertCarbon($d, 1975, 1, 13, 0, 0, 0);
}
public function test3rdWednesdayOfYear()
{
$d = Carbon::createFromDate(1975, 8, 5)->nthOfYear(3, 3);
$this->assertCarbon($d, 1975, 1, 15, 0, 0, 0);
}
public function testNextWeekday()
{
// Friday to Monday
$d = Carbon::create(2016, 7, 15)->nextWeekday();
$this->assertCarbon($d, 2016, 7, 18);
// Saturday to Monday
$d = Carbon::create(2016, 7, 16)->nextWeekday();
$this->assertCarbon($d, 2016, 7, 18);
// Sunday to Monday
$d = Carbon::create(2016, 7, 16)->nextWeekday();
$this->assertCarbon($d, 2016, 7, 18);
// Monday to Tuesday
$d = Carbon::create(2016, 7, 17)->nextWeekday();
$this->assertCarbon($d, 2016, 7, 18);
}
public function testPreviousWeekday()
{
// Tuesday to Monday
$d = Carbon::create(2016, 7, 19)->previousWeekday();
$this->assertCarbon($d, 2016, 7, 18);
// Monday to Friday
$d = Carbon::create(2016, 7, 18)->previousWeekday();
$this->assertCarbon($d, 2016, 7, 15);
// Sunday to Friday
$d = Carbon::create(2016, 7, 17)->previousWeekday();
$this->assertCarbon($d, 2016, 7, 15);
// Saturday to Friday
$d = Carbon::create(2016, 7, 16)->previousWeekday();
$this->assertCarbon($d, 2016, 7, 15);
}
public function testNextWeekendDay()
{
// Thursday to Saturday
$d = Carbon::create(2016, 7, 14)->nextWeekendDay();
$this->assertCarbon($d, 2016, 7, 16);
// Friday to Saturday
$d = Carbon::create(2016, 7, 15)->nextWeekendDay();
$this->assertCarbon($d, 2016, 7, 16);
// Saturday to Sunday
$d = Carbon::create(2016, 7, 16)->nextWeekendDay();
$this->assertCarbon($d, 2016, 7, 17);
// Sunday to Saturday
$d = Carbon::create(2016, 7, 17)->nextWeekendDay();
$this->assertCarbon($d, 2016, 7, 23);
}
public function testPreviousWeekendDay()
{
// Thursday to Sunday
$d = Carbon::create(2016, 7, 14)->previousWeekendDay();
$this->assertCarbon($d, 2016, 7, 10);
// Friday to Sunday
$d = Carbon::create(2016, 7, 15)->previousWeekendDay();
$this->assertCarbon($d, 2016, 7, 10);
// Saturday to Sunday
$d = Carbon::create(2016, 7, 16)->previousWeekendDay();
$this->assertCarbon($d, 2016, 7, 10);
// Sunday to Saturday
$d = Carbon::create(2016, 7, 17)->previousWeekendDay();
$this->assertCarbon($d, 2016, 7, 16);
}
public function testWeekStartAndEndWithAutoMode()
{
$this->assertSame('Monday', Carbon::now()->startOfWeek()->dayName);
Carbon::setLocale('en_UM');
$this->assertSame('Sunday', Carbon::now()->startOfWeek()->dayName);
Carbon::setLocale('en_US');
$this->assertSame('Sunday', Carbon::now()->startOfWeek()->dayName);
Carbon::setLocale('en');
$this->assertSame('Monday', Carbon::now()->startOfWeek()->dayName);
Carbon::setLocale('es_US');
$this->assertSame('domingo', Carbon::now()->startOfWeek()->dayName);
Carbon::setLocale('en_GB');
$this->assertSame('Monday', Carbon::now()->startOfWeek()->dayName);
Carbon::setLocale('en_UM');
$this->assertSame('Saturday', Carbon::now()->endOfWeek()->dayName);
Carbon::setLocale('en_US');
$this->assertSame('Saturday', Carbon::now()->endOfWeek()->dayName);
Carbon::setLocale('en');
$this->assertSame('Sunday', Carbon::now()->endOfWeek()->dayName);
Carbon::setLocale('es_US');
$this->assertSame('sábado', Carbon::now()->endOfWeek()->dayName);
Carbon::setLocale('en_GB');
$this->assertSame('Sunday', Carbon::now()->endOfWeek()->dayName);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/AddTest.php | tests/Carbon/AddTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\CarbonInterval;
use Carbon\Unit;
use DateTime;
use Tests\AbstractTestCase;
class AddTest extends AbstractTestCase
{
public function testAddMethod()
{
$this->assertSame(1977, Carbon::createFromDate(1975)->add(2, 'year')->year);
$this->assertSame(1977, Carbon::createFromDate(1975)->add('year', 2)->year);
$this->assertSame(1977, Carbon::createFromDate(1975)->add(2, Unit::Year)->year);
$this->assertSame(1977, Carbon::createFromDate(1975)->add(Unit::Year, 2)->year);
$this->assertSame(1977, Carbon::createFromDate(1975)->add('2 years')->year);
$lastNegated = null;
$date = Carbon::createFromDate(1975)->add(
function (DateTime $date, bool $negated = false) use (&$lastNegated): DateTime {
$lastNegated = $negated;
return new DateTime($date->format('Y-m-d H:i:s').' + 2 years');
},
);
$this->assertInstanceOf(Carbon::class, $date);
$this->assertSame(1977, $date->year);
$this->assertFalse($lastNegated);
/** @var CarbonInterval $interval */
$interval = include __DIR__.'/../Fixtures/dynamicInterval.php';
$originalDate = Carbon::parse('2020-06-04');
$date = $originalDate->add($interval);
$this->assertInstanceOf(Carbon::class, $date);
$this->assertSame('2020-06-08', $date->format('Y-m-d'));
$this->assertSame($date, $originalDate);
$date = Carbon::parse('2020-06-23')->add($interval);
$this->assertInstanceOf(Carbon::class, $date);
$this->assertSame('2020-07-16', $date->format('Y-m-d'));
}
public function testAddYearsPositive()
{
$this->assertSame(1976, Carbon::createFromDate(1975)->addYears(1)->year);
}
public function testAddYearsZero()
{
$this->assertSame(1975, Carbon::createFromDate(1975)->addYears(0)->year);
}
public function testAddYearsNegative()
{
$this->assertSame(1974, Carbon::createFromDate(1975)->addYears(-1)->year);
}
public function testAddYear()
{
$this->assertSame(1976, Carbon::createFromDate(1975)->addYear()->year);
}
public function testAddDaysPositive()
{
$this->assertSame(1, Carbon::createFromDate(1975, 5, 31)->addDays(1)->day);
}
public function testAddDaysZero()
{
$this->assertSame(31, Carbon::createFromDate(1975, 5, 31)->addDays(0)->day);
}
public function testAddDaysNegative()
{
$this->assertSame(30, Carbon::createFromDate(1975, 5, 31)->addDays(-1)->day);
}
public function testAddDay()
{
$this->assertSame(1, Carbon::createFromDate(1975, 5, 31)->addDay()->day);
}
public function testAddOverflow()
{
$this->assertSame(
'2021-03-03',
Carbon::parse('2021-01-31')->add(1, 'months', true)->format('Y-m-d'),
);
$this->assertSame(
'2021-03-03',
Carbon::parse('2021-01-31')->add(1, 'months')->format('Y-m-d'),
);
$this->assertSame(
'2021-02-28',
Carbon::parse('2021-01-31')->add(1, 'months', false)->format('Y-m-d'),
);
}
public function testAddWeekdaysPositive()
{
$dt = Carbon::create(2012, 1, 4, 13, 2, 1)->addWeekdays(9);
$this->assertSame(17, $dt->day);
// test for https://bugs.php.net/bug.php?id=54909
$this->assertSame(13, $dt->hour);
$this->assertSame(2, $dt->minute);
$this->assertSame(1, $dt->second);
}
public function testAddCustomWeekdays()
{
$date = Carbon::createMidnightDate(2018, 5, 25);
$weekendDays = Carbon::getWeekendDays();
Carbon::setWeekendDays([
Carbon::WEDNESDAY,
]);
$date->addWeekdays(2);
$this->assertSame(27, $date->day);
$date->subWeekdays(-3);
$this->assertSame(31, $date->day);
$date->addWeekdays(-3);
$this->assertSame(27, $date->day);
$date->subWeekdays(2);
$this->assertSame(25, $date->day);
$date->addWeekdays(14);
$this->assertSame(10, $date->day);
$date->subWeekdays(14);
$this->assertSame(25, $date->day);
$date->addWeekdays(12);
$this->assertSame(8, $date->day);
$date->subWeekdays(12);
$this->assertSame(25, $date->day);
Carbon::setWeekendDays($weekendDays);
}
public function testAddWeekdaysZero()
{
$this->assertSame(4, Carbon::createFromDate(2012, 1, 4)->addWeekdays(0)->day);
}
public function testAddWeekdaysNegative()
{
$this->assertSame(18, Carbon::createFromDate(2012, 1, 31)->addWeekdays(-9)->day);
}
public function testAddWeekday()
{
$this->assertSame(9, Carbon::createFromDate(2012, 1, 6)->addWeekday()->day);
}
public function testAddWeekdayDuringWeekend()
{
$this->assertSame(9, Carbon::createFromDate(2012, 1, 7)->addWeekday()->day);
}
public function testAddWeeksPositive()
{
$this->assertSame(28, Carbon::createFromDate(1975, 5, 21)->addWeeks(1)->day);
}
public function testAddWeeksZero()
{
$this->assertSame(21, Carbon::createFromDate(1975, 5, 21)->addWeeks(0)->day);
}
public function testAddWeeksNegative()
{
$this->assertSame(14, Carbon::createFromDate(1975, 5, 21)->addWeeks(-1)->day);
}
public function testAddWeek()
{
$this->assertSame(28, Carbon::createFromDate(1975, 5, 21)->addWeek()->day);
}
public function testAddHoursPositive()
{
$this->assertSame(1, Carbon::createFromTime(0)->addHours(1)->hour);
}
public function testAddHoursZero()
{
$this->assertSame(0, Carbon::createFromTime(0)->addHours(0)->hour);
}
public function testAddHoursNegative()
{
$this->assertSame(23, Carbon::createFromTime(0)->addHours(-1)->hour);
}
public function testAddHour()
{
$this->assertSame(1, Carbon::createFromTime(0)->addHour()->hour);
}
public function testAddMinutesPositive()
{
$this->assertSame(1, Carbon::createFromTime(0, 0)->addMinutes(1)->minute);
}
public function testAddMinutesZero()
{
$this->assertSame(0, Carbon::createFromTime(0, 0)->addMinutes(0)->minute);
}
public function testAddMinutesNegative()
{
$this->assertSame(59, Carbon::createFromTime(0, 0)->addMinutes(-1)->minute);
}
public function testAddMinute()
{
$this->assertSame(1, Carbon::createFromTime(0, 0)->addMinute()->minute);
}
public function testAddSecondsPositive()
{
$this->assertSame(1, Carbon::createFromTime(0, 0, 0)->addSeconds(1)->second);
}
public function testAddSecondsZero()
{
$this->assertSame(0, Carbon::createFromTime(0, 0, 0)->addSeconds(0)->second);
}
public function testAddSecondsNegative()
{
$this->assertSame(59, Carbon::createFromTime(0, 0, 0)->addSeconds(-1)->second);
}
public function testAddDecimalSeconds()
{
$this->assertSame(
'1999-12-31 23:59:58.500000',
Carbon::parse('2000-01-01 00:00:00')->addSeconds(-1.5)->format('Y-m-d H:i:s.u'),
);
$this->assertSame(
'2000-01-01 00:00:01.500000',
Carbon::parse('2000-01-01 00:00:00')->addSeconds(1.5)->format('Y-m-d H:i:s.u'),
);
$this->assertSame(
'1999-12-31 23:59:58.500000',
Carbon::parse('2000-01-01 00:00:00')->addRealSeconds(-1.5)->format('Y-m-d H:i:s.u'),
);
$this->assertSame(
'2000-01-01 00:00:01.500000',
Carbon::parse('2000-01-01 00:00:00')->addRealSeconds(1.5)->format('Y-m-d H:i:s.u'),
);
}
public function testAddSecond()
{
$this->assertSame(1, Carbon::createFromTime(0, 0, 0)->addSecond()->second);
}
public function testAddMillisecondsPositive()
{
$this->assertSame(1, Carbon::createFromTime(0, 0, 0)->addMilliseconds(1)->millisecond);
}
public function testAddMillisecondsZero()
{
$this->assertSame(100, Carbon::createFromTime(0, 0, 0.1)->addMilliseconds(0)->millisecond);
}
public function testAddMillisecondsNegative()
{
$this->assertSame(999, Carbon::createFromTime(0, 0, 0)->addMilliseconds(-1)->millisecond);
$this->assertSame(99, Carbon::createFromTime(0, 0, 0.1)->addMilliseconds(-1)->millisecond);
}
public function testAddMillisecond()
{
$this->assertSame(101, Carbon::createFromTime(0, 0, 0.1)->addMillisecond()->millisecond);
}
public function testAddMicrosecondsPositive()
{
$this->assertSame(1, Carbon::createFromTime(0, 0, 0)->addMicroseconds(1)->microsecond);
}
public function testAddMicrosecondsZero()
{
$this->assertSame(100000, Carbon::createFromTime(0, 0, 0.1)->addMicroseconds(0)->microsecond);
}
public function testAddMicrosecondsNegative()
{
$this->assertSame(999999, Carbon::createFromTime(0, 0, 0)->addMicroseconds(-1)->microsecond);
$this->assertSame(99999, Carbon::createFromTime(0, 0, 0.1)->addMicroseconds(-1)->microsecond);
}
public function testAddMicrosecond()
{
$this->assertSame(100001, Carbon::createFromTime(0, 0, 0.1)->addMicrosecond()->microsecond);
}
/**
* Test non plural methods with non default args.
*/
public function testAddYearPassingArg()
{
// addYear should ideally be used without argument
/** @var mixed $date */
$date = Carbon::createFromDate(1975);
$this->assertSame(1977, $date->addYear(2)->year);
$this->assertSame(1977, Carbon::createFromDate(1975)->add(2, 'year')->year);
$this->assertSame(1977, Carbon::createFromDate(1975)->add(2, 'years')->year);
$this->assertSame(1977, Carbon::createFromDate(1975)->add(CarbonInterval::years(2))->year);
}
public function testAddDayPassingArg()
{
// addDay should ideally be used without argument
/** @var mixed $date */
$date = Carbon::createFromDate(1975, 5, 10);
$this->assertSame(12, $date->addDay(2)->day);
}
public function testAddHourPassingArg()
{
// addHour should ideally be used without argument
/** @var mixed $date */
$date = Carbon::createFromTime(10);
$this->assertSame(12, $date->addHour(2)->hour);
}
public function testAddMinutePassingArg()
{
// addMinute should ideally be used without argument
/** @var mixed $date */
$date = Carbon::createFromTime(0);
$this->assertSame(2, $date->addMinute(2)->minute);
}
public function testAddSecondPassingArg()
{
// addSecond should ideally be used without argument
/** @var mixed $date */
$date = Carbon::createFromTime(0);
$this->assertSame(2, $date->addSecond(2)->second);
}
public function testAddQuarter()
{
$this->assertSame(8, Carbon::createFromDate(1975, 5, 6)->addQuarter()->month);
}
public function testAddQuarterNegative()
{
// addQuarter should ideally be used without argument
/** @var mixed $date */
$date = Carbon::createFromDate(1975, 5, 6);
$this->assertSame(2, $date->addQuarter(-1)->month);
}
public function testSubQuarter()
{
$this->assertSame(2, Carbon::createFromDate(1975, 5, 6)->subQuarter()->month);
}
public function testSubQuarterNegative()
{
$this->assertCarbon(Carbon::createFromDate(1975, 5, 6)->subQuarters(2), 1974, 11, 6);
}
public function testAddCentury()
{
$this->assertSame(2075, Carbon::createFromDate(1975)->addCentury()->year);
// addCentury should ideally be used without argument
/** @var mixed $date */
$date = Carbon::createFromDate(1975);
$this->assertSame(2075, $date->addCentury(1)->year);
/** @var mixed $date */
$date = Carbon::createFromDate(1975);
$this->assertSame(2175, $date->addCentury(2)->year);
}
public function testAddCenturyNegative()
{
// addCentury should ideally be used without argument
/** @var mixed $date */
$date = Carbon::createFromDate(1975);
$this->assertSame(1875, $date->addCentury(-1)->year);
/** @var mixed $date */
$date = Carbon::createFromDate(1975);
$this->assertSame(1775, $date->addCentury(-2)->year);
}
public function testAddCenturies()
{
$this->assertSame(2075, Carbon::createFromDate(1975)->addCenturies(1)->year);
$this->assertSame(2175, Carbon::createFromDate(1975)->addCenturies(2)->year);
}
public function testAddCenturiesNegative()
{
$this->assertSame(1875, Carbon::createFromDate(1975)->addCenturies(-1)->year);
$this->assertSame(1775, Carbon::createFromDate(1975)->addCenturies(-2)->year);
}
public function testSubCentury()
{
$this->assertSame(1875, Carbon::createFromDate(1975)->subCentury()->year);
// subCentury should ideally be used without argument
/** @var mixed $date */
$date = Carbon::createFromDate(1975);
$this->assertSame(1875, $date->subCentury(1)->year);
/** @var mixed $date */
$date = Carbon::createFromDate(1975);
$this->assertSame(1775, $date->subCentury(2)->year);
}
public function testSubCenturyNegative()
{
// subCentury should ideally be used without argument
/** @var mixed $date */
$date = Carbon::createFromDate(1975);
$this->assertSame(2075, $date->subCentury(-1)->year);
/** @var mixed $date */
$date = Carbon::createFromDate(1975);
$this->assertSame(2175, $date->subCentury(-2)->year);
}
public function testSubCenturies()
{
$this->assertSame(1875, Carbon::createFromDate(1975)->subCenturies(1)->year);
$this->assertSame(1775, Carbon::createFromDate(1975)->subCenturies(2)->year);
}
public function testSubCenturiesNegative()
{
$this->assertSame(2075, Carbon::createFromDate(1975)->subCenturies(-1)->year);
$this->assertSame(2175, Carbon::createFromDate(1975)->subCenturies(-2)->year);
}
public function testAddYearNoOverflow()
{
$this->assertCarbon(Carbon::createFromDate(2016, 2, 29)->addYearNoOverflow(), 2017, 2, 28);
}
public function testAddYearWithOverflow()
{
$this->assertCarbon(Carbon::createFromDate(2016, 2, 29)->addYearWithOverflow(), 2017, 3, 1);
}
public function testAddYearNoOverflowPassingArg()
{
$this->assertCarbon(Carbon::createFromDate(2016, 2, 29)->addYearsNoOverflow(2), 2018, 2, 28);
}
public function testAddYearWithOverflowPassingArg()
{
$this->assertCarbon(Carbon::createFromDate(2016, 2, 29)->addYearsWithOverflow(2), 2018, 3, 1);
}
public function testSubYearNoOverflowPassingArg()
{
$this->assertCarbon(Carbon::createFromDate(2016, 2, 29)->subYearsNoOverflow(2), 2014, 2, 28);
}
public function testSubYearWithOverflowPassingArg()
{
$this->assertCarbon(Carbon::createFromDate(2016, 2, 29)->subYearsWithOverflow(2), 2014, 3, 1);
}
public function testSubYearNoOverflow()
{
$this->assertCarbon(Carbon::createFromDate(2016, 2, 29)->subYearNoOverflow(), 2015, 2, 28);
}
public function testSubYearWithOverflow()
{
$this->assertCarbon(Carbon::createFromDate(2016, 2, 29)->subYearWithOverflow(), 2015, 3, 1);
}
public function testUseYearsOverflow()
{
$this->assertTrue(Carbon::shouldOverflowYears());
$this->assertCarbon(Carbon::createFromDate(2016, 2, 29)->addYears(2), 2018, 3, 1);
Carbon::useYearsOverflow(false);
$this->assertFalse(Carbon::shouldOverflowYears());
$this->assertCarbon(Carbon::createFromDate(2016, 2, 29)->addYears(2), 2018, 2, 28);
Carbon::resetYearsOverflow();
$this->assertTrue(Carbon::shouldOverflowYears());
$this->assertCarbon(Carbon::createFromDate(2016, 2, 29)->addYears(2), 2018, 3, 1);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/DiffTest.php | tests/Carbon/DiffTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\CarbonInterface;
use Carbon\CarbonInterval;
use Carbon\Exceptions\InvalidFormatException;
use Carbon\Exceptions\UnknownUnitException;
use Carbon\Unit;
use Closure;
use DateTime;
use DateTimeImmutable;
use Tests\AbstractTestCase;
use TypeError;
class DiffTest extends AbstractTestCase
{
public function wrapWithTestNow(Closure $func, ?CarbonInterface $dt = null): void
{
parent::wrapWithTestNow($func, $dt ?: Carbon::createMidnightDate(2012, 1, 1));
}
public function testDiffAsCarbonInterval()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertCarbonInterval($dt->diff($dt->copy()->addYear()), 1, 0, 0, 0, 0, 0);
$this->assertTrue($dt->diff($dt)->isEmpty());
}
public function testDiffInYearsPositive()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(1, (int) $dt->diffInYears($dt->copy()->addYear()));
}
public function testDiffInYearsNegativeWithSign()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(-1, (int) $dt->diffInYears($dt->copy()->subYear()));
}
public function testDiffInYearsNegativeNoSign()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(1, (int) $dt->diffInYears($dt->copy()->subYear(), true));
}
public function testDiffInYearsVsDefaultNow()
{
$this->wrapWithTestNow(function () {
$this->assertSame(1, (int) Carbon::now()->subYear()->diffInYears());
});
}
public function testDiffInYearsEnsureIsTruncated()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(1, (int) $dt->diffInYears($dt->copy()->addYear()->addMonths(7)));
}
public function testDiffInQuartersPositive()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(1, (int) $dt->diffInQuarters($dt->copy()->addQuarter()->addDay()));
}
public function testDiffInQuartersNegativeWithSign()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(-4, (int) $dt->diffInQuarters($dt->copy()->subQuarters(4)));
}
public function testDiffInQuartersNegativeWithNoSign()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(4, (int) $dt->diffInQuarters($dt->copy()->subQuarters(4), true));
}
public function testDiffInQuartersVsDefaultNow()
{
$this->wrapWithTestNow(function () {
$this->assertSame(4, (int) Carbon::now()->subYear()->diffInQuarters());
});
}
public function testDiffInQuartersEnsureIsTruncated()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(1, (int) $dt->diffInQuarters($dt->copy()->addQuarter()->addDays(12)));
}
public function testDiffInMonthsPositive()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(13, (int) $dt->diffInMonths($dt->copy()->addYear()->addMonth()));
}
public function testDiffInMonthsNegativeWithSign()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(-11, (int) $dt->diffInMonths($dt->copy()->subYear()->addMonth()));
}
public function testDiffInMonthsWithTimezone()
{
$first = new Carbon('2022-12-01 00:00:00.0 Africa/Nairobi');
$second = new Carbon('2022-11-01 00:00:00.0 Africa/Nairobi');
$this->assertSame(-1, (int) $first->diffInMonths($second, false));
$this->assertSame(1, (int) $second->diffInMonths($first, false));
$this->assertSame(-1.0, $first->diffInMonths($second));
$this->assertSame(1.0, $second->diffInMonths($first));
$first = new Carbon('2022-02-01 16:00 America/Toronto');
$second = new Carbon('2022-01-01 20:00 Europe/Berlin');
$this->assertSame(-1, (int) $first->diffInMonths($second, false));
$this->assertSame(1, (int) $second->diffInMonths($first, false));
$this->assertVeryClose(-1.002976190476190, $first->diffInMonths($second));
$this->assertVeryClose(1.002976190476190, $second->diffInMonths($first));
$first = new Carbon('2022-02-01 01:00 America/Toronto');
$second = new Carbon('2022-01-01 00:00 Europe/Berlin');
$this->assertSame(-1, (int) $first->diffInMonths($second, false));
$this->assertSame(1, (int) $second->diffInMonths($first, false));
$this->assertSame($first->copy()->utc()->diffInMonths($second->copy()->utc()), $first->diffInMonths($second));
$this->assertSame($second->copy()->utc()->diffInMonths($first->copy()->utc()), $second->diffInMonths($first));
$this->assertVeryClose(-(1 + 7 / 24 / 31), $first->diffInMonths($second));
// $second date in Toronto is 2021-12-31 18:00, so we have 6 hours in December (a 31 days month), and 1 hour in February (28 days month)
$this->assertVeryClose(1 + 7 / 24 / 31, $second->diffInMonths($first));
// Considered in Berlin timezone, the 7 extra hours are in February (28 days month)
$first = new Carbon('2022-02-01 01:00 Europe/Berlin');
$second = new Carbon('2022-01-01 00:00 America/Toronto');
$this->assertSame(0, (int) $first->diffInMonths($second, false));
$this->assertSame(0, (int) $second->diffInMonths($first, false));
$this->assertSame($first->copy()->utc()->diffInMonths($second->copy()->utc()), $first->diffInMonths($second));
$this->assertSame($second->copy()->utc()->diffInMonths($first->copy()->utc()), $second->diffInMonths($first));
$this->assertVeryClose(-(1 - 5 / 24 / 31), $first->diffInMonths($second));
$this->assertVeryClose(1 - 5 / 24 / 31, $second->diffInMonths($first));
}
public function testDiffInMonthsNegativeNoSign()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(11, (int) $dt->diffInMonths($dt->copy()->subYear()->addMonth(), true));
}
public function testDiffInMonthsVsDefaultNow()
{
$this->wrapWithTestNow(function () {
$this->assertSame(12, (int) Carbon::now()->subYear()->diffInMonths());
});
}
public function testDiffInMonthsEnsureIsTruncated()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(1, (int) $dt->diffInMonths($dt->copy()->addMonth()->addDays(16)));
}
public function testDiffInDaysPositive()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(366, (int) $dt->diffInDays($dt->copy()->addYear()));
}
public function testDiffInDaysNegativeWithSign()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(-365, (int) $dt->diffInDays($dt->copy()->subYear(), false));
}
public function testDiffInDaysNegativeNoSign()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(-365, (int) $dt->diffInDays($dt->copy()->subYear()));
}
public function testDiffInDaysVsDefaultNow()
{
$this->wrapWithTestNow(function () {
$this->assertSame(7, (int) Carbon::now()->subWeek()->diffInDays());
});
}
public function testDiffInDaysEnsureIsTruncated()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(1, (int) $dt->diffInDays($dt->copy()->addDay()->addHours(13)));
}
public function testDiffInDaysFilteredPositiveWithMutated()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(5, (int) $dt->diffInDaysFiltered(function (Carbon $date) {
return $date->dayOfWeek === 1;
}, $dt->copy()->endOfMonth()));
}
public function testDiffInDaysFilteredPositiveWithSecondObject()
{
$dt1 = Carbon::createFromDate(2000, 1, 1);
$dt2 = Carbon::createFromDate(2000, 1, 31);
$this->assertSame(5, $dt1->diffInDaysFiltered(function (Carbon $date) {
return $date->dayOfWeek === Carbon::SUNDAY;
}, $dt2));
}
public function testDiffInDaysFilteredNegativeNoSignWithMutated()
{
$dt = Carbon::createFromDate(2000, 1, 31);
$this->assertSame(-5, $dt->diffInDaysFiltered(function (Carbon $date) {
return $date->dayOfWeek === Carbon::SUNDAY;
}, $dt->copy()->startOfMonth()));
}
public function testDiffInDaysFilteredNegativeNoSignWithSecondObject()
{
$dt1 = Carbon::createFromDate(2000, 1, 31);
$dt2 = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(5, $dt1->diffInDaysFiltered(function (Carbon $date) {
return $date->dayOfWeek === Carbon::SUNDAY;
}, $dt2, true));
}
public function testDiffInDaysFilteredNegativeWithSignWithMutated()
{
$dt = Carbon::createFromDate(2000, 1, 31);
$this->assertSame(-5, $dt->diffInDaysFiltered(function (Carbon $date) {
return $date->dayOfWeek === 1;
}, $dt->copy()->startOfMonth()));
}
public function testDiffInDaysFilteredNegativeWithSignWithSecondObject()
{
$dt1 = Carbon::createFromDate(2000, 1, 31);
$dt2 = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(-5, $dt1->diffInDaysFiltered(function (Carbon $date) {
return $date->dayOfWeek === Carbon::SUNDAY;
}, $dt2));
}
public function testDiffInHoursFiltered()
{
$dt1 = Carbon::createFromDate(2000, 1, 31)->endOfDay();
$dt2 = Carbon::createFromDate(2000, 1, 1)->startOfDay();
$this->assertSame(-31, $dt1->diffInHoursFiltered(function (Carbon $date) {
return $date->hour === 9;
}, $dt2));
}
public function testDiffInHoursFilteredNegative()
{
$dt1 = Carbon::createFromDate(2000, 1, 31)->endOfDay();
$dt2 = Carbon::createFromDate(2000, 1, 1)->startOfDay();
$this->assertSame(-31, $dt1->diffInHoursFiltered(function (Carbon $date) {
return $date->hour === 9;
}, $dt2));
}
public function testDiffInHoursFilteredWorkHoursPerWeek()
{
$dt1 = Carbon::createFromDate(2000, 1, 5)->endOfDay();
$dt2 = Carbon::createFromDate(2000, 1, 1)->startOfDay();
$this->assertSame(-40, $dt1->diffInHoursFiltered(function (Carbon $date) {
return $date->hour > 8 && $date->hour < 17;
}, $dt2));
}
public function testDiffFilteredUsingMinutesPositiveWithMutated()
{
$dt = Carbon::createFromDate(2000, 1, 1)->startOfDay();
$this->assertSame(60, $dt->diffFiltered(CarbonInterval::minute(), function (Carbon $date) {
return $date->hour === 12;
}, Carbon::createFromDate(2000, 1, 1)->endOfDay()));
}
public function testDiffFilteredPositiveWithSecondObject()
{
$dt1 = Carbon::create(2000, 1, 1);
$dt2 = $dt1->copy()->addSeconds(80);
$this->assertSame(40, $dt1->diffFiltered(CarbonInterval::second(), function (Carbon $date) {
return $date->second % 2 === 0;
}, $dt2));
}
public function testDiffFilteredNegativeNoSignWithMutated()
{
$dt = Carbon::createFromDate(2000, 1, 31);
$this->assertSame(-2, $dt->diffFiltered(CarbonInterval::days(2), function (Carbon $date) {
return $date->dayOfWeek === Carbon::SUNDAY;
}, $dt->copy()->startOfMonth()));
}
public function testDiffFilteredNegativeNoSignWithSecondObject()
{
$dt1 = Carbon::createFromDate(2006, 1, 31);
$dt2 = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(-7, $dt1->diffFiltered(CarbonInterval::year(), function (Carbon $date) {
return $date->month === 1;
}, $dt2));
}
public function testDiffFilteredNegativeWithSignWithMutated()
{
$dt = Carbon::createFromDate(2000, 1, 31);
$this->assertSame(-4, $dt->diffFiltered(CarbonInterval::week(), function (Carbon $date) {
return $date->month === 12;
}, $dt->copy()->subMonths(3), false));
}
public function testDiffFilteredNegativeWithSignWithSecondObject()
{
$dt1 = Carbon::createFromDate(2001, 1, 31);
$dt2 = Carbon::createFromDate(1999, 1, 1);
$this->assertSame(-12, $dt1->diffFiltered(CarbonInterval::month(), function (Carbon $date) {
return $date->year === 2000;
}, $dt2, false));
}
public function testBug188DiffWithSameDates()
{
$start = Carbon::create(2014, 10, 8, 15, 20, 0);
$end = $start->copy();
$this->assertSame(0.0, $start->diffInDays($end));
$this->assertSame(0, $start->diffInWeekdays($end));
}
public function testBug188DiffWithDatesOnlyHoursApart()
{
$start = Carbon::create(2014, 10, 8, 15, 20, 0);
$end = $start->copy();
$this->assertSame(0, (int) $start->diffInDays($end));
$this->assertSame(0, $start->diffInWeekdays($end));
}
public function testBug188DiffWithSameDates1DayApart()
{
$start = Carbon::create(2014, 10, 8, 15, 20, 0);
$end = $start->copy()->addDay();
$this->assertSame(1, (int) $start->diffInDays($end));
$this->assertSame(1, $start->diffInWeekdays($end));
}
public function testBug188DiffWithDatesOnTheWeekend()
{
$start = Carbon::create(2014, 1, 1, 0, 0, 0);
$start->next(Carbon::SATURDAY);
$end = $start->copy()->addDay();
$this->assertSame(1, (int) $start->diffInDays($end));
$this->assertSame(0, $start->diffInWeekdays($end));
}
public function testNearlyOneDayDiff()
{
$this->assertVeryClose(
-0.9999999999884258,
Carbon::parse('2020-09-15 23:29:59.123456')->diffInDays('2020-09-14 23:29:59.123457'),
);
$this->assertVeryClose(
0.9999999999884258,
Carbon::parse('2020-09-14 23:29:59.123457')->diffInDays('2020-09-15 23:29:59.123456'),
);
}
public function testBug2798ConsistencyWithDiffInDays()
{
// 0 hour diff
$s1 = Carbon::create(2023, 6, 6, 15, 0, 0);
$e1 = Carbon::create(2023, 6, 6, 15, 0, 0);
$this->assertSame(0, $s1->diffInWeekdays($e1));
$this->assertSame(0, (int) $s1->diffInDays($e1));
// 1 hour diff
$s2 = Carbon::create(2023, 6, 6, 15, 0, 0);
$e2 = Carbon::create(2023, 6, 6, 16, 0, 0);
$this->assertSame(0, $s2->diffInWeekdays($e2));
$this->assertSame(0, $e2->diffInWeekdays($s2));
$this->assertSame('2023-06-06 15:00:00', $s2->format('Y-m-d H:i:s'));
$this->assertSame('2023-06-06 16:00:00', $e2->format('Y-m-d H:i:s'));
$this->assertSame(0, (int) $s2->diffInDays($e2));
// 23 hour diff
$s3 = Carbon::create(2023, 6, 6, 15, 0, 0);
$e3 = Carbon::create(2023, 6, 7, 14, 0, 0);
$this->assertSame(1, $s3->diffInWeekdays($e3));
$this->assertSame(-1, $e3->diffInWeekdays($s3));
$this->assertSame('2023-06-06 15:00:00', $s3->format('Y-m-d H:i:s'));
$this->assertSame('2023-06-07 14:00:00', $e3->format('Y-m-d H:i:s'));
$this->assertSame(0, (int) $s3->diffInDays($e3));
// 24 hour diff
$s4 = Carbon::create(2023, 6, 6, 15, 0, 0);
$e4 = Carbon::create(2023, 6, 7, 15, 0, 0);
$this->assertSame(1, $s4->diffInWeekdays($e4));
$this->assertSame(-1, $e4->diffInWeekdays($s4));
$this->assertSame(1, (int) $s4->diffInDays($e4));
// 25 hour diff
$s5 = Carbon::create(2023, 6, 6, 15, 0, 0);
$e5 = Carbon::create(2023, 6, 7, 16, 0, 0);
$this->assertSame(1, $s5->diffInWeekdays($e5));
$this->assertSame(-1, $e5->diffInWeekdays($s5));
$this->assertSame('2023-06-06 15:00:00', $s5->format('Y-m-d H:i:s'));
$this->assertSame('2023-06-07 16:00:00', $e5->format('Y-m-d H:i:s'));
$this->assertSame(1, (int) $s5->diffInDays($e5));
}
public function testDiffInWeekdaysPositive()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(21, $dt->diffInWeekdays($dt->copy()->addMonth()));
}
public function testDiffInWeekdaysNegativeNoSign()
{
$dt = Carbon::createFromDate(2000, 1, 31);
$this->assertSame(20, $dt->diffInWeekdays($dt->copy()->startOfMonth(), true));
}
public function testDiffInWeekdaysNegativeWithSign()
{
$dt = Carbon::createFromDate(2000, 1, 31);
$this->assertSame(-20, $dt->diffInWeekdays($dt->copy()->startOfMonth()));
}
public function testDiffInWeekendDaysPositive()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(10, $dt->diffInWeekendDays($dt->copy()->addMonth()));
}
public function testDiffInWeekendDaysNegativeNoSign()
{
$dt = Carbon::createFromDate(2000, 1, 31);
$this->assertSame(10, $dt->diffInWeekendDays($dt->copy()->startOfMonth(), true));
}
public function testDiffInWeekendDaysNegativeWithSign()
{
$dt = Carbon::createFromDate(2000, 1, 31);
$this->assertSame(-10, $dt->diffInWeekendDays($dt->copy()->startOfMonth()));
}
public function testDiffInWeeksPositive()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(52, (int) $dt->diffInWeeks($dt->copy()->addYear()));
}
public function testDiffInWeeksNegativeWithSign()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(-52, (int) $dt->diffInWeeks($dt->copy()->subYear()));
}
public function testDiffInWeeksNegativeNoSign()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(52, (int) $dt->diffInWeeks($dt->copy()->subYear(), true));
}
public function testDiffInWeeksVsDefaultNow()
{
$this->wrapWithTestNow(function () {
$this->assertSame(1, (int) Carbon::now()->subWeek()->diffInWeeks());
});
}
public function testDiffInWeeksEnsureIsTruncated()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(0, (int) $dt->diffInWeeks($dt->copy()->addWeek()->subDay()));
}
public function testDiffInHoursPositive()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(26, (int) $dt->diffInHours($dt->copy()->addDay()->addHours(2)));
}
public function testDiffInHoursNegativeWithSign()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(-22.0, $dt->diffInHours($dt->copy()->subDay()->addHours(2)));
}
public function testDiffInHoursNegativeNoSign()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(22.0, $dt->diffInHours($dt->copy()->subDay()->addHours(2), true));
}
public function testDiffInHoursVsDefaultNow()
{
$this->wrapWithTestNow(function () {
$this->assertSame(48, (int) Carbon::now()->subDays(2)->diffInHours());
}, Carbon::create(2012, 1, 15));
}
public function testDiffInHoursEnsureIsTruncated()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(1, (int) $dt->diffInHours($dt->copy()->addHour()->addMinutes(31)));
}
public function testDiffInHoursWithTimezones()
{
date_default_timezone_set('Africa/Algiers');
Carbon::setTestNow();
$dtToronto = Carbon::create(2012, 1, 1, 0, 0, 0, 'America/Toronto');
$dtVancouver = Carbon::create(2012, 1, 1, 0, 0, 0, 'America/Vancouver');
$this->assertSame(-3.0, $dtVancouver->diffInHours($dtToronto), 'Midnight in Toronto is 3 hours from midnight in Vancouver');
$dtToronto = Carbon::createFromDate(2012, 1, 1, 'America/Toronto');
usleep(2);
$dtVancouver = Carbon::createFromDate(2012, 1, 1, 'America/Vancouver');
$this->assertSame(0, ((int) round($dtVancouver->diffInHours($dtToronto))) % 24);
$dtToronto = Carbon::createMidnightDate(2012, 1, 1, 'America/Toronto');
$dtVancouver = Carbon::createMidnightDate(2012, 1, 1, 'America/Vancouver');
$this->assertSame(-3.0, $dtVancouver->diffInHours($dtToronto), 'Midnight in Toronto is 3 hours from midnight in Vancouver');
}
public function testDiffInMinutesPositive()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(62, (int) $dt->diffInMinutes($dt->copy()->addHour()->addMinutes(2)));
}
public function testDiffInMinutesPositiveALot()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(1502, (int) $dt->diffInMinutes($dt->copy()->addHours(25)->addMinutes(2)));
}
public function testDiffInMinutesNegativeWithSign()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(-58.0, $dt->diffInMinutes($dt->copy()->subHour()->addMinutes(2)));
}
public function testDiffInMinutesNegativeNoSign()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(58.0, $dt->diffInMinutes($dt->copy()->subHour()->addMinutes(2), true));
}
public function testDiffInMinutesVsDefaultNow()
{
$this->wrapWithTestNow(function () {
$this->assertSame(60, (int) Carbon::now()->subHour()->diffInMinutes());
});
}
public function testDiffInMinutesEnsureIsTruncated()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(1, (int) $dt->diffInMinutes($dt->copy()->addMinute()->addSeconds(31)));
}
public function testDiffInSecondsPositive()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(62, (int) $dt->diffInSeconds($dt->copy()->addMinute()->addSeconds(2)));
}
public function testDiffInSecondsPositiveALot()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(7202, (int) $dt->diffInSeconds($dt->copy()->addHours(2)->addSeconds(2)));
}
public function testDiffInSecondsNegativeWithSign()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(-58.0, $dt->diffInSeconds($dt->copy()->subMinute()->addSeconds(2)));
}
public function testDiffInSecondsNegativeNoSign()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(58.0, $dt->diffInSeconds($dt->copy()->subMinute()->addSeconds(2), true));
}
public function testDiffInSecondsVsDefaultNow()
{
$this->wrapWithTestNow(function () {
$this->assertSame(3600, (int) Carbon::now()->subHour()->diffInSeconds());
});
}
public function testDiffInSecondsEnsureIsTruncated()
{
$dt = Carbon::createFromDate(2000, 1, 1);
$this->assertSame(1.0, $dt->diffInSeconds($dt->copy()->addSeconds((int) 1.9)));
}
public function testDiffInSecondsWithTimezones()
{
$dtOttawa = Carbon::createFromDate(2000, 1, 1, 'America/Toronto');
$dtVancouver = Carbon::createFromDate(2000, 1, 1, 'America/Vancouver');
$this->assertSame(0, $dtOttawa->diffInSeconds($dtVancouver) % (24 * 3600));
$dtOttawa = Carbon::createMidnightDate(2000, 1, 1, 'America/Toronto');
$dtVancouver = Carbon::createMidnightDate(2000, 1, 1, 'America/Vancouver');
$this->assertSame(3 * 60 * 60, (int) $dtOttawa->diffInSeconds($dtVancouver));
}
public function testDiffInSecondsWithTimezonesAndVsDefault()
{
$vanNow = Carbon::now('America/Vancouver');
$hereNow = $vanNow->copy()->setTimezone(Carbon::now()->tz);
$this->wrapWithTestNow(function () use ($vanNow) {
$this->assertSame(0, (int) $vanNow->diffInSeconds());
}, $hereNow);
}
public function testDiffForHumansNowAndSecond()
{
$this->wrapWithTestNow(function () {
$this->assertSame('0 seconds ago', Carbon::now()->diffForHumans());
});
}
/**
* @see https://github.com/briannesbitt/Carbon/issues/2136
*/
public function testDiffInTheFuture()
{
Carbon::setTestNow('2020-07-22 09:15');
$this->assertSame(
'1 week from now',
Carbon::parse('2020-07-30 13:51:15')
->diffForHumans(['options' => CarbonInterface::ROUND]),
);
}
public function testDiffWithSkippedUnits()
{
Carbon::setTestNow('2021-11-04 15:42');
$this->assertSame(
'28 weeks from now',
Carbon::parse('2022-05-25')
->diffForHumans(['skip' => ['y', 'm']])
);
$this->assertSame(
'201 days from now',
Carbon::parse('2022-05-25')
->diffForHumans(['skip' => ['y', 'm', 'w']])
);
$this->assertSame(
'4 hours from now',
Carbon::parse('2021-11-04 20:00')
->diffForHumans(['skip' => ['y', 'm', 'w']])
);
$this->assertSame(
'6 hours ago',
Carbon::parse('2021-11-04 09:00')
->diffForHumans(['skip' => ['y', 'm', 'w']])
);
$this->assertSame(
'528 days ago',
Carbon::parse('2020-05-25')
->diffForHumans(['skip' => ['y', 'm', 'w']])
);
Carbon::setTestNow('2023-01-02 16:57');
$this->assertSame(
'1 day 16 hours 57 minutes',
Carbon::yesterday()->diffForHumans([
'syntax' => CarbonInterface::DIFF_ABSOLUTE,
'parts' => 3,
'skip' => 's',
])
);
$this->assertSame(
'2 days 190 minutes ago',
Carbon::parse('-2 days -3 hours -10 minutes')->diffForHumans(['parts' => 3, 'skip' => [Unit::Hour]]),
);
}
public function testDiffForHumansNowAndSecondWithTimezone()
{
$vanNow = Carbon::now('America/Vancouver');
$hereNow = $vanNow->copy()->setTimezone(Carbon::now()->tz);
$this->wrapWithTestNow(function () use ($vanNow) {
$this->assertSame('0 seconds ago', $vanNow->diffForHumans());
}, $hereNow);
}
public function testDiffForHumansNowAndSeconds()
{
$this->wrapWithTestNow(function () {
$this->assertSame('2 seconds ago', Carbon::now()->subSeconds(2)->diffForHumans());
});
}
public function testDiffForHumansNowAndNearlyMinute()
{
$this->wrapWithTestNow(function () {
$this->assertSame('59 seconds ago', Carbon::now()->subSeconds(59)->diffForHumans());
});
}
public function testDiffForHumansNowAndMinute()
{
$this->wrapWithTestNow(function () {
$this->assertSame('1 minute ago', Carbon::now()->subMinute()->diffForHumans());
});
}
public function testDiffForHumansNowAndMinutes()
{
$this->wrapWithTestNow(function () {
$this->assertSame('2 minutes ago', Carbon::now()->subMinutes(2)->diffForHumans());
});
}
public function testDiffForHumansNowAndNearlyHour()
{
$this->wrapWithTestNow(function () {
$this->assertSame('59 minutes ago', Carbon::now()->subMinutes(59)->diffForHumans());
});
}
public function testDiffForHumansNowAndHour()
{
$this->wrapWithTestNow(function () {
$this->assertSame('1 hour ago', Carbon::now()->subHour()->diffForHumans());
});
}
public function testDiffForHumansNowAndHours()
{
$this->wrapWithTestNow(function () {
$this->assertSame('2 hours ago', Carbon::now()->subHours(2)->diffForHumans());
});
}
public function testDiffForHumansNowAndNearlyDay()
{
$this->wrapWithTestNow(function () {
$this->assertSame('23 hours ago', Carbon::now()->subHours(23)->diffForHumans());
});
}
public function testDiffForHumansNowAndDay()
{
$this->wrapWithTestNow(function () {
$this->assertSame('1 day ago', Carbon::now()->subDay()->diffForHumans());
});
}
public function testDiffForHumansNowAndDays()
{
$this->wrapWithTestNow(function () {
$this->assertSame('2 days ago', Carbon::now()->subDays(2)->diffForHumans());
});
}
public function testDiffForHumansNowAndNearlyWeek()
{
$this->wrapWithTestNow(function () {
$this->assertSame('6 days ago', Carbon::now()->subDays(6)->diffForHumans());
});
}
public function testDiffForHumansNowAndWeek()
{
$this->wrapWithTestNow(function () {
$this->assertSame('1 week ago', Carbon::now()->subWeek()->diffForHumans());
});
}
public function testDiffForHumansNowAndWeeks()
{
$this->wrapWithTestNow(function () {
$this->assertSame('2 weeks ago', Carbon::now()->subWeeks(2)->diffForHumans());
});
}
public function testDiffForHumansNowAndNearlyMonth()
{
$this->wrapWithTestNow(function () {
$this->assertSame('3 weeks ago', Carbon::now()->subWeeks(3)->diffForHumans());
});
}
public function testDiffForHumansNowAndMonth()
{
Carbon::setTestNow('2018-12-01');
$this->assertSame('4 weeks ago', Carbon::now()->subWeeks(4)->diffForHumans());
$this->assertSame('1 month ago', Carbon::now()->subMonth()->diffForHumans());
}
public function testDiffForHumansNowAndMonths()
{
$this->wrapWithTestNow(function () {
$this->assertSame('2 months ago', Carbon::now()->subMonthsNoOverflow(2)->diffForHumans());
});
}
public function testDiffForHumansNowAndNearlyYear()
{
$this->wrapWithTestNow(function () {
$this->assertSame('11 months ago', Carbon::now()->subMonthsNoOverflow(11)->diffForHumans());
});
}
public function testDiffForHumansNowAndYear()
{
$this->wrapWithTestNow(function () {
$this->assertSame('1 year ago', Carbon::now()->subYear()->diffForHumans());
});
}
public function testDiffForHumansNowAndYears()
{
$this->wrapWithTestNow(function () {
$this->assertSame('2 years ago', Carbon::now()->subYears(2)->diffForHumans());
});
}
public function testDiffForHumansNowAndFutureSecond()
{
$this->wrapWithTestNow(function () {
$this->assertSame('1 second from now', Carbon::now()->addSecond()->diffForHumans());
});
}
public function testDiffForHumansNowAndFutureSeconds()
{
$this->wrapWithTestNow(function () {
$this->assertSame('2 seconds from now', Carbon::now()->addSeconds(2)->diffForHumans());
});
}
public function testDiffForHumansNowAndNearlyFutureMinute()
{
$this->wrapWithTestNow(function () {
$this->assertSame('59 seconds from now', Carbon::now()->addSeconds(59)->diffForHumans());
});
}
public function testDiffForHumansNowAndFutureMinute()
{
$this->wrapWithTestNow(function () {
$this->assertSame('1 minute from now', Carbon::now()->addMinute()->diffForHumans());
});
}
public function testDiffForHumansNowAndFutureMinutes()
{
$this->wrapWithTestNow(function () {
$this->assertSame('2 minutes from now', Carbon::now()->addMinutes(2)->diffForHumans());
});
}
public function testDiffForHumansNowAndNearlyFutureHour()
{
$this->wrapWithTestNow(function () {
$this->assertSame('59 minutes from now', Carbon::now()->addMinutes(59)->diffForHumans());
});
}
public function testDiffForHumansNowAndFutureHour()
{
$this->wrapWithTestNow(function () {
$this->assertSame('1 hour from now', Carbon::now()->addHour()->diffForHumans());
});
}
public function testDiffForHumansNowAndFutureHours()
{
$this->wrapWithTestNow(function () {
$this->assertSame('2 hours from now', Carbon::now()->addHours(2)->diffForHumans());
});
}
public function testDiffForHumansNowAndNearlyFutureDay()
{
$this->wrapWithTestNow(function () {
$this->assertSame('23 hours from now', Carbon::now()->addHours(23)->diffForHumans());
});
}
public function testDiffForHumansNowAndFutureDay()
{
$this->wrapWithTestNow(function () {
$this->assertSame('1 day from now', Carbon::now()->addDay()->diffForHumans());
});
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | true |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/MacroTest.php | tests/Carbon/MacroTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use BadMethodCallException;
use Carbon\Carbon;
use Carbon\CarbonInterface;
use CarbonTimezoneTrait;
use DateTime;
use SubCarbon;
use Tests\AbstractTestCaseWithOldNow;
use Tests\Carbon\Fixtures\FooBar;
use Tests\Carbon\Fixtures\Mixin;
class MacroTest extends AbstractTestCaseWithOldNow
{
public function testInstance()
{
$this->assertInstanceOf(DateTime::class, $this->now);
$this->assertInstanceOf(Carbon::class, $this->now);
}
public function testCarbonIsMacroableWhenNotCalledDynamically()
{
if (!\function_exists('easter_days')) {
$this->markTestSkipped('This test requires ext-calendar to be enabled.');
}
Carbon::macro('easterDays', function ($year = 2019) {
return easter_days($year);
});
/** @var mixed $now */
$now = Carbon::now();
$this->assertSame(22, $now->easterDays(2020));
$this->assertSame(31, $now->easterDays());
Carbon::macro('otherParameterName', function ($other = true) {
return $other;
});
$this->assertTrue($now->otherParameterName());
}
public function testCarbonIsMacroableWhenNotCalledDynamicallyUsingThis()
{
if (!\function_exists('easter_days')) {
$this->markTestSkipped('This test requires ext-calendar to be enabled.');
}
Carbon::macro('diffFromEaster', function ($year) {
/** @var CarbonInterface $date */
$date = $this;
return $date->toDateTime()->diff(
Carbon::create($year, 3, 21)
->setTimezone($date->getTimezone())
->addDays(easter_days($year))
->endOfDay(),
);
});
/** @var mixed $now */
$now = Carbon::now();
$this->assertSame(1020, $now->diffFromEaster(2020)->days);
}
public function testCarbonIsMacroableWhenCalledStatically()
{
if (!\function_exists('easter_days')) {
$this->markTestSkipped('This test requires ext-calendar to be enabled.');
}
Carbon::macro('easterDate', function ($year) {
return Carbon::create($year, 3, 21)->addDays(easter_days($year));
});
$this->assertSame('05/04', Carbon::easterDate(2015)->format('d/m'));
}
public function testCarbonIsMacroableWithNonClosureCallables()
{
Carbon::macro('lower', 'strtolower');
/** @var mixed $now */
$now = Carbon::now();
$this->assertSame('abc', $now->lower('ABC'));
$this->assertSame('abc', Carbon::lower('ABC'));
}
public function testCarbonIsMixinable()
{
include_once __DIR__.'/Fixtures/Mixin.php';
$mixin = new Mixin('America/New_York');
Carbon::mixin($mixin);
Carbon::setUserTimezone('America/Belize');
/** @var mixed $date */
$date = Carbon::parse('2000-01-01 12:00:00', 'UTC');
$this->assertSame('06:00 America/Belize', $date->userFormat('H:i e'));
}
public function testMacroProperties()
{
// Let say a school year start 5 months before, so school year 2018 is august 2017 to july 2018,
// Then you can create get/set method this way:
Carbon::macro('setSchoolYear', function ($schoolYear) {
/** @var CarbonInterface $date */
$date = $this;
$date->year = $schoolYear;
if ($date->month > 7) {
$date->year--;
}
});
Carbon::macro('getSchoolYear', function () {
/** @var CarbonInterface $date */
$date = $this;
$schoolYear = $date->year;
if ($date->month > 7) {
$schoolYear++;
}
return $schoolYear;
});
// This will make getSchoolYear/setSchoolYear as usual, but get/set prefix will also enable
// getter and setter for the ->schoolYear property
/** @var mixed $date */
$date = Carbon::parse('2016-06-01');
$this->assertSame(2016, $date->schoolYear);
$date->addMonths(3);
$this->assertSame(2017, $date->schoolYear);
$date->schoolYear++;
$this->assertSame(2018, $date->schoolYear);
$this->assertSame('2017-09-01', $date->format('Y-m-d'));
$date->schoolYear = 2020;
$this->assertSame('2019-09-01', $date->format('Y-m-d'));
}
public function testLocalMacroProperties()
{
/** @var mixed $date */
$date = Carbon::parse('2016-06-01')->settings([
'macros' => [
'setSchoolYear' => function ($schoolYear) {
/** @var CarbonInterface $date */
$date = $this;
$date->year = $schoolYear;
if ($date->month > 7) {
$date->year--;
}
},
'getSchoolYear' => function () {
/** @var CarbonInterface $date */
$date = $this;
$schoolYear = $date->year;
if ($date->month > 7) {
$schoolYear++;
}
return $schoolYear;
},
],
]);
$this->assertTrue($date->hasLocalMacro('getSchoolYear'));
$this->assertFalse(Carbon::now()->hasLocalMacro('getSchoolYear'));
$this->assertFalse(Carbon::hasMacro('getSchoolYear'));
$this->assertSame(2016, $date->schoolYear);
$date->addMonths(3);
$this->assertSame(2017, $date->schoolYear);
$date->schoolYear++;
$this->assertSame(2018, $date->schoolYear);
$this->assertSame('2017-09-01', $date->format('Y-m-d'));
$date->schoolYear = 2020;
$this->assertSame('2019-09-01', $date->format('Y-m-d'));
}
public function testMacroOverridingMethod()
{
Carbon::macro('setDate', function ($dateString) {
/** @var CarbonInterface $date */
$date = $this;
$date->modify($dateString);
});
/** @var mixed $date */
$date = Carbon::parse('2016-06-01 11:25:36');
$date->date = '1997-08-26 04:13:56';
$this->assertSame('1997-08-26 04:13:56', $date->format('Y-m-d H:i:s'));
$date->setDate(2001, 4, 13);
$this->assertSame('2001-04-13 04:13:56', $date->format('Y-m-d H:i:s'));
}
public function testCarbonRaisesExceptionWhenStaticMacroIsNotFound()
{
$this->expectExceptionObject(new BadMethodCallException(
'Method Carbon\Carbon::nonExistingStaticMacro does not exist.',
));
Carbon::nonExistingStaticMacro();
}
public function testCarbonRaisesExceptionWhenMacroIsNotFound()
{
$this->expectExceptionObject(new BadMethodCallException(
'Method nonExistingMacro does not exist.',
));
/** @var mixed $date */
$date = Carbon::now();
$date->nonExistingMacro();
}
public function testTraitMixin()
{
Carbon::mixin(FooBar::class);
Carbon::setTestNow('2019-07-19 00:00:00');
$this->assertSame('supergirl / Friday / mutable', Carbon::super('girl'));
$this->assertSame('superboy / Thursday / mutable', Carbon::parse('2019-07-18')->super('boy'));
$this->assertInstanceOf(Carbon::class, Carbon::me());
$this->assertFalse(Carbon::noThis());
$this->assertFalse(Carbon::now()->noThis());
}
public function testTraitWithNamedParameters()
{
require_once __DIR__.'/../Fixtures/CarbonTimezoneTrait.php';
Carbon::mixin(CarbonTimezoneTrait::class);
$now = Carbon::now();
$now = eval("return \$now->toAppTz(tz: 'Europe/Paris');");
$this->assertSame('Europe/Paris', $now->format('e'));
}
public function testSerializationAfterTraitChaining()
{
require_once __DIR__.'/../Fixtures/CarbonTimezoneTrait.php';
Carbon::mixin(CarbonTimezoneTrait::class);
Carbon::setTestNow('2023-05-24 14:49');
$date = Carbon::toAppTz(false, 'Europe/Paris');
$this->assertSame('2023-05-24 16:49 Europe/Paris', unserialize(serialize($date))->format('Y-m-d H:i e'));
$date = Carbon::parse('2023-06-12 11:49')->toAppTz(false, 'Europe/Paris');
$this->assertSame('2023-06-12 13:49 Europe/Paris', unserialize(serialize($date))->format('Y-m-d H:i e'));
}
public function testMutabilityOfMixinMethodReturnedValue()
{
require_once __DIR__.'/../Fixtures/CarbonTimezoneTrait.php';
Carbon::mixin(CarbonTimezoneTrait::class);
Carbon::setTestNow('2023-05-24 14:49');
$now = Carbon::now();
$this->assertSame('Monday', $now->copy()->startOfWeek()->dayName);
$copy = $now->copyWithAppTz(false, 'Europe/Paris');
$this->assertSame('Monday', $copy->copy()->startOfWeek()->dayName);
$this->assertSame('Europe/Paris', $copy->format('e'));
$this->assertSame('UTC', $now->format('e'));
$mutated = $now->toAppTz(false, 'America/Toronto');
$this->assertSame('America/Toronto', $mutated->format('e'));
$this->assertSame('America/Toronto', $now->format('e'));
$this->assertSame(Carbon::class, \get_class($mutated));
$this->assertSame(Carbon::class, \get_class($copy));
$this->assertSame($mutated, $now);
$this->assertEquals($mutated, $copy);
$this->assertNotSame($mutated, $copy);
}
public function testSubClassMacro()
{
require_once __DIR__.'/../Fixtures/SubCarbon.php';
$subCarbon = new SubCarbon('2024-01-24 00:00');
SubCarbon::macro('diffInDecades', function (SubCarbon|string|null $dt = null, $abs = true) {
return (int) ($this->diffInYears($dt, $abs) / 10);
});
$this->assertSame(2, $subCarbon->diffInDecades(new SubCarbon('2049-01-24 00:00')));
$this->assertSame(2, $subCarbon->diffInDecades('2049-01-24 00:00'));
SubCarbon::resetMacros();
}
public function testMacroNameCanStartWithDiff()
{
Carbon::macro('diffInBusinessDays', static fn () => 2);
$this->assertSame(2, Carbon::now()->diffInBusinessDays());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/IsTest.php | tests/Carbon/IsTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use BadMethodCallException;
use Carbon\Carbon;
use Carbon\CarbonInterval;
use Carbon\Month;
use Carbon\Unit;
use Carbon\WeekDay;
use DateInterval;
use DateTime;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\TestWith;
use stdClass;
use Tests\AbstractTestCase;
use TypeError;
class IsTest extends AbstractTestCase
{
public function testIsWeekdayTrue()
{
$this->assertTrue(Carbon::createFromDate(2012, 1, 2)->isWeekday());
}
public function testIsWeekdayFalse()
{
$this->assertFalse(Carbon::createFromDate(2012, 1, 1)->isWeekday());
}
public function testIsWeekendTrue()
{
$this->assertTrue(Carbon::createFromDate(2012, 1, 1)->isWeekend());
}
public function testIsWeekendFalse()
{
$this->assertFalse(Carbon::createFromDate(2012, 1, 2)->isWeekend());
}
public function testIsYesterdayTrue()
{
$this->assertTrue(Carbon::now()->subDay()->isYesterday());
}
public function testIsYesterdayFalseWithToday()
{
$this->assertFalse(Carbon::now()->endOfDay()->isYesterday());
}
public function testIsYesterdayFalseWith2Days()
{
$this->assertFalse(Carbon::now()->subDays(2)->startOfDay()->isYesterday());
}
public function testIsTodayTrue()
{
$this->assertTrue(Carbon::now()->isToday());
}
public function testIsCurrentWeek()
{
$this->assertFalse(Carbon::now()->subWeek()->isCurrentWeek());
$this->assertFalse(Carbon::now()->addWeek()->isCurrentWeek());
$this->assertTrue(Carbon::now()->isCurrentWeek());
$this->assertTrue(Carbon::now()->startOfWeek()->isCurrentWeek());
$this->assertTrue(Carbon::now()->endOfWeek()->isCurrentWeek());
}
public function testIsSameWeek()
{
$this->assertFalse(Carbon::now()->subWeek()->isSameWeek(Carbon::now()));
$this->assertFalse(Carbon::now()->addWeek()->isSameWeek(Carbon::now()));
$this->assertTrue(Carbon::now()->isSameWeek(Carbon::now()));
$this->assertTrue(Carbon::now()->startOfWeek()->isSameWeek(Carbon::now()));
$this->assertTrue(Carbon::now()->endOfWeek()->isSameWeek(Carbon::now()));
$this->assertTrue(Carbon::parse('2019-01-01')->isSameWeek(Carbon::parse('2018-12-31')));
}
public function testIsNextWeekTrue()
{
$this->assertTrue(Carbon::now()->addWeek()->isNextWeek());
}
public function testIsLastWeekTrue()
{
$this->assertTrue(Carbon::now()->subWeek()->isLastWeek());
}
public function testIsNextWeekFalse()
{
/** @var mixed $date */
$date = Carbon::now();
$this->assertFalse($date->addWeek(2)->isNextWeek());
}
public function testIsLastWeekFalse()
{
/** @var mixed $date */
$date = Carbon::now();
$this->assertFalse($date->subWeek(2)->isLastWeek());
}
public function testIsNextQuarterTrue()
{
$this->assertTrue(Carbon::now()->addQuarterNoOverflow()->isNextQuarter());
}
public function testIsLastQuarterTrue()
{
$this->assertTrue(Carbon::now()->subQuarterNoOverflow()->isLastQuarter());
}
public function testIsNextQuarterFalse()
{
$this->assertFalse(Carbon::now()->addQuartersNoOverflow(2)->isNextQuarter());
$this->assertFalse(Carbon::now()->addQuartersNoOverflow(5)->isNextQuarter());
}
public function testIsLastQuarterFalse()
{
$this->assertFalse(Carbon::now()->subQuartersNoOverflow(2)->isLastQuarter());
$this->assertFalse(Carbon::now()->subQuartersNoOverflow(5)->isLastQuarter());
}
public function testIsNextMonthTrue()
{
$this->assertTrue(Carbon::now()->addMonthNoOverflow()->isNextMonth());
}
public function testIsLastMonthTrue()
{
$this->assertTrue(Carbon::now()->subMonthNoOverflow()->isLastMonth());
}
public function testIsNextMonthFalse()
{
$this->assertFalse(Carbon::now()->addMonthsNoOverflow(2)->isNextMonth());
$this->assertFalse(Carbon::now()->addMonthsNoOverflow(13)->isNextMonth());
}
public function testIsLastMonthFalse()
{
Carbon::setTestNow(Carbon::create(2018, 5, 31));
$this->assertFalse(Carbon::now()->subMonthsNoOverflow(2)->isLastMonth());
$this->assertFalse(Carbon::now()->subMonthsNoOverflow(13)->isLastMonth());
}
public function testIsNextYearTrue()
{
$this->assertTrue(Carbon::now()->addYear()->isNextYear());
}
public function testIsLastYearTrue()
{
$this->assertTrue(Carbon::now()->subYear()->isLastYear());
}
public function testIsNextYearFalse()
{
/** @var mixed $date */
$date = Carbon::now();
$this->assertFalse($date->addYear(2)->isNextYear());
}
public function testIsLastYearFalse()
{
/** @var mixed $date */
$date = Carbon::now();
$this->assertFalse($date->subYear(2)->isLastYear());
}
public function testIsTodayFalseWithYesterday()
{
$this->assertFalse(Carbon::now()->subDay()->endOfDay()->isToday());
}
public function testIsTodayFalseWithTomorrow()
{
$this->assertFalse(Carbon::now()->addDay()->startOfDay()->isToday());
}
public function testIsTodayWithTimezone()
{
$this->assertTrue(Carbon::now('Asia/Tokyo')->isToday());
}
public function testIsTomorrowTrue()
{
$this->assertTrue(Carbon::now()->addDay()->isTomorrow());
}
public function testIsTomorrowFalseWithToday()
{
$this->assertFalse(Carbon::now()->endOfDay()->isTomorrow());
}
public function testIsTomorrowFalseWith2Days()
{
$this->assertFalse(Carbon::now()->addDays(2)->startOfDay()->isTomorrow());
}
public function testIsFutureTrue()
{
$this->assertTrue(Carbon::now()->addSecond()->isFuture());
}
public function testIsFutureFalse()
{
$this->assertFalse(Carbon::now()->isFuture());
}
public function testIsFutureFalseInThePast()
{
$this->assertFalse(Carbon::now()->subSecond()->isFuture());
}
public function testIsPastTrue()
{
$this->assertTrue(Carbon::now()->subSecond()->isPast());
}
public function testIsPastFalse()
{
$this->assertFalse(Carbon::now()->addSecond()->isPast());
}
public function testNowIsPastFalse()
{
$this->assertFalse(Carbon::now()->isPast());
}
public function testIsNowOrFutureTrue()
{
$this->assertTrue(Carbon::now()->addSecond()->isNowOrFuture());
}
public function testIsNowOrFutureFalse()
{
$this->assertFalse(Carbon::now()->subSecond()->isNowOrFuture());
}
public function testNowIsNowOrFutureTrue()
{
$this->assertTrue(Carbon::now()->isNowOrFuture());
}
public function testIsNowOrPastTrue()
{
$this->assertTrue(Carbon::now()->subSecond()->isNowOrPast());
}
public function testIsNowOrPastFalse()
{
$this->assertFalse(Carbon::now()->addSecond()->isNowOrPast());
}
public function testNowIsNowOrPastTrue()
{
$this->assertTrue(Carbon::now()->isNowOrPast());
}
public function testIsLeapYearTrue()
{
$this->assertTrue(Carbon::createFromDate(2016, 1, 1)->isLeapYear());
}
public function testIsLeapYearFalse()
{
$this->assertFalse(Carbon::createFromDate(2014, 1, 1)->isLeapYear());
}
public function testIsCurrentYearTrue()
{
$this->assertTrue(Carbon::now()->isCurrentYear());
}
public function testIsCurrentYearFalse()
{
$this->assertFalse(Carbon::now()->subYear()->isCurrentYear());
}
public function testIsSameYearTrue()
{
$this->assertTrue(Carbon::now()->isSameYear(Carbon::now()));
}
public function testIsSameYearFalse()
{
$this->assertFalse(Carbon::now()->isSameYear(Carbon::now()->subYear()));
}
public function testIsCurrentQuarterTrue()
{
$this->assertTrue(Carbon::now()->isCurrentQuarter());
}
public function testIsCurrentQuarterFalse()
{
Carbon::useMonthsOverflow(false);
$this->assertFalse(Carbon::now()->subQuarter()->isCurrentQuarter());
Carbon::resetMonthsOverflow();
}
public function testIsSameQuarterTrue()
{
$this->assertTrue(Carbon::now()->isSameQuarter(Carbon::now()));
}
public function testIsSameQuarterTrueWithDateTime()
{
$this->assertTrue(Carbon::now()->isSameQuarter(new DateTime()));
}
public function testIsSameQuarterFalse()
{
Carbon::useMonthsOverflow(false);
$this->assertFalse(Carbon::now()->isSameQuarter(Carbon::now()->subQuarter()));
Carbon::resetMonthsOverflow();
}
public function testIsSameQuarterFalseWithDateTime()
{
$now = Carbon::now();
$dt = new DateTime();
$dt->modify((Carbon::MONTHS_PER_QUARTER * -1).' month');
if ($dt->format('d') !== $now->format('d')) {
$dt->modify('last day of previous month');
}
$this->assertFalse($now->isSameQuarter($dt));
}
public function testIsSameQuarterAndYearTrue()
{
$this->assertTrue(Carbon::now()->isSameQuarter(Carbon::now(), true));
}
public function testIsSameQuarterAndYearTrueWithDateTime()
{
$this->assertTrue(Carbon::now()->isSameQuarter(new DateTime(), true));
}
public function testIsSameQuarterAndYearFalse()
{
$this->assertFalse(Carbon::now()->isSameQuarter(Carbon::now()->subYear(), true));
}
public function testIsSameQuarterAndYearFalseWithDateTime()
{
$dt = new DateTime();
$dt->modify('-1 year');
$this->assertFalse(Carbon::now()->isSameQuarter($dt, true));
}
public function testIsCurrentMonth()
{
$this->assertTrue(Carbon::now()->isCurrentMonth());
$dt = Carbon::now();
$dt->modify(Carbon::now()->year.$dt->format('-m-').'01');
$this->assertTrue($dt->isCurrentMonth());
$dt->modify((Carbon::now()->year + 1).$dt->format('-m-').'28');
$this->assertFalse($dt->isCurrentMonth());
}
public function testIsCurrentMonthFalse()
{
$this->assertFalse(Carbon::now()->day(15)->subMonth()->isCurrentMonth());
$this->assertFalse(Carbon::now()->day(15)->addYear()->isCurrentMonth());
}
public function testIsSameMonth()
{
$this->assertTrue(Carbon::now()->isSameMonth(Carbon::now()));
$dt = Carbon::now();
for ($year = 1990; $year < Carbon::now()->year; $year++) {
$dt->modify($year.$dt->format('-m-').'01');
$this->assertTrue(Carbon::now()->isSameMonth($dt, false));
$dt->modify($year.$dt->format('-m-').'28');
$this->assertTrue(Carbon::now()->isSameMonth($dt, false));
}
}
public function testIsSameMonthTrueWithDateTime()
{
$this->assertTrue(Carbon::now()->isSameMonth(new DateTime()));
$dt = new DateTime();
for ($year = 1990; $year < 2200; $year++) {
$dt->modify($year.$dt->format('-m-').'01');
$this->assertTrue(Carbon::now()->isSameMonth($dt, false));
$dt->modify($year.$dt->format('-m-').'28');
$this->assertTrue(Carbon::now()->isSameMonth($dt, false));
}
}
public function testIsSameMonthOfSameYear()
{
$this->assertFalse(Carbon::now()->isSameMonth(Carbon::now()->day(15)->subMonth()));
$this->assertTrue(Carbon::now()->isSameMonth(Carbon::now()));
$dt = Carbon::now();
for ($year = 1990; $year < Carbon::now()->year; $year++) {
$dt->modify($year.$dt->format('-m-').'01');
$this->assertFalse(Carbon::now()->isSameMonth($dt, true));
$dt->modify($year.$dt->format('-m-').'28');
$this->assertFalse(Carbon::now()->isSameMonth($dt, true));
}
$year = Carbon::now()->year;
$dt->modify($year.$dt->format('-m-').'01');
$this->assertTrue(Carbon::now()->isSameMonth($dt, true));
$dt->modify($year.$dt->format('-m-').'28');
$this->assertTrue(Carbon::now()->isSameMonth($dt, true));
for ($year = Carbon::now()->year + 1; $year < 2200; $year++) {
$dt->modify($year.$dt->format('-m-').'01');
$this->assertFalse(Carbon::now()->isSameMonth($dt, true));
$dt->modify($year.$dt->format('-m-').'28');
$this->assertFalse(Carbon::now()->isSameMonth($dt, true));
}
}
public function testIsSameMonthFalseWithDateTime()
{
$dt = new DateTime();
$dt->modify('-2 months');
$this->assertFalse(Carbon::now()->isSameMonth($dt));
}
public function testIsSameMonthAndYearTrue()
{
$this->assertTrue(Carbon::now()->isSameMonth(Carbon::now(), true));
$dt = Carbon::now();
$dt->modify($dt->format('Y-m-').'01');
$this->assertTrue(Carbon::now()->isSameMonth($dt, true));
$dt->modify($dt->format('Y-m-').'28');
$this->assertTrue(Carbon::now()->isSameMonth($dt, true));
}
public function testIsSameMonthAndYearTrueWithDateTime()
{
$this->assertTrue(Carbon::now()->isSameMonth(new DateTime(), true));
$dt = new DateTime();
$dt->modify($dt->format('Y-m-').'01');
$this->assertTrue(Carbon::now()->isSameMonth($dt, true));
$dt->modify($dt->format('Y-m-').'28');
$this->assertTrue(Carbon::now()->isSameMonth($dt, true));
}
public function testIsSameMonthAndYearFalse()
{
$this->assertFalse(Carbon::now()->isSameMonth(Carbon::now()->subYear(), true));
}
public function testIsSameMonthAndYearFalseWithDateTime()
{
$dt = new DateTime();
$dt->modify('-1 year');
$this->assertFalse(Carbon::now()->isSameMonth($dt, true));
}
public function testIsSameDayTrue()
{
$current = Carbon::createFromDate(2012, 1, 2);
$this->assertTrue($current->isSameDay(Carbon::createFromDate(2012, 1, 2)));
$this->assertTrue($current->isSameDay(Carbon::create(2012, 1, 2, 23, 59, 59)));
}
public function testIsSameDayWithString()
{
$current = Carbon::createFromDate(2012, 1, 2);
$this->assertTrue($current->isSameDay('2012-01-02 15:00:25'));
$this->assertTrue($current->isSameDay('2012-01-02'));
}
public function testIsSameDayTrueWithDateTime()
{
$current = Carbon::createFromDate(2012, 1, 2);
$this->assertTrue($current->isSameDay(new DateTime('2012-01-02')));
$this->assertTrue($current->isSameDay(new DateTime('2012-01-02 23:59:59')));
}
public function testIsSameDayFalse()
{
$current = Carbon::createFromDate(2012, 1, 2);
$this->assertFalse($current->isSameDay(Carbon::createFromDate(2012, 1, 3)));
$this->assertFalse($current->isSameDay(Carbon::createFromDate(2012, 6, 2)));
}
public function testIsSameDayFalseWithDateTime()
{
$current = Carbon::createFromDate(2012, 1, 2);
$this->assertFalse($current->isSameDay(new DateTime('2012-01-03')));
$this->assertFalse($current->isSameDay(new DateTime('2012-05-02')));
}
public function testIsCurrentDayTrue()
{
$this->assertTrue(Carbon::now()->isCurrentDay());
$this->assertTrue(Carbon::now()->hour(0)->isCurrentDay());
$this->assertTrue(Carbon::now()->hour(23)->isCurrentDay());
}
public function testIsCurrentDayFalse()
{
$this->assertFalse(Carbon::now()->subDay()->isCurrentDay());
$this->assertFalse(Carbon::now()->subMonth()->isCurrentDay());
}
public function testIsSameHourTrue()
{
$current = Carbon::create(2018, 5, 6, 12);
$this->assertTrue($current->isSameHour(Carbon::create(2018, 5, 6, 12)));
$this->assertTrue($current->isSameHour(Carbon::create(2018, 5, 6, 12, 59, 59)));
}
public function testIsSameHourTrueWithDateTime()
{
$current = Carbon::create(2018, 5, 6, 12);
$this->assertTrue($current->isSameHour(new DateTime('2018-05-06T12:00:00')));
$this->assertTrue($current->isSameHour(new DateTime('2018-05-06T12:59:59')));
}
public function testIsSameHourFalse()
{
$current = Carbon::create(2018, 5, 6, 12);
$this->assertFalse($current->isSameHour(Carbon::create(2018, 5, 6, 13)));
$this->assertFalse($current->isSameHour(Carbon::create(2018, 5, 5, 12)));
}
public function testIsSameHourFalseWithDateTime()
{
$current = Carbon::create(2018, 5, 6, 12);
$this->assertFalse($current->isSameHour(new DateTime('2018-05-06T13:00:00')));
$this->assertFalse($current->isSameHour(new DateTime('2018-06-06T12:00:00')));
}
public function testIsCurrentHourTrue()
{
$this->assertTrue(Carbon::now()->isCurrentHour());
$this->assertTrue(Carbon::now()->second(1)->isCurrentHour());
$this->assertTrue(Carbon::now()->second(12)->isCurrentHour());
$this->assertTrue(Carbon::now()->minute(0)->isCurrentHour());
$this->assertTrue(Carbon::now()->minute(59)->second(59)->isCurrentHour());
}
public function testIsCurrentHourFalse()
{
$this->assertFalse(Carbon::now()->subHour()->isCurrentHour());
$this->assertFalse(Carbon::now()->subDay()->isCurrentHour());
}
public function testIsSameMinuteTrue()
{
$current = Carbon::create(2018, 5, 6, 12, 30);
$this->assertTrue($current->isSameMinute(Carbon::create(2018, 5, 6, 12, 30)));
$current = Carbon::create(2018, 5, 6, 12, 30, 15);
$this->assertTrue($current->isSameMinute(Carbon::create(2018, 5, 6, 12, 30, 45)));
}
public function testIsSameMinuteTrueWithDateTime()
{
$current = Carbon::create(2018, 5, 6, 12, 30);
$this->assertTrue($current->isSameMinute(new DateTime('2018-05-06T12:30:00')));
$current = Carbon::create(2018, 5, 6, 12, 30, 20);
$this->assertTrue($current->isSameMinute(new DateTime('2018-05-06T12:30:40')));
}
public function testIsSameMinuteFalse()
{
$current = Carbon::create(2018, 5, 6, 12, 30);
$this->assertFalse($current->isSameMinute(Carbon::create(2018, 5, 6, 13, 31)));
$this->assertFalse($current->isSameMinute(Carbon::create(2019, 5, 6, 13, 30)));
}
public function testIsSameMinuteFalseWithDateTime()
{
$current = Carbon::create(2018, 5, 6, 12, 30);
$this->assertFalse($current->isSameMinute(new DateTime('2018-05-06T13:31:00')));
$this->assertFalse($current->isSameMinute(new DateTime('2018-05-06T17:30:00')));
}
public function testIsCurrentMinuteTrue()
{
$this->assertTrue(Carbon::now()->isCurrentMinute());
$this->assertTrue(Carbon::now()->second(0)->isCurrentMinute());
$this->assertTrue(Carbon::now()->second(59)->isCurrentMinute());
}
public function testIsCurrentMinuteFalse()
{
$this->assertFalse(Carbon::now()->subMinute()->isCurrentMinute());
$this->assertFalse(Carbon::now()->subHour()->isCurrentMinute());
}
public function testIsSameSecondTrue()
{
$current = Carbon::create(2018, 5, 6, 12, 30, 13);
$other = Carbon::create(2018, 5, 6, 12, 30, 13);
$this->assertTrue($current->isSameSecond($other));
$this->assertTrue($current->modify($current->hour.':'.$current->minute.':'.$current->second.'.0')->isSameSecond($other));
$this->assertTrue($current->modify($current->hour.':'.$current->minute.':'.$current->second.'.999999')->isSameSecond($other));
}
public function testIsSameSecondTrueWithDateTime()
{
$current = Carbon::create(2018, 5, 6, 12, 30, 13);
$this->assertTrue($current->isSameSecond(new DateTime('2018-05-06T12:30:13')));
}
public function testIsSameSecondFalse()
{
$current = Carbon::create(2018, 5, 6, 12, 30, 13);
$this->assertFalse($current->isSameSecond(Carbon::create(2018, 5, 6, 12, 30, 55)));
$this->assertFalse($current->isSameSecond(Carbon::create(2018, 5, 6, 14, 30, 13)));
}
public function testIsSameSecondFalseWithDateTime()
{
$current = Carbon::create(2018, 5, 6, 12, 30, 13);
$this->assertFalse($current->isSameSecond(new DateTime('2018-05-06T13:30:54')));
$this->assertFalse($current->isSameSecond(new DateTime('2018-05-06T13:36:13')));
}
public function testIsCurrentSecondTrue()
{
$this->assertTrue(Carbon::now()->isCurrentSecond());
$now = Carbon::now();
$this->assertTrue($now->modify($now->hour.':'.$now->minute.':'.$now->second.'.0')->isCurrentSecond());
$this->assertTrue($now->modify($now->hour.':'.$now->minute.':'.$now->second.'.999999')->isCurrentSecond());
}
public function testIsCurrentSecondFalse()
{
$this->assertFalse(Carbon::now()->subSecond()->isCurrentSecond());
$this->assertFalse(Carbon::now()->subDay()->isCurrentSecond());
}
public function testIsSameMicrosecond()
{
$current = new Carbon('2018-05-06T13:30:54.123456');
$this->assertTrue($current->isSameMicrosecond(new DateTime('2018-05-06T13:30:54.123456')));
$this->assertFalse($current->isSameMicrosecond(new DateTime('2018-05-06T13:30:54.123457')));
$this->assertFalse($current->isSameMicrosecond(new DateTime('2019-05-06T13:30:54.123456')));
$this->assertFalse($current->isSameMicrosecond(new DateTime('2018-05-06T13:30:55.123456')));
$this->assertTrue($current->isSameSecond($current->copy()));
$this->assertTrue(Carbon::now()->isCurrentMicrosecond());
$this->assertFalse(Carbon::now()->subMicrosecond()->isCurrentMicrosecond());
$this->assertFalse(Carbon::now()->isLastMicrosecond());
$this->assertTrue(Carbon::now()->subMicrosecond()->isLastMicrosecond());
$this->assertFalse(Carbon::now()->isNextMicrosecond());
$this->assertTrue(Carbon::now()->addMicrosecond()->isNextMicrosecond());
$this->assertTrue(Carbon::now()->subMicroseconds(Carbon::MICROSECONDS_PER_SECOND)->isLastSecond());
$this->assertSame(4.0, Carbon::now()->subMicroseconds(4 * Carbon::MICROSECONDS_PER_SECOND)->diffInSeconds(Carbon::now()));
}
public function testIsDayOfWeek()
{
// True in the past past
$this->assertTrue(Carbon::createFromDate(2015, 5, 31)->isDayOfWeek(0));
$this->assertTrue(Carbon::createFromDate(2015, 6, 21)->isDayOfWeek(0));
$this->assertTrue(Carbon::now()->subWeek()->previous(Carbon::SUNDAY)->isDayOfWeek(0));
$this->assertTrue(Carbon::now()->subWeek()->previous(Carbon::SUNDAY)->isDayOfWeek('sunday'));
$this->assertTrue(Carbon::now()->subWeek()->previous(Carbon::SUNDAY)->isDayOfWeek('SUNDAY'));
// True in the future
$this->assertTrue(Carbon::now()->addWeek()->previous(Carbon::SUNDAY)->isDayOfWeek(0));
$this->assertTrue(Carbon::now()->addMonth()->previous(Carbon::SUNDAY)->isDayOfWeek(0));
$this->assertTrue(Carbon::now()->addMonth()->previous(Carbon::SUNDAY)->isDayOfWeek('sunday'));
$this->assertTrue(Carbon::now()->addMonth()->previous(Carbon::SUNDAY)->isDayOfWeek('SUNDAY'));
$this->assertTrue(Carbon::now()->addMonth()->previous(Carbon::MONDAY)->isDayOfWeek('monday'));
$this->assertTrue(Carbon::now()->addMonth()->previous(Carbon::MONDAY)->isDayOfWeek('MONDAY'));
// False in the past
$this->assertFalse(Carbon::now()->subWeek()->previous(Carbon::MONDAY)->isDayOfWeek(0));
$this->assertFalse(Carbon::now()->subMonth()->previous(Carbon::MONDAY)->isDayOfWeek(0));
$this->assertFalse(Carbon::now()->subMonth()->previous(Carbon::MONDAY)->isDayOfWeek('sunday'));
$this->assertFalse(Carbon::now()->subMonth()->previous(Carbon::MONDAY)->isDayOfWeek('SUNDAY'));
$this->assertFalse(Carbon::now()->subMonth()->previous(Carbon::SUNDAY)->isDayOfWeek('monday'));
$this->assertFalse(Carbon::now()->subMonth()->previous(Carbon::SUNDAY)->isDayOfWeek('MONDAY'));
// False in the future
$this->assertFalse(Carbon::now()->addWeek()->previous(Carbon::MONDAY)->isDayOfWeek(0));
$this->assertFalse(Carbon::now()->addMonth()->previous(Carbon::MONDAY)->isDayOfWeek(0));
$this->assertFalse(Carbon::now()->addMonth()->previous(Carbon::MONDAY)->isDayOfWeek('sunday'));
$this->assertFalse(Carbon::now()->addMonth()->previous(Carbon::MONDAY)->isDayOfWeek('SUNDAY'));
$this->assertFalse(Carbon::now()->addMonth()->previous(Carbon::SUNDAY)->isDayOfWeek('monday'));
$this->assertFalse(Carbon::now()->addMonth()->previous(Carbon::SUNDAY)->isDayOfWeek('MONDAY'));
}
public function testIsSameAs()
{
$current = Carbon::createFromDate(2012, 1, 2);
$this->assertTrue($current->isSameAs('c', $current));
}
public function testIsSameAsWithInvalidArgument()
{
$this->expectException(TypeError::class);
$current = Carbon::createFromDate(2012, 1, 2);
$current->isSameAs('Y-m-d', new stdClass());
}
public function testIsSunday()
{
// True in the past past
$this->assertTrue(Carbon::createFromDate(2015, 5, 31)->isSunday());
$this->assertTrue(Carbon::createFromDate(2015, 6, 21)->isSunday());
$this->assertTrue(Carbon::now()->subWeek()->previous(Carbon::SUNDAY)->isSunday());
$this->assertTrue(Carbon::now()->subWeek()->previous('Sunday')->isSunday());
// True in the future
$this->assertTrue(Carbon::now()->addWeek()->previous(Carbon::SUNDAY)->isSunday());
$this->assertTrue(Carbon::now()->addMonth()->previous(Carbon::SUNDAY)->isSunday());
// False in the past
$this->assertFalse(Carbon::now()->subWeek()->previous(Carbon::MONDAY)->isSunday());
$this->assertFalse(Carbon::now()->subMonth()->previous(Carbon::MONDAY)->isSunday());
// False in the future
$this->assertFalse(Carbon::now()->addWeek()->previous(Carbon::MONDAY)->isSunday());
$this->assertFalse(Carbon::now()->addMonth()->previous(Carbon::MONDAY)->isSunday());
}
public function testIsMonday()
{
// True in the past past
$this->assertTrue(Carbon::createFromDate(2015, 6, 1)->isMonday());
$this->assertTrue(Carbon::now()->subWeek()->previous(Carbon::MONDAY)->isMonday());
// True in the future
$this->assertTrue(Carbon::now()->addWeek()->previous(Carbon::MONDAY)->isMonday());
$this->assertTrue(Carbon::now()->addMonth()->previous(Carbon::MONDAY)->isMonday());
// False in the past
$this->assertFalse(Carbon::now()->subWeek()->previous(Carbon::TUESDAY)->isMonday());
$this->assertFalse(Carbon::now()->subMonth()->previous(Carbon::TUESDAY)->isMonday());
// False in the future
$this->assertFalse(Carbon::now()->addWeek()->previous(Carbon::TUESDAY)->isMonday());
$this->assertFalse(Carbon::now()->addMonth()->previous(Carbon::TUESDAY)->isMonday());
}
public function testIsTuesday()
{
// True in the past past
$this->assertTrue(Carbon::createFromDate(2015, 6, 2)->isTuesday());
$this->assertTrue(Carbon::now()->subWeek()->previous(Carbon::TUESDAY)->isTuesday());
// True in the future
$this->assertTrue(Carbon::now()->addWeek()->previous(Carbon::TUESDAY)->isTuesday());
$this->assertTrue(Carbon::now()->addMonth()->previous(Carbon::TUESDAY)->isTuesday());
// False in the past
$this->assertFalse(Carbon::now()->subWeek()->previous(Carbon::WEDNESDAY)->isTuesday());
$this->assertFalse(Carbon::now()->subMonth()->previous(Carbon::WEDNESDAY)->isTuesday());
// False in the future
$this->assertFalse(Carbon::now()->addWeek()->previous(Carbon::WEDNESDAY)->isTuesday());
$this->assertFalse(Carbon::now()->addMonth()->previous(Carbon::WEDNESDAY)->isTuesday());
}
public function testIsWednesday()
{
// True in the past past
$this->assertTrue(Carbon::createFromDate(2015, 6, 3)->isWednesday());
$this->assertTrue(Carbon::now()->subWeek()->previous(Carbon::WEDNESDAY)->isWednesday());
// True in the future
$this->assertTrue(Carbon::now()->addWeek()->previous(Carbon::WEDNESDAY)->isWednesday());
$this->assertTrue(Carbon::now()->addMonth()->previous(Carbon::WEDNESDAY)->isWednesday());
// False in the past
$this->assertFalse(Carbon::now()->subWeek()->previous(Carbon::THURSDAY)->isWednesday());
$this->assertFalse(Carbon::now()->subMonth()->previous(Carbon::THURSDAY)->isWednesday());
// False in the future
$this->assertFalse(Carbon::now()->addWeek()->previous(Carbon::THURSDAY)->isWednesday());
$this->assertFalse(Carbon::now()->addMonth()->previous(Carbon::THURSDAY)->isWednesday());
}
public function testIsThursday()
{
// True in the past past
$this->assertTrue(Carbon::createFromDate(2015, 6, 4)->isThursday());
$this->assertTrue(Carbon::now()->subWeek()->previous(Carbon::THURSDAY)->isThursday());
// True in the future
$this->assertTrue(Carbon::now()->addWeek()->previous(Carbon::THURSDAY)->isThursday());
$this->assertTrue(Carbon::now()->addMonth()->previous(Carbon::THURSDAY)->isThursday());
// False in the past
$this->assertFalse(Carbon::now()->subWeek()->previous(Carbon::FRIDAY)->isThursday());
$this->assertFalse(Carbon::now()->subMonth()->previous(Carbon::FRIDAY)->isThursday());
// False in the future
$this->assertFalse(Carbon::now()->addWeek()->previous(Carbon::FRIDAY)->isThursday());
$this->assertFalse(Carbon::now()->addMonth()->previous(Carbon::FRIDAY)->isThursday());
}
public function testIsFriday()
{
// True in the past past
$this->assertTrue(Carbon::createFromDate(2015, 6, 5)->isFriday());
$this->assertTrue(Carbon::now()->subWeek()->previous(Carbon::FRIDAY)->isFriday());
// True in the future
$this->assertTrue(Carbon::now()->addWeek()->previous(Carbon::FRIDAY)->isFriday());
$this->assertTrue(Carbon::now()->addMonth()->previous(Carbon::FRIDAY)->isFriday());
// False in the past
$this->assertFalse(Carbon::now()->subWeek()->previous(Carbon::SATURDAY)->isFriday());
$this->assertFalse(Carbon::now()->subMonth()->previous(Carbon::SATURDAY)->isFriday());
// False in the future
$this->assertFalse(Carbon::now()->addWeek()->previous(Carbon::SATURDAY)->isFriday());
$this->assertFalse(Carbon::now()->addMonth()->previous(Carbon::SATURDAY)->isFriday());
}
public function testIsSaturday()
{
// True in the past past
$this->assertTrue(Carbon::createFromDate(2015, 6, 6)->isSaturday());
$this->assertTrue(Carbon::now()->subWeek()->previous(Carbon::SATURDAY)->isSaturday());
// True in the future
$this->assertTrue(Carbon::now()->addWeek()->previous(Carbon::SATURDAY)->isSaturday());
$this->assertTrue(Carbon::now()->addMonth()->previous(Carbon::SATURDAY)->isSaturday());
// False in the past
$this->assertFalse(Carbon::now()->subWeek()->previous(Carbon::SUNDAY)->isSaturday());
$this->assertFalse(Carbon::now()->subMonth()->previous(Carbon::SUNDAY)->isSaturday());
// False in the future
$this->assertFalse(Carbon::now()->addWeek()->previous(Carbon::SUNDAY)->isSaturday());
$this->assertFalse(Carbon::now()->addMonth()->previous(Carbon::SUNDAY)->isSaturday());
}
public function testIsStartOfMillisecond()
{
$this->assertFalse(Carbon::parse('2025-01-30 21:33:45.999999')->isStartOfMillisecond());
$this->assertTrue(Carbon::parse('2025-01-30 21:33:45')->isStartOfMillisecond());
$this->assertTrue(Carbon::parse('2025-01-30 21:33:45.123')->isStartOfMillisecond());
$this->assertFalse(Carbon::parse('2025-01-30 21:33:45.000001')->isStartOfMillisecond());
$this->assertFalse(Carbon::parse('2025-01-30 21:33:45.999999')->isStartOfMillisecond());
}
public function testIsEndOfMillisecond()
{
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | true |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/StartEndOfTest.php | tests/Carbon/StartEndOfTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\Unit;
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\TestWith;
use Tests\AbstractTestCase;
class StartEndOfTest extends AbstractTestCase
{
public function testStartOfDay()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->startOfDay());
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->day, 0, 0, 0, 0);
}
public function testEndOfDay()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->endOfDay());
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->day, 23, 59, 59, 999999);
}
public function testStartOfMonthIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->startOfMonth());
}
public function testStartOfMonthFromNow()
{
$dt = Carbon::now()->startOfMonth();
$this->assertCarbon($dt, $dt->year, $dt->month, 1, 0, 0, 0);
}
public function testStartOfMonthFromLastDay()
{
$dt = Carbon::create(2000, 1, 31, 2, 3, 4)->startOfMonth();
$this->assertCarbon($dt, 2000, 1, 1, 0, 0, 0);
}
public function testStartOfYearIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->startOfYear());
}
public function testStartOfYearFromNow()
{
$dt = Carbon::now()->startOfYear();
$this->assertCarbon($dt, $dt->year, 1, 1, 0, 0, 0);
}
public function testStartOfYearFromFirstDay()
{
$dt = Carbon::create(2000, 1, 1, 1, 1, 1)->startOfYear();
$this->assertCarbon($dt, 2000, 1, 1, 0, 0, 0);
}
public function testStartOfYearFromLastDay()
{
$dt = Carbon::create(2000, 12, 31, 23, 59, 59)->startOfYear();
$this->assertCarbon($dt, 2000, 1, 1, 0, 0, 0);
}
public function testEndOfMonthIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->endOfMonth());
}
public function testEndOfMonth()
{
$dt = Carbon::create(2000, 1, 1, 2, 3, 4)->endOfMonth();
$this->assertCarbon($dt, 2000, 1, 31, 23, 59, 59, 999999);
}
public function testEndOfMonthFromLastDay()
{
$dt = Carbon::create(2000, 1, 31, 2, 3, 4)->endOfMonth();
$this->assertCarbon($dt, 2000, 1, 31, 23, 59, 59, 999999);
}
public function testEndOfYearIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->endOfYear());
}
public function testEndOfYearFromNow()
{
$dt = Carbon::now()->endOfYear();
$this->assertCarbon($dt, $dt->year, 12, 31, 23, 59, 59, 999999);
}
public function testEndOfYearFromFirstDay()
{
$dt = Carbon::create(2000, 1, 1, 1, 1, 1)->endOfYear();
$this->assertCarbon($dt, 2000, 12, 31, 23, 59, 59, 999999);
}
public function testEndOfYearFromLastDay()
{
$dt = Carbon::create(2000, 12, 31, 23, 59, 59)->endOfYear();
$this->assertCarbon($dt, 2000, 12, 31, 23, 59, 59, 999999);
}
public function testStartOfDecadeIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->startOfDecade());
}
public function testStartOfDecadeFromNow()
{
$dt = Carbon::now()->startOfDecade();
$this->assertCarbon($dt, $dt->year - $dt->year % 10, 1, 1, 0, 0, 0);
}
public function testStartOfDecadeFromFirstDay()
{
$dt = Carbon::create(2000, 1, 1, 1, 1, 1)->startOfDecade();
$this->assertCarbon($dt, 2000, 1, 1, 0, 0, 0);
}
public function testStartOfDecadeFromLastDay()
{
$dt = Carbon::create(2009, 12, 31, 23, 59, 59)->startOfDecade();
$this->assertCarbon($dt, 2000, 1, 1, 0, 0, 0);
}
public function testEndOfDecadeIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->endOfDecade());
}
public function testEndOfDecadeFromNow()
{
$dt = Carbon::now()->endOfDecade();
$this->assertCarbon($dt, $dt->year - $dt->year % 10 + 9, 12, 31, 23, 59, 59, 999999);
}
public function testEndOfDecadeFromFirstDay()
{
$dt = Carbon::create(2000, 1, 1, 1, 1, 1)->endOfDecade();
$this->assertCarbon($dt, 2009, 12, 31, 23, 59, 59, 999999);
}
public function testEndOfDecadeFromLastDay()
{
$dt = Carbon::create(2009, 12, 31, 23, 59, 59)->endOfDecade();
$this->assertCarbon($dt, 2009, 12, 31, 23, 59, 59, 999999);
}
public function testStartOfCenturyIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->startOfCentury());
}
public function testStartOfCenturyFromNow()
{
$now = Carbon::now();
$dt = Carbon::now()->startOfCentury();
$this->assertCarbon($dt, $now->year - $now->year % 100 + 1, 1, 1, 0, 0, 0);
}
public function testStartOfCenturyFromFirstDay()
{
$dt = Carbon::create(2001, 1, 1, 1, 1, 1)->startOfCentury();
$this->assertCarbon($dt, 2001, 1, 1, 0, 0, 0);
}
public function testStartOfCenturyFromLastDay()
{
$dt = Carbon::create(2100, 12, 31, 23, 59, 59)->startOfCentury();
$this->assertCarbon($dt, 2001, 1, 1, 0, 0, 0);
}
public function testStartOfMillenniumIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->startOfMillennium());
}
public function testStartOfMillenniumFromNow()
{
$now = Carbon::now();
$dt = Carbon::now()->startOfMillennium();
$this->assertCarbon($dt, $now->year - $now->year % 1000 + 1, 1, 1, 0, 0, 0);
}
public function testStartOfMillenniumFromFirstDay()
{
$dt = Carbon::create(2001, 1, 1, 1, 1, 1)->startOfMillennium();
$this->assertCarbon($dt, 2001, 1, 1, 0, 0, 0);
}
public function testStartOfMillenniumFromLastDay()
{
$dt = Carbon::create(3000, 12, 31, 23, 59, 59)->startOfMillennium();
$this->assertCarbon($dt, 2001, 1, 1, 0, 0, 0);
}
public function testStartOfHourIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->startOfHour());
}
public function testStartOfHourFromNow()
{
$now = Carbon::now();
$dt = Carbon::now()->startOfHour();
$this->assertCarbon($dt, $now->year, $now->month, $now->day, $now->hour, 0, 0);
}
public function testStartOfHourFromFirstMinute()
{
$dt = Carbon::create(2001, 1, 1, 1, 1, 1)->startOfHour();
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->day, $dt->hour, 0, 0);
}
public function testStartOfHourFromLastMinute()
{
$dt = Carbon::create(2100, 12, 31, 23, 59, 59)->startOfHour();
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->day, $dt->hour, 0, 0);
}
public function testEndOfHourIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->endOfHour());
}
public function testEndOfHourFromNow()
{
$now = Carbon::now();
$dt = Carbon::now()->endOfHour();
$this->assertCarbon($dt, $now->year, $now->month, $now->day, $now->hour, 59, 59, 999999);
}
public function testEndOfHourFromFirstMinute()
{
$dt = Carbon::create(2001, 1, 1, 1, 1, rand(0, 59))->endOfHour();
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->day, $dt->hour, 59, 59, 999999);
}
public function testEndOfHourFromLastMinute()
{
$dt = Carbon::create(2100, 12, 31, 23, 59, rand(0, 59))->endOfHour();
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->day, $dt->hour, 59, 59, 999999);
}
public function testStartOfMinuteIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->startOfMinute());
}
public function testStartOfMinuteFromNow()
{
$now = Carbon::now();
$dt = Carbon::now()->startOfMinute();
$this->assertCarbon($dt, $now->year, $now->month, $now->day, $now->hour, $now->minute, 0);
}
public function testStartOfMinuteFromFirstSecond()
{
$dt = Carbon::create(2001, 1, 1, 1, 1, 1)->startOfMinute();
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->day, $dt->hour, $dt->minute, 0);
}
public function testStartOfMinuteFromLastSecond()
{
$dt = Carbon::create(2100, 12, 31, 23, 59, 59)->startOfMinute();
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->day, $dt->hour, $dt->minute, 0);
}
public function testEndOfMinuteIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->endOfMinute());
}
public function testEndOfMinuteFromNow()
{
$now = Carbon::now();
$dt = Carbon::now()->endOfMinute();
$this->assertCarbon($dt, $now->year, $now->month, $now->day, $now->hour, $now->minute, 59, 999999);
}
public function testEndOfMinuteFromFirstSecond()
{
$dt = Carbon::create(2001, 1, 1, 1, 1, 1)->endOfMinute();
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->day, $dt->hour, $dt->minute, 59, 999999);
}
public function testEndOfMinuteFromLastSecond()
{
$dt = Carbon::create(2100, 12, 31, 23, 59, 59)->endOfMinute();
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->day, $dt->hour, $dt->minute, 59, 999999);
}
public function testStartOfSecondIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->startOfSecond());
}
public function testStartOfSecondFromNow()
{
$now = Carbon::now();
$dt = Carbon::now()->startOfSecond();
$this->assertCarbon($dt, $now->year, $now->month, $now->day, $now->hour, $now->minute, $now->second, 0);
}
public function testStartOfSecondFromFirstSecond()
{
$dt = Carbon::create(2001, 1, 1, 1, 1, 1)->startOfSecond();
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->day, $dt->hour, $dt->minute, $dt->second, 0);
}
public function testStartOfSecondFromLastSecond()
{
$dt = Carbon::create(2100, 12, 31, 23, 59, 59)->startOfSecond();
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->day, $dt->hour, $dt->minute, $dt->second, 0);
}
public function testEndOfSecondIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->endOfSecond());
}
public function testEndOfSecondFromNow()
{
$now = Carbon::now();
$dt = Carbon::now()->endOfSecond();
$this->assertCarbon($dt, $now->year, $now->month, $now->day, $now->hour, $now->minute, $now->second, 999999);
}
public function testEndOfSecondFromFirstSecond()
{
$dt = Carbon::create(2001, 1, 1, 1, 1, 1)->modify('01:01:01.1')->endOfSecond();
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->day, $dt->hour, $dt->minute, $dt->second, 999999);
}
public function testEndOfSecondFromLastSecond()
{
$dt = Carbon::create(2100, 12, 31, 23, 59, 59)->modify('23:59:59.1')->endOfSecond();
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->day, $dt->hour, $dt->minute, $dt->second, 999999);
}
public function testStartOfSecond()
{
$dt = new Carbon('2000-06-15 23:10:10.123456');
$this->assertCarbon($dt->startOfSecond(), 2000, 6, 15, 23, 10, 10, 0);
$this->assertCarbon($dt->endOfSecond(), 2000, 6, 15, 23, 10, 10, 999999);
}
public function testMidDayIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->midDay());
}
public function testMidDayFromNow()
{
$now = Carbon::now();
$dt = Carbon::now()->midDay();
$this->assertCarbon($dt, $now->year, $now->month, $now->day, 12, 0, 0);
}
public function testEndOfCenturyIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->endOfCentury());
}
public function testEndOfCenturyFromNow()
{
$now = Carbon::now();
$dt = Carbon::now()->endOfCentury();
$this->assertCarbon($dt, $now->year - $now->year % 100 + 100, 12, 31, 23, 59, 59, 999999);
}
public function testEndOfCenturyFromFirstDay()
{
$dt = Carbon::create(2001, 1, 1, 1, 1, 1)->endOfCentury();
$this->assertCarbon($dt, 2100, 12, 31, 23, 59, 59, 999999);
}
public function testEndOfCenturyFromLastDay()
{
$dt = Carbon::create(2100, 12, 31, 23, 59, 59)->endOfCentury();
$this->assertCarbon($dt, 2100, 12, 31, 23, 59, 59, 999999);
}
public function testEndOfMillenniumIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->endOfMillennium());
}
public function testEndOfMillenniumFromNow()
{
$now = Carbon::now();
$dt = Carbon::now()->endOfMillennium();
$this->assertCarbon($dt, $now->year - $now->year % 1000 + 1000, 12, 31, 23, 59, 59);
}
public function testEndOfMillenniumFromFirstDay()
{
$dt = Carbon::create(2001, 1, 1, 1, 1, 1)->endOfMillennium();
$this->assertCarbon($dt, 3000, 12, 31, 23, 59, 59);
}
public function testEndOfMillenniumFromLastDay()
{
$dt = Carbon::create(2100, 12, 31, 23, 59, 59)->endOfMillennium();
$this->assertCarbon($dt, 3000, 12, 31, 23, 59, 59);
}
public function testStartOfQuarterIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->startOfQuarter());
}
#[TestWith([1, 1])]
#[TestWith([2, 1])]
#[TestWith([3, 1])]
#[TestWith([4, 4])]
#[TestWith([5, 4])]
#[TestWith([6, 4])]
#[TestWith([7, 7])]
#[TestWith([8, 7])]
#[TestWith([9, 7])]
#[TestWith([10, 10])]
#[TestWith([11, 10])]
#[TestWith([12, 10])]
public function testStartOfQuarter(int $month, int $startOfQuarterMonth)
{
$dt = Carbon::create(2015, $month, 15, 1, 2, 3);
$this->assertCarbon($dt->startOfQuarter(), 2015, $startOfQuarterMonth, 1, 0, 0, 0);
}
public function testEndOfQuarterIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->endOfQuarter());
}
#[TestWith([1, 3, 31])]
#[TestWith([2, 3, 31])]
#[TestWith([3, 3, 31])]
#[TestWith([4, 6, 30])]
#[TestWith([5, 6, 30])]
#[TestWith([6, 6, 30])]
#[TestWith([7, 9, 30])]
#[TestWith([8, 9, 30])]
#[TestWith([9, 9, 30])]
#[TestWith([10, 12, 31])]
#[TestWith([11, 12, 31])]
#[TestWith([12, 12, 31])]
public function testEndOfQuarter(int $month, int $endOfQuarterMonth, int $endOfQuarterDay)
{
$dt = Carbon::create(2015, $month, 15, 1, 2, 3);
$this->assertCarbon($dt->endOfQuarter(), 2015, $endOfQuarterMonth, $endOfQuarterDay, 23, 59, 59, 999999);
}
public function testAverageIsFluid()
{
$dt = Carbon::now()->average();
$this->assertInstanceOfCarbon($dt);
}
public function testAverageFromSame()
{
$dt1 = Carbon::create(2000, 1, 31, 2, 3, 4);
$dt2 = Carbon::create(2000, 1, 31, 2, 3, 4)->average($dt1);
$this->assertCarbon($dt2, 2000, 1, 31, 2, 3, 4);
}
public function testAverageFromGreater()
{
$dt1 = Carbon::create(2000, 1, 1, 1, 1, 1);
$dt2 = Carbon::create(2009, 12, 31, 23, 59, 59)->average($dt1);
$this->assertCarbon($dt2, 2004, 12, 31, 12, 30, 30);
}
public function testAverageFromLower()
{
$dt1 = Carbon::create(2009, 12, 31, 23, 59, 59);
$dt2 = Carbon::create(2000, 1, 1, 1, 1, 1)->average($dt1);
$this->assertCarbon($dt2, 2004, 12, 31, 12, 30, 30);
}
public function testAverageWithCloseDates()
{
$dt1 = Carbon::parse('2004-01-24 09:46:56.500000');
$dt2 = Carbon::parse('2004-01-24 09:46:56.600000');
$this->assertSame('2004-01-24 09:46:56.550000', $dt1->average($dt2)->format('Y-m-d H:i:s.u'));
}
public function testAverageWithFarDates()
{
$dt1 = Carbon::parse('-2018-05-07 12:34:46.500000', 'UTC');
$dt2 = Carbon::parse('6025-10-11 20:59:06.600000', 'UTC');
$this->assertSame('2004-01-24 04:46:56.550000', $dt1->average($dt2)->format('Y-m-d H:i:s.u'));
}
public function testStartOf()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->startOf('day'));
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->day, 0, 0, 0, 0);
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->startOf(Unit::Day));
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->day, 0, 0, 0, 0);
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->startOf('Months'));
$this->assertCarbon($dt, $dt->year, $dt->month, 1, 0, 0, 0, 0);
}
public function testEndOf()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->endOf('day'));
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->day, 23, 59, 59, 999999);
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->endOf(Unit::Day));
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->day, 23, 59, 59, 999999);
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->endOf('Months'));
$this->assertCarbon($dt, $dt->year, $dt->month, $dt->daysInMonth, 23, 59, 59, 999999);
}
public function testStartOfInvalidUnit()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Unknown unit \'microsecond\'',
));
Carbon::now()->startOf('microsecond');
}
public function testEndOfInvalidUnit()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Unknown unit \'microsecond\'',
));
Carbon::now()->endOf('microsecond');
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/IssetTest.php | tests/Carbon/IssetTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Generator;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\AbstractTestCase;
class IssetTest extends AbstractTestCase
{
public function testIssetReturnFalseForUnknownProperty(): void
{
$this->assertFalse(isset($this->now->sdfsdfss));
}
public static function dataForTestIssetReturnTrueForProperties(): Generator
{
yield ['age'];
yield ['century'];
yield ['day'];
yield ['dayName'];
yield ['dayOfWeek'];
yield ['dayOfWeekIso'];
yield ['dayOfYear'];
yield ['daysInMonth'];
yield ['daysInYear'];
yield ['decade'];
yield ['dst'];
yield ['englishDayOfWeek'];
yield ['englishMonth'];
yield ['firstWeekDay'];
yield ['hour'];
yield ['isoWeek'];
yield ['isoWeekYear'];
yield ['isoWeeksInYear'];
yield ['lastWeekDay'];
yield ['latinMeridiem'];
yield ['latinUpperMeridiem'];
yield ['local'];
yield ['locale'];
yield ['localeDayOfWeek'];
yield ['localeMonth'];
yield ['meridiem'];
yield ['micro'];
yield ['microsecond'];
yield ['millennium'];
yield ['milli'];
yield ['millisecond'];
yield ['milliseconds'];
yield ['minDayName'];
yield ['minute'];
yield ['month'];
yield ['monthName'];
yield ['noZeroHour'];
yield ['offset'];
yield ['offsetHours'];
yield ['offsetMinutes'];
yield ['quarter'];
yield ['second'];
yield ['shortDayName'];
yield ['shortEnglishDayOfWeek'];
yield ['shortEnglishMonth'];
yield ['shortLocaleDayOfWeek'];
yield ['shortLocaleMonth'];
yield ['shortMonthName'];
yield ['timestamp'];
yield ['timezone'];
yield ['timezoneAbbreviatedName'];
yield ['timezoneName'];
yield ['tz'];
yield ['tzAbbrName'];
yield ['tzName'];
yield ['upperMeridiem'];
yield ['utc'];
yield ['week'];
yield ['weekNumberInMonth'];
yield ['weekOfMonth'];
yield ['weekOfYear'];
yield ['weekYear'];
yield ['weeksInYear'];
yield ['year'];
yield ['yearIso'];
}
#[DataProvider('dataForTestIssetReturnTrueForProperties')]
public function testIssetReturnTrueForProperties(string $property): void
{
Carbon::useStrictMode(false);
$this->assertTrue(isset($this->now->{$property}));
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/RelativeTest.php | tests/Carbon/RelativeTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Tests\AbstractTestCase;
class RelativeTest extends AbstractTestCase
{
public function testSecondsSinceMidnight()
{
$d = Carbon::today()->addSeconds(30);
$this->assertSame(30.0, $d->secondsSinceMidnight());
$d = Carbon::today()->addDays(1);
$this->assertSame(0.0, $d->secondsSinceMidnight());
$d = Carbon::today()->addDays(1)->addSeconds(120);
$this->assertSame(120.0, $d->secondsSinceMidnight());
$d = Carbon::today()->addMonths(3)->addSeconds(42);
$this->assertSame(42.0, $d->secondsSinceMidnight());
}
public function testSecondsUntilEndOfDay()
{
$d = Carbon::today()->endOfDay();
$this->assertSame(0.0, $d->secondsUntilEndOfDay());
$d = Carbon::today()->endOfDay()->subSeconds(60);
$this->assertSame(60.0, $d->secondsUntilEndOfDay());
$d = Carbon::create(2014, 10, 24, 12, 34, 56);
$this->assertVeryClose(41103.999999, $d->secondsUntilEndOfDay());
$d = Carbon::create(2014, 10, 24, 0, 0, 0);
$this->assertVeryClose(86399.99999899999, $d->secondsUntilEndOfDay());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/RoundTest.php | tests/Carbon/RoundTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\CarbonInterval;
use DateInterval;
use InvalidArgumentException;
use Tests\AbstractTestCase;
class RoundTest extends AbstractTestCase
{
public function testRoundWithDefaultUnit()
{
$dt = Carbon::create(2315, 7, 18, 22, 42, 17.643971);
$copy = $dt->copy();
$ref = $copy->round();
$this->assertSame($ref, $copy);
$this->assertCarbon($ref, 2315, 7, 18, 22, 42, 18, 0);
$this->assertCarbon($dt->copy()->round(5), 2315, 7, 18, 22, 42, 20, 0);
$this->assertCarbon($dt->copy()->floor()->round(5), 2315, 7, 18, 22, 42, 15, 0);
$this->assertCarbon($dt->copy()->round(3), 2315, 7, 18, 22, 42, 18, 0);
$this->assertCarbon($dt->copy()->round(4), 2315, 7, 18, 22, 42, 16, 0);
$this->assertCarbon($dt->copy()->round(10), 2315, 7, 18, 22, 42, 20, 0);
$this->assertCarbon($dt->copy()->round(0.5), 2315, 7, 18, 22, 42, 17, 500000);
$this->assertCarbon($dt->copy()->round(0.25), 2315, 7, 18, 22, 42, 17, 750000);
$this->assertCarbon($dt->copy()->round(3.8), 2315, 7, 18, 22, 42, 19, 800000);
$this->assertCarbon($dt->copy()->floor(5), 2315, 7, 18, 22, 42, 15, 0);
$this->assertCarbon($dt->copy()->floor()->floor(5), 2315, 7, 18, 22, 42, 15, 0);
$this->assertCarbon($dt->copy()->floor(3), 2315, 7, 18, 22, 42, 15, 0);
$this->assertCarbon($dt->copy()->floor(4), 2315, 7, 18, 22, 42, 16, 0);
$this->assertCarbon($dt->copy()->floor(10), 2315, 7, 18, 22, 42, 10, 0);
$this->assertCarbon($dt->copy()->floor(0.5), 2315, 7, 18, 22, 42, 17, 500000);
$this->assertCarbon($dt->copy()->floor(0.25), 2315, 7, 18, 22, 42, 17, 500000);
$this->assertCarbon($dt->copy()->floor(3.8), 2315, 7, 18, 22, 42, 15, 0);
$this->assertCarbon($dt->copy()->ceil(5), 2315, 7, 18, 22, 42, 20, 0);
$this->assertCarbon($dt->copy()->floor()->ceil(5), 2315, 7, 18, 22, 42, 20, 0);
$this->assertCarbon($dt->copy()->ceil(3), 2315, 7, 18, 22, 42, 18, 0);
$this->assertCarbon($dt->copy()->ceil(4), 2315, 7, 18, 22, 42, 20, 0);
$this->assertCarbon($dt->copy()->ceil(10), 2315, 7, 18, 22, 42, 20, 0);
$this->assertCarbon($dt->copy()->ceil(0.5), 2315, 7, 18, 22, 42, 18, 0);
$this->assertCarbon($dt->copy()->ceil(0.25), 2315, 7, 18, 22, 42, 17, 750000);
$this->assertCarbon($dt->copy()->ceil(3.8), 2315, 7, 18, 22, 42, 19, 800000);
}
public function testRoundWithStrings()
{
$dt = Carbon::create(2315, 7, 18, 22, 42, 17.643971);
$this->assertCarbon($dt->copy()->round('minute'), 2315, 7, 18, 22, 42, 0, 0);
$this->assertCarbon($dt->copy()->floor('5 minutes'), 2315, 7, 18, 22, 40, 0, 0);
$this->assertCarbon($dt->copy()->ceil('5 minutes'), 2315, 7, 18, 22, 45, 0, 0);
}
public function testRoundWithStringsException()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Rounding is only possible with single unit intervals.',
));
Carbon::create(2315, 7, 18, 22, 42, 17.643971)->round('2 hours 5 minutes');
}
public function testRoundWithInterval()
{
$dt = Carbon::create(2315, 7, 18, 22, 42, 17.643971);
$this->assertCarbon($dt->copy()->round(CarbonInterval::minute()), 2315, 7, 18, 22, 42, 0, 0);
$this->assertCarbon($dt->copy()->floor(CarbonInterval::minutes(5)), 2315, 7, 18, 22, 40, 0, 0);
$this->assertCarbon($dt->copy()->ceil(new DateInterval('PT5M')), 2315, 7, 18, 22, 45, 0, 0);
}
public function testRoundWithIntervalException()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Rounding is only possible with single unit intervals.',
));
Carbon::create(2315, 7, 18, 22, 42, 17.643971)->round(CarbonInterval::day()->minutes(5));
}
public function testRoundWithBaseUnit()
{
$dt = Carbon::create(2315, 7, 18, 22, 42, 17.643971);
$copy = $dt->copy();
$ref = $copy->roundSecond();
$this->assertSame($ref, $copy);
$this->assertCarbon($ref, 2315, 7, 18, 22, 42, 18, 0);
$this->assertCarbon($dt->copy()->roundDay(), 2315, 7, 19, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->roundDay(5), 2315, 7, 21, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->ceilDay(), 2315, 7, 19, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->floorDay(), 2315, 7, 18, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->roundYear(), 2316, 1, 1, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->subMonths(2)->roundYear(), 2315, 1, 1, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->roundYear(2), 2315, 1, 1, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->floorYear(2), 2315, 1, 1, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->ceilYear(2), 2317, 1, 1, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->roundMonth(), 2315, 8, 1, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->floorMonth(), 2315, 7, 1, 0, 0, 0, 0);
for ($i = 1; $i <= Carbon::MONTHS_PER_YEAR; $i++) {
$dt = Carbon::parse("2021-$i-01")->endOfMonth()->floorMonth();
$this->assertCarbon($dt, 2021, $i, 1, 0, 0, 0, 0);
}
}
public function testFloorYear()
{
$date = Carbon::create(2022)->endOfYear()->floorYear();
$this->assertCarbon($date, 2022, 1, 1, 0, 0, 0, 0);
$date = Carbon::create(2022)->endOfYear()->floorDay()->floorYear();
$this->assertCarbon($date, 2022, 1, 1, 0, 0, 0, 0);
$date = Carbon::create(2022)->endOfYear()->floorYear();
$this->assertCarbon($date, 2022, 1, 1, 0, 0, 0, 0);
$date = Carbon::create(2022)->addMonths(6)->floorYear();
$this->assertCarbon($date, 2022, 1, 1, 0, 0, 0, 0);
}
public function testCeilYear()
{
$date = Carbon::create(2022)->addMonths(6)->ceilYear();
$this->assertCarbon($date, 2023, 1, 1, 0, 0, 0, 0);
$date = Carbon::create(2022)->endOfYear()->ceilYear();
$this->assertCarbon($date, 2023, 1, 1, 0, 0, 0, 0);
$date = Carbon::create(2022)->ceilYear();
$this->assertCarbon($date, 2022, 1, 1, 0, 0, 0, 0);
$date = Carbon::create(2022)->addMicrosecond()->ceilYear();
$this->assertCarbon($date, 2023, 1, 1, 0, 0, 0, 0);
}
public function testRoundWithMetaUnit()
{
$dt = Carbon::create(2315, 7, 18, 22, 42, 17.643971);
$copy = $dt->copy();
$ref = $copy->roundSecond();
$this->assertSame($ref, $copy);
$this->assertCarbon($ref, 2315, 7, 18, 22, 42, 18, 0);
$this->assertCarbon($dt->copy()->roundMillisecond(), 2315, 7, 18, 22, 42, 17, 644000);
$this->assertCarbon($dt->copy()->roundMillennium(), 2001, 1, 1, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->roundQuarter(), 2315, 7, 1, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->roundQuarters(2), 2315, 7, 1, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->subMonth()->floorQuarter(), 2315, 4, 1, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->subMonth()->floorQuarters(2), 2315, 1, 1, 0, 0, 0, 0);
}
public function testRoundWeek()
{
$dt = Carbon::create(2315, 7, 18, 22, 42, 17.643971);
$copy = $dt->copy();
$ref = $copy->roundSecond();
$this->assertSame($ref, $copy);
$this->assertCarbon($ref, 2315, 7, 18, 22, 42, 18, 0);
$this->assertCarbon($dt->copy()->floorWeek(), 2315, 7, 12, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->ceilWeek(), 2315, 7, 19, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->roundWeek(), 2315, 7, 19, 0, 0, 0, 0);
$dt = Carbon::create(2315, 7, 19, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->floorWeek(), 2315, 7, 19, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->ceilWeek(), 2315, 7, 19, 0, 0, 0, 0);
$this->assertCarbon($dt->copy()->roundWeek(), 2315, 7, 19, 0, 0, 0, 0);
}
public function testCeilMonth()
{
$this->assertCarbon(Carbon::parse('2021-01-29')->ceilMonth(), 2021, 2, 1, 0, 0, 0);
$this->assertCarbon(Carbon::parse('2021-01-31')->ceilMonth(), 2021, 2, 1, 0, 0, 0);
$this->assertCarbon(Carbon::parse('2021-12-17')->ceilMonth(), 2022, 1, 1, 0, 0, 0);
}
public function testFloorMonth()
{
$this->assertCarbon(Carbon::parse('2021-05-31')->floorMonth(3), 2021, 4, 1, 0, 0, 0);
}
public function testRoundInvalidArgument()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Unknown unit \'foobar\'.',
));
Carbon::now()->roundUnit('foobar');
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/AddMonthsTest.php | tests/Carbon/AddMonthsTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Generator;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\AbstractTestCase;
class AddMonthsTest extends AbstractTestCase
{
/**
* @var \Carbon\Carbon
*/
private $carbon;
protected function setUp(): void
{
parent::setUp();
$date = Carbon::create(2016, 1, 31);
$this->carbon = $date;
}
public static function dataForTestAddMonthNoOverflow(): Generator
{
yield [-2, 2015, 11, 30];
yield [-1, 2015, 12, 31];
yield [0, 2016, 1, 31];
yield [1, 2016, 2, 29];
yield [2, 2016, 3, 31];
}
#[DataProvider('dataForTestAddMonthNoOverflow')]
public function testAddMonthNoOverflow(int $months, int $y, int $m, int $d)
{
$this->assertCarbon($this->carbon->addMonthNoOverflow($months), $y, $m, $d);
}
#[DataProvider('dataForTestAddMonthNoOverflow')]
public function testAddMonthsNoOverflow(int $months, int $y, int $m, int $d)
{
$this->assertCarbon($this->carbon->addMonthsNoOverflow($months), $y, $m, $d);
}
public static function dataForTestSubMonthNoOverflow(): Generator
{
yield [-2, 2016, 3, 31];
yield [-1, 2016, 2, 29];
yield [0, 2016, 1, 31];
yield [1, 2015, 12, 31];
yield [2, 2015, 11, 30];
}
#[DataProvider('dataForTestSubMonthNoOverflow')]
public function testSubMonthNoOverflow(int $months, int $y, int $m, int $d)
{
$this->assertCarbon($this->carbon->subMonthNoOverflow($months), $y, $m, $d);
}
#[DataProvider('dataForTestSubMonthNoOverflow')]
public function testSubMonthsNoOverflow(int $months, int $y, int $m, int $d)
{
$this->assertCarbon($this->carbon->subMonthsNoOverflow($months), $y, $m, $d);
}
public static function dataForTestAddMonthWithOverflow(): Generator
{
yield [-2, 2015, 12, 1];
yield [-1, 2015, 12, 31];
yield [0, 2016, 1, 31];
yield [1, 2016, 3, 2];
yield [2, 2016, 3, 31];
}
#[DataProvider('dataForTestAddMonthWithOverflow')]
public function testAddMonthWithOverflow(int $months, int $y, int $m, int $d)
{
$this->assertCarbon($this->carbon->addMonthWithOverflow($months), $y, $m, $d);
}
#[DataProvider('dataForTestAddMonthWithOverflow')]
public function testAddMonthsWithOverflow(int $months, int $y, int $m, int $d)
{
$this->assertCarbon($this->carbon->addMonthsWithOverflow($months), $y, $m, $d);
}
public static function dataForTestSubMonthWithOverflow(): Generator
{
yield [-2, 2016, 3, 31];
yield [-1, 2016, 3, 2];
yield [0, 2016, 1, 31];
yield [1, 2015, 12, 31];
yield [2, 2015, 12, 1];
}
#[DataProvider('dataForTestSubMonthWithOverflow')]
public function testSubMonthWithOverflow(int $months, int $y, int $m, int $d)
{
$this->assertCarbon($this->carbon->subMonthWithOverflow($months), $y, $m, $d);
}
#[DataProvider('dataForTestSubMonthWithOverflow')]
public function testSubMonthsWithOverflow(int $months, int $y, int $m, int $d)
{
$this->assertCarbon($this->carbon->subMonthsWithOverflow($months), $y, $m, $d);
}
public function testSetOverflowIsTrue()
{
Carbon::useMonthsOverflow(true);
$this->assertTrue(Carbon::shouldOverflowMonths());
}
public function testSetOverflowIsFalse()
{
Carbon::useMonthsOverflow(false);
$this->assertFalse(Carbon::shouldOverflowMonths());
}
public function testSetOverflowIsResetInTests()
{
$this->assertTrue(Carbon::shouldOverflowMonths());
}
public function testSetOverflowIsReset()
{
Carbon::useMonthsOverflow(false);
$this->assertFalse(Carbon::shouldOverflowMonths());
Carbon::resetMonthsOverflow();
$this->assertTrue(Carbon::shouldOverflowMonths());
}
#[DataProvider('dataForTestAddMonthWithOverflow')]
public function testUseOverflowAddMonth(int $months, int $y, int $m, int $d)
{
Carbon::useMonthsOverflow(true);
$this->assertCarbon($this->carbon->addMonth($months), $y, $m, $d);
}
#[DataProvider('dataForTestAddMonthWithOverflow')]
public function testUseOverflowAddMonths(int $months, int $y, int $m, int $d)
{
Carbon::useMonthsOverflow(true);
$this->assertCarbon($this->carbon->addMonths($months), $y, $m, $d);
}
#[DataProvider('dataForTestSubMonthWithOverflow')]
public function testUseOverflowSubMonth(int $months, int $y, int $m, int $d)
{
Carbon::useMonthsOverflow(true);
$this->assertCarbon($this->carbon->subMonth($months), $y, $m, $d);
}
#[DataProvider('dataForTestSubMonthWithOverflow')]
public function testUseOverflowSubMonths(int $months, int $y, int $m, int $d)
{
Carbon::useMonthsOverflow(true);
$this->assertCarbon($this->carbon->subMonths($months), $y, $m, $d);
}
#[DataProvider('dataForTestAddMonthNoOverflow')]
public function testSkipOverflowAddMonth(int $months, int $y, int $m, int $d)
{
Carbon::useMonthsOverflow(false);
$this->assertCarbon($this->carbon->addMonth($months), $y, $m, $d);
}
#[DataProvider('dataForTestAddMonthNoOverflow')]
public function testSkipOverflowAddMonths(int $months, int $y, int $m, int $d)
{
Carbon::useMonthsOverflow(false);
$this->assertCarbon($this->carbon->addMonths($months), $y, $m, $d);
}
#[DataProvider('dataForTestSubMonthNoOverflow')]
public function testSkipOverflowSubMonth(int $months, int $y, int $m, int $d)
{
Carbon::useMonthsOverflow(false);
$this->assertCarbon($this->carbon->subMonth($months), $y, $m, $d);
}
#[DataProvider('dataForTestSubMonthNoOverflow')]
public function testSkipOverflowSubMonths(int $months, int $y, int $m, int $d)
{
Carbon::useMonthsOverflow(false);
$this->assertCarbon($this->carbon->subMonths($months), $y, $m, $d);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/ModifyNearDSTChangeTest.php | tests/Carbon/ModifyNearDSTChangeTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Generator;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use Tests\AbstractTestCase;
class ModifyNearDSTChangeTest extends AbstractTestCase
{
/**
* Tests transition through DST change hour in non default timezone.
*/
#[Group('dst')]
#[DataProvider('dataForTransitionTests')]
public function testTransitionInNonDefaultTimezone(string $dateString, int $addHours, string $expected)
{
date_default_timezone_set('Europe/london');
$date = Carbon::parse($dateString, 'America/New_York');
$date->addHours($addHours);
$this->assertSame($expected, $date->format('c'));
}
/**
* Tests transition through DST change hour in default timezone.
*/
#[Group('dst')]
#[DataProvider('dataForTransitionTests')]
public function testTransitionInDefaultTimezone(string $dateString, int $addHours, string $expected)
{
date_default_timezone_set('America/New_York');
$date = Carbon::parse($dateString, 'America/New_York');
$date->addHours($addHours);
$this->assertSame($expected, $date->format('c'));
}
public static function dataForTransitionTests(): Generator
{
// arguments:
// - Date string to Carbon::parse in America/New_York.
// - Hours to add
// - Resulting string in 'c' format
// testForwardTransition
// When standard time was about to reach 2010-03-14T02:00:00-05:00 clocks were turned forward 1 hour to
// 2010-03-14T03:00:00-04:00 local daylight time instead
yield [
'2010-03-14T00:00:00',
24,
'2010-03-15T01:00:00-04:00',
];
// testBackwardTransition
// When local daylight time was about to reach 2010-11-07T02:00:00-04:00 clocks were turned backward 1 hour
// to 2010-11-07T01:00:00-05:00 local standard time instead
yield ['2010-11-07T00:00:00', 24, '2010-11-07T23:00:00-05:00'];
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/ModifyTest.php | tests/Carbon/ModifyTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\Exceptions\InvalidFormatException;
use Closure;
use DateMalformedStringException;
use InvalidArgumentException;
use Tests\AbstractTestCase;
class ModifyTest extends AbstractTestCase
{
public function testSimpleModify()
{
$a = new Carbon('2014-03-30 00:00:00');
$b = $a->copy();
$b->addHours(24);
$this->assertSame(24.0, $a->diffInHours($b));
}
public function testTimezoneModify()
{
$php81Fix = 1.0;
// For daylight saving time reason 2014-03-30 0h59 is immediately followed by 2h00
$a = new Carbon('2014-03-30 00:00:00', 'Europe/London');
$b = $a->copy();
$b->addHours(24);
$this->assertSame(23.0 + $php81Fix, $a->diffInRealHours($b));
$this->assertSame(23.0 + $php81Fix, $b->diffInRealHours($a, true));
$this->assertSame(-(23.0 + $php81Fix), $b->diffInRealHours($a));
$this->assertSame(-(23.0 + $php81Fix) * 60, $b->diffInRealMinutes($a));
$this->assertSame(-(23.0 + $php81Fix) * 60 * 60, $b->diffInRealSeconds($a));
$this->assertSame(-(23.0 + $php81Fix) * 60 * 60 * 1000, $b->diffInRealMilliseconds($a));
$this->assertSame(-(23.0 + $php81Fix) * 60 * 60 * 1000000, $b->diffInRealMicroseconds($a));
$a = new Carbon('2014-03-30 00:00:00', 'Europe/London');
$b = $a->copy();
$b->addUTCHours(24);
$this->assertSame(-24.0, $b->diffInHours($a, false));
$this->assertSame(-24.0 * 60, $b->diffInMinutes($a, false));
$this->assertSame(-24.0 * 60 * 60, $b->diffInSeconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000, $b->diffInMilliseconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000000, $b->diffInMicroseconds($a, false));
$b->subRealHours(24);
$this->assertSame(0.0, $b->diffInHours($a, false));
$this->assertSame(0.0, $b->diffInHours($a, false));
$a = new Carbon('2014-03-30 00:59:00', 'Europe/London');
$a->addRealHour();
$this->assertSame('02:59', $a->format('H:i'));
$a->subRealHour();
$this->assertSame('00:59', $a->format('H:i'));
$a = new Carbon('2014-03-30 00:59:00', 'Europe/London');
$a->addRealMinutes(2);
$this->assertSame('02:01', $a->format('H:i'));
$a->subRealMinutes(2);
$this->assertSame('00:59', $a->format('H:i'));
$a = new Carbon('2014-03-30 00:59:30', 'Europe/London');
$a->addRealMinute();
$this->assertSame('02:00:30', $a->format('H:i:s'));
$a->subRealMinute();
$this->assertSame('00:59:30', $a->format('H:i:s'));
$a = new Carbon('2014-03-30 00:59:30', 'Europe/London');
$a->addRealSeconds(40);
$this->assertSame('02:00:10', $a->format('H:i:s'));
$a->subRealSeconds(40);
$this->assertSame('00:59:30', $a->format('H:i:s'));
$a = new Carbon('2014-03-30 00:59:59', 'Europe/London');
$a->addRealSecond();
$this->assertSame('02:00:00', $a->format('H:i:s'));
$a->subRealSecond();
$this->assertSame('00:59:59', $a->format('H:i:s'));
$a = new Carbon('2014-03-30 00:59:59.990000', 'Europe/London');
$a->addRealMilliseconds(20);
$this->assertSame('02:00:00.010000', $a->format('H:i:s.u'));
$a->subRealMilliseconds(20);
$this->assertSame('00:59:59.990000', $a->format('H:i:s.u'));
$a = new Carbon('2014-03-30 00:59:59.999990', 'Europe/London');
$a->addRealMicroseconds(20);
$this->assertSame('02:00:00.000010', $a->format('H:i:s.u'));
$a->subRealMicroseconds(20);
$this->assertSame('00:59:59.999990', $a->format('H:i:s.u'));
$a = new Carbon('2014-03-30 00:59:59.999999', 'Europe/London');
$a->addRealMicrosecond();
$this->assertSame('02:00:00.000000', $a->format('H:i:s.u'));
$a->subRealMicrosecond();
$this->assertSame('00:59:59.999999', $a->format('H:i:s.u'));
$a = new Carbon('2014-03-30 00:00:00', 'Europe/London');
$b = $a->copy();
$b->addRealDay();
$this->assertSame(-24.0, $b->diffInHours($a, false));
$this->assertSame(-24.0 * 60, $b->diffInMinutes($a, false));
$this->assertSame(-24.0 * 60 * 60, $b->diffInSeconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000, $b->diffInMilliseconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000000, $b->diffInMicroseconds($a, false));
$a = new Carbon('2014-03-30 00:00:00', 'Europe/London');
$b = $a->copy();
$b->addUTCDay();
$this->assertSame(-24.0, $b->diffInHours($a, false));
$this->assertSame(-24.0 * 60, $b->diffInMinutes($a, false));
$this->assertSame(-24.0 * 60 * 60, $b->diffInSeconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000, $b->diffInMilliseconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000000, $b->diffInMicroseconds($a, false));
$a = new Carbon('2014-03-30 00:00:00', 'Europe/London');
$b = $a->copy();
$b->addRealWeeks(1 / 7);
$this->assertSame(-24.0, $b->diffInHours($a, false));
$this->assertSame(-24.0 * 60, $b->diffInMinutes($a, false));
$this->assertSame(-24.0 * 60 * 60, $b->diffInSeconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000, $b->diffInMilliseconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000000, $b->diffInMicroseconds($a, false));
$a = new Carbon('2014-03-30 00:00:00', 'Europe/London');
$b = $a->copy();
$b->addRealMonths(1 / 30);
$this->assertSame(-24.0, $b->diffInHours($a, false));
$this->assertSame(-24.0 * 60, $b->diffInMinutes($a, false));
$this->assertSame(-24.0 * 60 * 60, $b->diffInSeconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000, $b->diffInMilliseconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000000, $b->diffInMicroseconds($a, false));
$a = new Carbon('2014-03-30 00:00:00', 'Europe/London');
$b = $a->copy();
$b->addRealQuarters(1 / 90);
$this->assertSame(-24.0, $b->diffInHours($a, false));
$this->assertSame(-24.0 * 60, $b->diffInMinutes($a, false));
$this->assertSame(-24.0 * 60 * 60, $b->diffInSeconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000, $b->diffInMilliseconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000000, $b->diffInMicroseconds($a, false));
$a = new Carbon('2014-03-30 00:00:00', 'Europe/London');
$b = $a->copy();
$b->addRealYears(1 / 365);
$this->assertSame(-24.0, $b->diffInHours($a, false));
$this->assertSame(-24.0 * 60, $b->diffInMinutes($a, false));
$this->assertSame(-24.0 * 60 * 60, $b->diffInSeconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000, $b->diffInMilliseconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000000, $b->diffInMicroseconds($a, false));
$a = new Carbon('2014-03-30 00:00:00', 'Europe/London');
$b = $a->copy();
$b->addRealDecades(1 / 3650);
$this->assertSame(-24.0, $b->diffInHours($a, false));
$this->assertSame(-24.0 * 60, $b->diffInMinutes($a, false));
$this->assertSame(-24.0 * 60 * 60, $b->diffInSeconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000, $b->diffInMilliseconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000000, $b->diffInMicroseconds($a, false));
$a = new Carbon('2014-03-30 00:00:00', 'Europe/London');
$b = $a->copy();
$b->addRealCenturies(1 / 36500);
$this->assertSame(-24.0, $b->diffInHours($a, false));
$this->assertSame(-24.0 * 60, $b->diffInMinutes($a, false));
$this->assertSame(-24.0 * 60 * 60, $b->diffInSeconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000, $b->diffInMilliseconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000000, $b->diffInMicroseconds($a, false));
$a = new Carbon('2014-03-30 00:00:00', 'Europe/London');
$b = $a->copy();
$b->addRealMillennia(1 / 365000);
$this->assertSame(-24.0, $b->diffInHours($a, false));
$this->assertSame(-24.0 * 60, $b->diffInMinutes($a, false));
$this->assertSame(-24.0 * 60 * 60, $b->diffInSeconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000, $b->diffInMilliseconds($a, false));
$this->assertSame(-24.0 * 60 * 60 * 1000000, $b->diffInMicroseconds($a, false));
}
public function testAddRealUnitException()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Invalid unit for real timestamp add/sub: \'foobar\'',
));
(new Carbon('2014-03-30 00:00:00'))->addRealUnit('foobar');
}
public function testAddRealMicrosecondWithLowFloatPrecision()
{
$precision = ini_set('precision', '9');
$a = new Carbon('2014-03-30 00:59:59.999999', 'Europe/London');
$a->addRealMicrosecond();
$this->assertSame('02:00:00.000000', $a->format('H:i:s.u'));
ini_set('precision', $precision);
}
public function testNextAndPrevious()
{
Carbon::setTestNow('2019-06-02 13:27:09.816752');
$this->assertSame('2019-06-02 14:00:00', Carbon::now()->next('2pm')->format('Y-m-d H:i:s'));
$this->assertSame('2019-06-01 14:00:00', Carbon::now()->previous('2pm')->format('Y-m-d H:i:s'));
$this->assertSame('2019-06-02 14:00:00', Carbon::now()->next('14h')->format('Y-m-d H:i:s'));
$this->assertSame('2019-06-01 14:00:00', Carbon::now()->previous('14h')->format('Y-m-d H:i:s'));
$this->assertSame('2019-06-03 09:00:00', Carbon::now()->next('9am')->format('Y-m-d H:i:s'));
$this->assertSame('2019-06-02 09:00:00', Carbon::now()->previous('9am')->format('Y-m-d H:i:s'));
$this->assertSame('2019-06-02 14:00:00', Carbon::parse('next 2pm')->format('Y-m-d H:i:s'));
$this->assertSame('2019-06-01 14:00:00', Carbon::parse('previous 2pm')->format('Y-m-d H:i:s'));
$this->assertSame('2019-06-02 14:00:00', Carbon::parse('next 14h')->format('Y-m-d H:i:s'));
$this->assertSame('2019-06-01 14:00:00', Carbon::parse('previous 14h')->format('Y-m-d H:i:s'));
$this->assertSame('2019-06-03 09:00:00', Carbon::parse('next 9am')->format('Y-m-d H:i:s'));
$this->assertSame('2019-06-02 09:00:00', Carbon::parse('previous 9am')->format('Y-m-d H:i:s'));
$this->assertSame(
'2019-06-04 00:00:00',
Carbon::parse('after tomorrow')->format('Y-m-d H:i:s'),
);
$this->assertSame(
'2000-01-27 00:00:00',
Carbon::parse('2000-01-25')->change('after tomorrow')->format('Y-m-d H:i:s'),
);
$this->assertSame(
'2019-05-31 00:00:00',
Carbon::parse('before yesterday')->format('Y-m-d H:i:s'),
);
$this->assertSame(
'2000-01-23 00:00:00',
Carbon::parse('2000-01-25')->change('before yesterday')->format('Y-m-d H:i:s'),
);
}
public function testInvalidModifier(): void
{
$this->checkInvalid('invalid', static function () {
return @Carbon::parse('2000-01-25')->change('invalid');
});
$this->checkInvalid('next invalid', static function () {
return @Carbon::now()->next('invalid');
});
$this->checkInvalid('last invalid', static function () {
return @Carbon::now()->previous('invalid');
});
}
private function checkInvalid(string $message, Closure $callback): void
{
$this->expectExceptionObject(
PHP_VERSION < 8.3
? new InvalidFormatException('Could not modify with: '.var_export($message, true))
: new DateMalformedStringException("Failed to parse time string ($message)"),
);
$callback();
}
public function testImplicitCast(): void
{
$this->assertSame(
'2000-01-25 06:00:00.000000',
Carbon::parse('2000-01-25')->addRealHours('6')->format('Y-m-d H:i:s.u')
);
$this->assertSame(
'2000-01-25 07:00:00.000000',
Carbon::parse('2000-01-25')->addRealUnit('hour', '7')->format('Y-m-d H:i:s.u')
);
$this->assertSame(
'2000-01-24 17:00:00.000000',
Carbon::parse('2000-01-25')->subRealUnit('hour', '7')->format('Y-m-d H:i:s.u')
);
$this->assertSame(
'2000-01-25 00:08:00.000000',
Carbon::parse('2000-01-25')->addRealUnit('minute', '8')->format('Y-m-d H:i:s.u')
);
$this->assertSame(
'2000-01-25 00:00:00.007000',
Carbon::parse('2000-01-25')->addRealUnit('millisecond', '7')->format('Y-m-d H:i:s.u')
);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/CreateFromFormatTest.php | tests/Carbon/CreateFromFormatTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use DateTime;
use DateTimeZone;
use PHPUnit\Framework\Attributes\RequiresPhp;
use Tests\AbstractTestCase;
use Tests\Carbon\Fixtures\MyCarbon;
class CreateFromFormatTest extends AbstractTestCase
{
/**
* @var array
*/
protected $lastErrors;
/**
* @var array
*/
protected $noErrors;
protected function setUp(): void
{
parent::setUp();
$this->lastErrors = [
'warning_count' => 1,
'warnings' => ['10' => 'The parsed date was invalid'],
'error_count' => 0,
'errors' => [],
];
}
public function testCreateFromFormatReturnsCarbon()
{
$d = Carbon::createFromFormat('Y-m-d H:i:s', '1975-05-21 22:32:11');
$this->assertCarbon($d, 1975, 5, 21, 22, 32, 11);
$this->assertInstanceOfCarbon($d);
}
public function testCreateFromFormatWithNamedArguments()
{
$d = Carbon::createFromFormat(
format: 'Y-m-d H:i:s',
time: '1975-05-21 22:32:11',
timezone: 'Asia/tokyo',
);
$this->assertSame('1975-05-21 22:32:11 Asia/tokyo', $d->format('Y-m-d H:i:s e'));
}
public function testCreateFromFalseTimezone()
{
$d = Carbon::createFromFormat('Y-m-d H:i:s.u', '1975-05-21 22:32:11.123456', false);
$this->assertInstanceOfCarbon($d);
$this->assertSame('1975-05-21 22:32:11.123456 America/Toronto', $d->format('Y-m-d H:i:s.u e'));
}
/**
* Work-around for https://bugs.php.net/bug.php?id=80141
*/
public function testCFormat()
{
$d = Carbon::createFromFormat('c', Carbon::parse('2020-02-02')->format('c'));
$this->assertCarbon($d, 2020, 2, 2, 0, 0, 0, 0);
$d = Carbon::createFromFormat('c', '2020-02-02T23:45:12+09:00');
$this->assertSame('+09:00', $d->tzName);
$this->assertCarbon($d, 2020, 2, 2, 23, 45, 12, 0);
$d = Carbon::createFromFormat('l c', 'Sunday 2020-02-02T23:45:12+09:00');
$this->assertSame('+09:00', $d->tzName);
$this->assertCarbon($d, 2020, 2, 2, 23, 45, 12, 0);
$d = Carbon::createFromFormat('l \\\\c', 'Sunday \\2020-02-02T23:45:12+09:00');
$this->assertSame('+09:00', $d->tzName);
$this->assertCarbon($d, 2020, 2, 2, 23, 45, 12, 0);
$d = Carbon::createFromFormat('Y-m-d\\cH:i:s', '2020-02-02c23:45:12');
$this->assertCarbon($d, 2020, 2, 2, 23, 45, 12, 0);
}
public function testCreateFromFormatWithMillisecondsAlone()
{
$d = Carbon::createFromFormat('Y-m-d H:i:s.v', '1975-05-21 22:32:11.321');
$this->assertCarbon($d, 1975, 5, 21, 22, 32, 11, 321000);
$this->assertInstanceOfCarbon($d);
}
/**
* Due to https://bugs.php.net/bug.php?id=75577, proper "v" format support can only work from PHP 7.3.0.
*/
public function testCreateFromFormatWithMillisecondsMerged()
{
$d = Carbon::createFromFormat('Y-m-d H:s.vi', '1975-05-21 22:11.32132');
$this->assertCarbon($d, 1975, 5, 21, 22, 32, 11, 321000);
$this->assertInstanceOfCarbon($d);
}
public function testCreateFromFormatWithTimezoneString()
{
$d = Carbon::createFromFormat('Y-m-d H:i:s', '1975-05-21 22:32:11', 'Europe/London');
$this->assertCarbon($d, 1975, 5, 21, 22, 32, 11);
$this->assertSame('Europe/London', $d->tzName);
}
public function testCreateFromFormatWithTimezone()
{
$d = Carbon::createFromFormat('Y-m-d H:i:s', '1975-05-21 22:32:11', new DateTimeZone('Europe/London'));
$this->assertCarbon($d, 1975, 5, 21, 22, 32, 11);
$this->assertSame('Europe/London', $d->tzName);
}
public function testCreateFromFormatWithMillis()
{
$d = Carbon::createFromFormat('Y-m-d H:i:s.u', '1975-05-21 22:32:11.254687');
$this->assertSame(254687, $d->micro);
}
public function testCreateFromFormatWithTestNow()
{
Carbon::setTestNow();
$nativeDate = Carbon::createFromFormat('Y-m-d H:i:s', '1975-05-21 22:32:11');
Carbon::setTestNow(Carbon::now());
$mockedDate = Carbon::createFromFormat('Y-m-d H:i:s', '1975-05-21 22:32:11');
$this->assertSame($mockedDate->micro === 0, $nativeDate->micro === 0);
}
#[RequiresPhp('>=8.2')]
public function testCreateLastErrorsCanBeAccessedByExtendingClass()
{
$this->assertFalse(MyCarbon::getLastErrors());
}
public function testCreateFromFormatHandlesLastErrors()
{
$carbon = Carbon::createFromFormat('d/m/Y', '41/02/1900');
$datetime = DateTime::createFromFormat('d/m/Y', '41/02/1900');
$this->assertSame($this->lastErrors, $carbon->getLastErrors());
$this->assertSame($carbon->getLastErrors(), $datetime->getLastErrors());
}
#[RequiresPhp('>=8.2')]
public function testCreateFromFormatResetLastErrors()
{
$carbon = Carbon::createFromFormat('d/m/Y', '41/02/1900');
$this->assertSame($this->lastErrors, $carbon->getLastErrors());
$carbon = Carbon::createFromFormat('d/m/Y', '11/03/2016');
$this->assertFalse($carbon->getLastErrors());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/SetDateAndTimeFromTest.php | tests/Carbon/SetDateAndTimeFromTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Tests\AbstractTestCase;
class SetDateAndTimeFromTest extends AbstractTestCase
{
public function testSetDateFrom()
{
$source = Carbon::now();
$target = $source->copy()
->addDays(rand(1, 6))
->addHours(rand(1, 23))
->addMinutes(rand(1, 59))
->addSeconds(rand(1, 59));
$this->assertCarbon(
$target->copy()->setDateFrom($source),
$source->year,
$source->month,
$source->day,
$target->hour,
$target->minute,
$target->second,
);
}
public function testSetTimeFrom()
{
$source = Carbon::now();
$target = $source->copy()
->addDays(rand(1, 6))
->addHours(rand(1, 23))
->addMinutes(rand(1, 59))
->addSeconds(rand(1, 59));
$this->assertCarbon(
$target->copy()->setTimeFrom($source),
$target->year,
$target->month,
$target->day,
$source->hour,
$source->minute,
$source->second,
);
}
public function testSetDateTimeFrom()
{
$source = Carbon::now();
$target = $source->copy()
->addDays(rand(1, 6))
->addHours(rand(1, 23))
->addMinutes(rand(1, 59))
->addSeconds(rand(1, 59));
$this->assertCarbon(
$target->copy()->setDateTimeFrom($source),
$source->year,
$source->month,
$source->day,
$source->hour,
$source->minute,
$source->second,
);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/SettersTest.php | tests/Carbon/SettersTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use BadMethodCallException;
use Carbon\Carbon;
use Carbon\Exceptions\InvalidFormatException;
use Carbon\Exceptions\InvalidIntervalException;
use Carbon\Exceptions\UnitException;
use Carbon\Exceptions\UnsupportedUnitException;
use Carbon\Month;
use Carbon\Unit;
use DateInterval;
use DateTimeZone;
use Exception;
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\TestWith;
use Tests\AbstractTestCase;
class SettersTest extends AbstractTestCase
{
public const SET_UNIT_NO_OVERFLOW_SAMPLE = 200;
public function testMonthEnum()
{
$d = Carbon::parse('2023-10-25 21:14:51');
$d->month = Month::February;
$this->assertSame('2023-02-25 21:14:51', $d->format('Y-m-d H:i:s'));
$d->setMonth(Month::July);
$this->assertSame('2023-07-25 21:14:51', $d->format('Y-m-d H:i:s'));
}
public function testSetMonthUnit()
{
$d = Carbon::parse('2023-10-25 21:14:51');
$d->set(Unit::Month, Month::February);
$this->assertSame(2, $d->get(Unit::Month));
$this->assertSame('2023-02-25 21:14:51', $d->format('Y-m-d H:i:s'));
}
public function testMonthEnumOnWrongUnit()
{
$this->expectExceptionObject(new UnitException(
'Month enum cannot be used to set year',
));
$d = Carbon::now();
// @phpstan-ignore-next-line
$d->year = Month::February;
}
public function testSingularUnit()
{
$this->assertSame('year', Carbon::singularUnit('year'));
$this->assertSame('year', Carbon::singularUnit('Years'));
$this->assertSame('century', Carbon::singularUnit('centuries'));
$this->assertSame('millennium', Carbon::singularUnit('Millennia'));
$this->assertSame('millennium', Carbon::singularUnit('millenniums'));
}
public function testPluralUnit()
{
$this->assertSame('years', Carbon::pluralUnit('year'));
$this->assertSame('years', Carbon::pluralUnit('Years'));
$this->assertSame('centuries', Carbon::pluralUnit('century'));
$this->assertSame('centuries', Carbon::pluralUnit('centuries'));
$this->assertSame('millennia', Carbon::pluralUnit('Millennia'));
$this->assertSame('millennia', Carbon::pluralUnit('millenniums'));
$this->assertSame('millennia', Carbon::pluralUnit('millennium'));
}
public function testSet()
{
$d = Carbon::create(2000, 1, 12);
$d->set([
'year' => 1995,
'month' => 4,
]);
$this->assertSame(1995, $d->year);
$this->assertSame(4, $d->month);
$this->assertSame(12, $d->day);
}
public function testYearSetter()
{
$d = Carbon::now();
$d->year = 1995;
$this->assertSame(1995, $d->year);
}
public function testMonthSetter()
{
$d = Carbon::now();
$d->month = 3;
$this->assertSame(3, $d->month);
}
public function testMonthSetterWithWrap()
{
$d = Carbon::now();
$d->month = 13;
$this->assertSame(1, $d->month);
}
public function testDaySetter()
{
$d = Carbon::now();
$d->day = 2;
$this->assertSame(2, $d->day);
}
public function testDaySetterWithWrap()
{
$d = Carbon::createFromDate(2012, 8, 5);
$d->day = 32;
$this->assertSame(1, $d->day);
}
public function testHourSetter()
{
$d = Carbon::now();
$d->hour = 2;
$this->assertSame(2, $d->hour);
}
public function testHourSetterWithWrap()
{
$d = Carbon::now();
$d->hour = 25;
$this->assertSame(1, $d->hour);
}
public function testMinuteSetter()
{
$d = Carbon::now();
$d->minute = 2;
$this->assertSame(2, $d->minute);
}
public function testMinuteSetterWithWrap()
{
$d = Carbon::now();
$d->minute = 65;
$this->assertSame(5, $d->minute);
}
public function testSecondSetter()
{
$d = Carbon::now();
$d->second = 2;
$this->assertSame(2, $d->second);
}
public function testUnitOfUnit()
{
$date = Carbon::create(2023, 1, 27, 20, 12, 42, 'America/Toronto');
$date->minuteOfYear = (95 * 24 + 3) * 60 + 50;
$this->assertSame('2023-04-06 04:50:42 America/Toronto', $date->format('Y-m-d H:i:s e'));
$date->dayOfWeek = 2;
$this->assertSame('2023-04-04 04:50:42 America/Toronto', $date->format('Y-m-d H:i:s e'));
$date->dayOfWeek = 6;
$this->assertSame('2023-04-08 04:50:42 America/Toronto', $date->format('Y-m-d H:i:s e'));
$date->dayOfWeek = 0;
$this->assertSame('2023-04-02 04:50:42 America/Toronto', $date->format('Y-m-d H:i:s e'));
$date->dayOfWeekIso = 7;
$this->assertSame('2023-04-02 04:50:42 America/Toronto', $date->format('Y-m-d H:i:s e'));
$date->dayOfWeek = 4;
$this->assertSame('2023-04-06 04:50:42 America/Toronto', $date->format('Y-m-d H:i:s e'));
$date->dayOfWeekIso = 7;
$this->assertSame('2023-04-09 04:50:42 America/Toronto', $date->format('Y-m-d H:i:s e'));
}
public function testUnitOfUnitMethod()
{
$date = Carbon::create(2023, 1, 27, 20, 12, 42, 'America/Toronto');
$date->minuteOfYear((95 * 24 + 3) * 60 + 50);
$this->assertSame('2023-04-06 04:50:42 America/Toronto', $date->format('Y-m-d H:i:s e'));
}
public function testUnitOfUnitUnknownMethod()
{
$this->expectExceptionObject(new BadMethodCallException(
'Method fooOfBar does not exist.',
));
$date = Carbon::create(2023, 1, 27, 20, 12, 42, 'America/Toronto');
$date->fooOfBar((95 * 24 + 3) * 60 + 50);
}
public function testUnitOfUnitFloat()
{
$this->expectExceptionObject(new UnitException(
'->minuteOfYear expects integer value',
));
$date = Carbon::create(2018, 1, 27, 20, 12, 42, 'America/Toronto');
$date->minuteOfYear = (float) ((95 * 24 + 3) * 60 + 50);
}
public function testTimeSetter()
{
$d = Carbon::now();
$d->setTime(1, 1, 1);
$this->assertSame(1, $d->second);
$d->setTime(1, 1);
$this->assertSame(0, $d->second);
}
public function testTimeSetterWithChaining()
{
$d = Carbon::now();
$d->setTime(2, 2, 2)->setTime(1, 1, 1);
$this->assertInstanceOfCarbon($d);
$this->assertSame(1, $d->second);
$d->setTime(2, 2, 2)->setTime(1, 1);
$this->assertInstanceOfCarbon($d);
$this->assertSame(0, $d->second);
}
public function testTimeSetterWithZero()
{
$d = Carbon::now();
$d->setTime(1, 1);
$this->assertSame(0, $d->second);
}
public function testDateTimeSetter()
{
$d = Carbon::now();
$d->setDateTime($d->year, $d->month, $d->day, 1, 1, 1);
$this->assertSame(1, $d->second);
}
public function testDateTimeSetterWithZero()
{
$d = Carbon::now();
$d->setDateTime($d->year, $d->month, $d->day, 1, 1);
$this->assertSame(0, $d->second);
}
public function testDateTimeSetterWithChaining()
{
$d = Carbon::now();
$d->setDateTime(2013, 9, 24, 17, 4, 29);
$this->assertInstanceOfCarbon($d);
$d->setDateTime(2014, 10, 25, 18, 5, 30);
$this->assertInstanceOfCarbon($d);
$this->assertCarbon($d, 2014, 10, 25, 18, 5, 30);
}
/**
* @link https://github.com/briannesbitt/Carbon/issues/539
*/
public function testSetDateAfterStringCreation()
{
$d = new Carbon('first day of this month');
$this->assertSame(1, $d->day);
$d->setDate($d->year, $d->month, 12);
$this->assertSame(12, $d->day);
}
public function testSecondSetterWithWrap()
{
$d = Carbon::now();
$d->second = 65;
$this->assertSame(5, $d->second);
}
public function testMicrosecondSetterWithWrap()
{
$d = Carbon::now();
$d->micro = -4;
$this->assertSame(999996, $d->micro);
$this->assertSame((Carbon::now()->second + 59) % 60, $d->second);
$d->microsecond = 3123456;
$this->assertSame(123456, $d->micro);
$this->assertSame((Carbon::now()->second + 2) % 60, $d->second);
$d->micro -= 12123400;
$this->assertSame(56, $d->micro);
$this->assertSame((Carbon::now()->second + 50) % 60, $d->second);
$d->micro = -12600000;
$this->assertSame(400000, $d->micro);
$this->assertSame((Carbon::now()->second + 37) % 60, $d->second);
$d->millisecond = 123;
$this->assertSame(123, $d->milli);
$this->assertSame(123000, $d->micro);
$d->milli = 456;
$this->assertSame(456, $d->millisecond);
$this->assertSame(456000, $d->microsecond);
$d->microseconds(567);
$this->assertSame(567, $d->microsecond);
$d->setMicroseconds(678);
$this->assertSame(678, $d->microsecond);
$d->milliseconds(567);
$this->assertSame(567, $d->millisecond);
$this->assertSame(567000, $d->microsecond);
$d->setMilliseconds(678);
$this->assertSame(678, $d->millisecond);
$this->assertSame(678000, $d->microsecond);
}
public function testTimestampSetter()
{
$d = Carbon::now();
$d->timestamp = 10;
$this->assertSame(10, $d->timestamp);
$d->setTimestamp(11);
$this->assertSame(11, $d->timestamp);
$d->timestamp = 1600887164.88952298;
$this->assertSame('2020-09-23 14:52:44.889523', $d->format('Y-m-d H:i:s.u'));
$d->setTimestamp(
// See https://github.com/php/php-src/issues/14332
PHP_VERSION < 8.4
? 1599828571.23561248
: 1599828571.2356121,
);
$this->assertSame('2020-09-11 08:49:31.235612', $d->format('Y-m-d H:i:s.u'));
$d->timestamp = '0.88951247 1600887164';
$this->assertSame('2020-09-23 14:52:44.889512', $d->format('Y-m-d H:i:s.u'));
$d->setTimestamp('0.23561248 1599828571');
$this->assertSame('2020-09-11 08:49:31.235612', $d->format('Y-m-d H:i:s.u'));
$d->timestamp = '0.88951247/1600887164/12.56';
$this->assertSame('2020-09-23 14:52:57.449512', $d->format('Y-m-d H:i:s.u'));
$d->setTimestamp('0.00561248/1599828570--1.23');
$this->assertSame('2020-09-11 08:49:31.235612', $d->format('Y-m-d H:i:s.u'));
}
public function testSetTimezoneWithInvalidTimezone()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Unknown or bad timezone (sdf)',
));
$d = Carbon::now();
$d->setTimezone('sdf');
}
public function testTimezoneWithInvalidTimezone()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Unknown or bad timezone (sdf)',
));
/** @var mixed $d */
$d = Carbon::now();
$d->timezone = 'sdf';
}
public function testTimeZoneOfUnserialized()
{
$date = new Carbon('2020-01-01', 'America/Vancouver');
$new = unserialize(serialize($date));
$this->assertSame('America/Vancouver', $date->getTimezone()->getName());
$date->cleanupDumpProperties()->timezone = 'UTC';
$this->assertSame('UTC', $date->getTimezone()->getName());
$this->assertSame('America/Vancouver', $new->getTimezone()->getName());
@$new->timezone = 'UTC';
$this->assertSame('UTC', $new->getTimezone()->getName());
/** @var mixed $date */
$date = new Carbon('2020-01-01', 'America/Vancouver');
$new = clone $date;
$this->assertSame('America/Vancouver', $date->getTimezone()->getName());
@$date->timezone = 'UTC';
$this->assertSame('UTC', $date->getTimezone()->getName());
$this->assertSame('America/Vancouver', $new->getTimezone()->getName());
@$new->timezone = 'UTC';
$this->assertSame('UTC', $new->getTimezone()->getName());
$date = new Carbon('2020-01-01', 'America/Vancouver');
$this->assertSame('America/Vancouver', $date->getTimezone()->getName());
var_export($date, true);
$date->cleanupDumpProperties()->timezone = 'UTC';
$this->assertSame('UTC', $date->getTimezone()->getName());
$date = new Carbon('2020-01-01', 'America/Vancouver');
$this->assertSame('America/Vancouver', $date->getTimezone()->getName());
/** @var array $array */
$array = $date;
foreach ($array as $item) {
}
$date->cleanupDumpProperties()->timezone = 'UTC';
$this->assertSame('UTC', $date->getTimezone()->getName());
$date = new Carbon('2020-01-01', 'America/Vancouver');
$this->assertSame('America/Vancouver', $date->getTimezone()->getName());
get_object_vars($date);
$date->cleanupDumpProperties()->timezone = 'UTC';
$this->assertSame('UTC', $date->getTimezone()->getName());
}
public function testTimezoneWithInvalidTimezoneSetter()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Unknown or bad timezone (sdf)',
));
$d = Carbon::now();
$d->timezone('sdf');
}
public function testTzWithInvalidTimezone()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Unknown or bad timezone (sdf)',
));
/** @var mixed $d */
$d = Carbon::now();
$d->tz = 'sdf';
}
public function testTzWithInvalidTimezoneSetter()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Unknown or bad timezone (sdf)',
));
$d = Carbon::now();
$d->tz('sdf');
}
public function testSetTimezoneUsingString()
{
$d = Carbon::now();
$d->setTimezone('America/Toronto');
$this->assertSame('America/Toronto', $d->tzName);
}
public function testShiftTimezone()
{
$d = Carbon::parse('2018-08-13 10:53:12', 'Europe/Paris');
$d2 = $d->copy()->setTimezone('America/Toronto');
$this->assertSame(0, $d2->getTimestamp() - $d->getTimestamp());
$this->assertSame('04:53:12', $d2->format('H:i:s'));
$d = Carbon::parse('2018-08-13 10:53:12.321654', 'Europe/Paris');
$d2 = $d->copy()->shiftTimezone('America/Toronto');
$this->assertSame(21600, $d2->getTimestamp() - $d->getTimestamp());
$this->assertSame('America/Toronto', $d2->tzName);
$this->assertSame('10:53:12.321654', $d2->format('H:i:s.u'));
$d = Carbon::parse('2018-03-25 00:53:12.321654 America/Toronto')->shiftTimezone('Europe/Oslo');
$this->assertSame('2018-03-25 00:53:12.321654 Europe/Oslo', $d->format('Y-m-d H:i:s.u e'));
}
public function testTimezoneUsingString()
{
/** @var mixed $d */
$d = Carbon::now();
$d->timezone = 'America/Toronto';
$this->assertSame('America/Toronto', $d->tzName);
$d->timezone('America/Vancouver');
$this->assertSame('America/Vancouver', $d->tzName);
}
public function testTzUsingString()
{
/** @var mixed $d */
$d = Carbon::now();
$d->tz = 'America/Toronto';
$this->assertSame('America/Toronto', $d->tzName);
$this->assertSame('America/Toronto', $d->tz());
$d->tz('America/Vancouver');
$this->assertSame('America/Vancouver', $d->tzName);
$this->assertSame('America/Vancouver', $d->tz());
}
public function testTzUsingOffset()
{
$d = Carbon::create(2000, 8, 1, 0, 0, 0);
$d->offset = 7200;
$this->assertSame(7200, $d->offset);
$this->assertSame(120, $d->offsetMinutes);
$this->assertSame(2, $d->offsetHours);
$this->assertSame(120, $d->utcOffset());
$d->utcOffset(-180);
$this->assertSame(-10800, $d->offset);
$this->assertSame(-180, $d->offsetMinutes);
$this->assertSame(-3, $d->offsetHours);
$this->assertSame(-180, $d->utcOffset());
$d->offsetMinutes = -240;
$this->assertSame(-14400, $d->offset);
$this->assertSame(-240, $d->offsetMinutes);
$this->assertSame(-4, $d->offsetHours);
$this->assertSame(-240, $d->utcOffset());
$d->offsetHours = 1;
$this->assertSame(3600, $d->offset);
$this->assertSame(60, $d->offsetMinutes);
$this->assertSame(1, $d->offsetHours);
$this->assertSame(60, $d->utcOffset());
$d->utcOffset(330);
$this->assertSame(330, $d->utcOffset());
}
public function testSetTimezoneUsingDateTimeZone()
{
$d = Carbon::now();
$d->setTimezone(new DateTimeZone('America/Toronto'));
$this->assertSame('America/Toronto', $d->tzName);
}
public function testTimezoneUsingDateTimeZone()
{
/** @var mixed $d */
$d = Carbon::now();
$d->timezone = new DateTimeZone('America/Toronto');
$this->assertSame('America/Toronto', $d->tzName);
$d->timezone(new DateTimeZone('America/Vancouver'));
$this->assertSame('America/Vancouver', $d->tzName);
}
public function testTzUsingDateTimeZone()
{
/** @var mixed $d */
$d = Carbon::now();
$d->tz = new DateTimeZone('America/Toronto');
$this->assertSame('America/Toronto', $d->tzName);
$d->tz(new DateTimeZone('America/Vancouver'));
$this->assertSame('America/Vancouver', $d->tzName);
}
public function testInvalidSetter()
{
$this->expectExceptionObject(new InvalidArgumentException(
"Unknown setter 'doesNotExit'",
));
/** @var mixed $date */
$date = Carbon::now();
$date->doesNotExit = 'bb';
}
#[TestWith([9, 15, 30, '09:15:30'])]
#[TestWith([9, 15, 0, '09:15'])]
#[TestWith([9, 0, 0, '09'])]
#[TestWith([9, 5, 3, '9:5:3'])]
#[TestWith([9, 5, 0, '9:5'])]
#[TestWith([9, 0, 0, '9'])]
public function testSetTimeFromTimeString(int $hour, int $minute, int $second, string $time)
{
Carbon::setTestNow(Carbon::create(2016, 2, 12, 1, 2, 3));
$d = Carbon::now()->setTimeFromTimeString($time);
$this->assertCarbon($d, 2016, 2, 12, $hour, $minute, $second);
}
public function testWeekendDaysSetter()
{
$weekendDays = [Carbon::FRIDAY,Carbon::SATURDAY];
$d = Carbon::now();
$d->setWeekendDays($weekendDays);
$this->assertSame($weekendDays, $d->getWeekendDays());
Carbon::setWeekendDays([Carbon::SATURDAY, Carbon::SUNDAY]);
}
public function testMidDayAtSetter()
{
$d = Carbon::now();
$d->setMidDayAt(11);
$this->assertSame(11, $d->getMidDayAt());
$d->setMidDayAt(12);
$this->assertSame(12, $d->getMidDayAt());
}
public function testSetUnitNoOverflowFebruary()
{
$d = Carbon::parse('2024-02-29')->setUnitNoOverFlow('day', 31, 'month');
$this->assertInstanceOf(Carbon::class, $d);
$this->assertSame('2024-02-29 23:59:59.999999', $d->format('Y-m-d H:i:s.u'));
}
public function testSetUnitNoOverflow()
{
$results = [
'current' => 0,
'start' => 0,
'end' => 0,
'failure' => [],
];
for ($i = 0; $i < static::SET_UNIT_NO_OVERFLOW_SAMPLE; $i++) {
$year = mt_rand(2000, 2500);
$month = mt_rand(1, 12);
$day = mt_rand(1, 28);
$hour = mt_rand(0, 23);
$minute = mt_rand(0, 59);
$second = mt_rand(0, 59);
$microsecond = mt_rand(0, 999999);
$units = ['millennium', 'century', 'decade', 'year', 'quarter', 'month', 'day', 'hour', 'minute', 'second', 'week'];
$overflowUnit = $units[mt_rand(0, \count($units) - 1)];
$units = [
'year' => 10,
'month' => 12,
'day' => 9999,
'hour' => 24,
'minute' => 60,
'second' => 60,
'microsecond' => 1000000,
];
$valueUnit = array_keys($units)[mt_rand(0, \count($units) - 1)];
$value = mt_rand(0, 1) === 1 ?
mt_rand(-9999, 9999) :
mt_rand(-60, 60);
$date = Carbon::create($year, $month, $day, $hour, $minute, $second + $microsecond / 1000000, 'UTC');
$original = $date->copy();
$date->setUnitNoOverflow($valueUnit, $value, $overflowUnit);
$start = $original->copy()->startOf($overflowUnit);
$end = $original->copy()->endOf($overflowUnit);
if ($date->lessThan($start) || $date->greaterThan($end)) {
$results['failure'][] = [
'year' => $year,
'month' => $month,
'day' => $day,
'hour' => $hour,
'minute' => $minute,
'second' => $second,
'microsecond' => $microsecond,
'valueUnit' => $valueUnit,
'value' => $value,
'overflowUnit' => $overflowUnit,
'date' => $date->format('Y-m-d H:i:s'),
'start' => $start->format('Y-m-d H:i:s'),
'end' => $end->format('Y-m-d H:i:s'),
];
continue;
}
$unit = ucfirst(Carbon::pluralUnit($valueUnit));
$modulo = $value % $units[$valueUnit];
if ($modulo < 0) {
$modulo += $units[$valueUnit];
}
if ($value === $date->$valueUnit ||
$modulo === $date->$valueUnit ||
$$valueUnit - ((int) $date->{"diffIn$unit"}($original, false)) === $value ||
($valueUnit === 'day' &&
$date->format('Y-m-d H:i:s.u') === $original->copy()
->modify(($original->day + $value).' days')
->format('Y-m-d H:i:s.u'))
) {
$results['current']++;
continue;
}
if ($date->$valueUnit === $start->$valueUnit) {
$results['start']++;
continue;
}
if ($date->$valueUnit === $end->$valueUnit) {
$results['end']++;
continue;
}
$this->failOperation(
$original,
$date,
$start,
$end,
'setUnitNoOverflow',
$valueUnit,
$value,
$overflowUnit,
$unit,
$modulo,
$$valueUnit,
);
}
$minimum = static::SET_UNIT_NO_OVERFLOW_SAMPLE / 100;
$this->assertSame([], $results['failure']);
$this->assertGreaterThan($minimum, $results['start']);
$this->assertGreaterThan($minimum, $results['end']);
$this->assertGreaterThan($minimum, $results['current']);
$this->assertSame(static::SET_UNIT_NO_OVERFLOW_SAMPLE, $results['end'] + $results['start'] + $results['current']);
}
public function testSetUnitNoOverflowInputUnitException()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Unknown unit \'anyUnit\'',
));
Carbon::now()->setUnitNoOverflow('anyUnit', 1, 'year');
}
public function testSetUnitNoOverflowOverflowUnitException()
{
$this->expectExceptionObject(new InvalidArgumentException(
'Unknown unit \'anyUnit\'',
));
Carbon::now()->setUnitNoOverflow('minute', 1, 'anyUnit');
}
public function testAddUnitError()
{
$this->expectExceptionObject(new UnitException(implode("\n", [
'Unable to add unit array (',
" 0 => 'foobar',",
' 1 => 1,',
')',
])));
$date = Carbon::parse('2021-09-13');
@$date->addUnit('foobar', 1);
}
public function testUnsupportedUnitException()
{
$date = new class('2021-09-13') extends Carbon {
public function rawAdd(DateInterval $interval): static
{
throw new InvalidIntervalException('InvalidIntervalException');
}
public function modify($modifier): static
{
throw new InvalidFormatException('InvalidFormatException');
}
};
$exception = null;
try {
$date->addUnit('year', 999);
} catch (UnitException $error) {
$exception = $error;
}
$this->assertSame(
'Unable to add unit '.var_export(['year', 999], true),
$exception?->getMessage(),
);
$previous = $exception->getPrevious();
$this->assertInstanceOf(UnsupportedUnitException::class, $previous);
$this->assertSame("Unsupported unit 'year'", $previous->getMessage());
$previous = $previous->getPrevious();
$this->assertInstanceOf(InvalidIntervalException::class, $previous);
$this->assertSame('InvalidIntervalException', $previous->getMessage());
$this->assertNull($previous->getPrevious());
}
public function testAddUnitNoOverflow()
{
$results = [
'current' => 0,
'start' => 0,
'end' => 0,
'failure' => [],
];
for ($i = 0; $i < static::SET_UNIT_NO_OVERFLOW_SAMPLE; $i++) {
$year = mt_rand(2000, 2500);
$month = mt_rand(1, 12);
$day = mt_rand(1, 28);
$hour = mt_rand(0, 23);
$minute = mt_rand(0, 59);
$second = mt_rand(0, 59);
$microsecond = mt_rand(0, 999999);
$units = ['millennium', 'century', 'decade', 'year', 'quarter', 'month', 'day', 'hour', 'minute', 'second', 'week'];
$overflowUnit = $units[mt_rand(0, \count($units) - 1)];
$units = [
'year' => 10,
'month' => 12,
'day' => 9999,
'hour' => 24,
'minute' => 60,
'second' => 60,
'microsecond' => 1000000,
];
$valueUnit = array_keys($units)[mt_rand(0, \count($units) - 1)];
$value = mt_rand(0, 1) === 1 ?
mt_rand(-9999, 9999) :
mt_rand(-60, 60);
$date = Carbon::create($year, $month, $day, $hour, $minute, $second + $microsecond / 1000000);
$original = $date->copy();
$date->addUnitNoOverflow($valueUnit, $value, $overflowUnit);
$start = $original->copy()->startOf($overflowUnit);
$end = $original->copy()->endOf($overflowUnit);
if ($date->lessThan($start) || $date->greaterThan($end)) {
$results['failure'][] = [
'year' => $year,
'month' => $month,
'day' => $day,
'hour' => $hour,
'minute' => $minute,
'second' => $second,
'microsecond' => $microsecond,
'valueUnit' => $valueUnit,
'value' => $value,
'overflowUnit' => $overflowUnit,
'date' => $date->format('Y-m-d H:i:s.u e O'),
'start' => $start->format('Y-m-d H:i:s.u e O'),
'end' => $end->format('Y-m-d H:i:s.u e O'),
];
continue;
}
$unit = ucfirst(Carbon::pluralUnit($valueUnit));
$modulo = ($$valueUnit + $value) % $units[$valueUnit];
if ($modulo < 0) {
$modulo += $units[$valueUnit];
}
if ($value === $date->$valueUnit ||
$modulo === $date->$valueUnit ||
(method_exists($date, "diffInReal$unit") && -$date->{"diffInReal$unit"}($original, false) === $value)
) {
$results['current']++;
continue;
}
if ($date->$valueUnit === $start->$valueUnit) {
$results['start']++;
continue;
}
if ($date->$valueUnit === $end->$valueUnit) {
$results['end']++;
continue;
}
$currentDiff = -((int) round($date->{"diffIn$unit"}($original, false)));
if ($currentDiff === $value) {
$results['current']++;
continue;
}
$delta = ($currentDiff - $value);
if ($valueUnit === 'hour') {
$diff = $this->getOffsetChangeOfTheDay($date) ?: $this->getOffsetChangeOfTheDay($original);
if ($diff !== 0) {
$sign = $diff < 0 ? -1 : 1;
$diff = abs($diff);
$minutes = $diff % 100;
$hours = (int) ($sign * (floor($diff / 100) + $minutes / 60));
if ($delta === -$hours) {
$results['current']++;
continue;
}
}
}
$this->failOperation(
$original,
$date,
$start,
$end,
'addUnitNoOverflow',
$valueUnit,
$value,
$overflowUnit,
$unit,
$modulo,
$value,
);
}
$minimum = static::SET_UNIT_NO_OVERFLOW_SAMPLE / 100;
$this->assertSame([], $results['failure']);
$this->assertGreaterThan($minimum, $results['start']);
$this->assertGreaterThan($minimum, $results['end']);
$this->assertGreaterThan($minimum, $results['current']);
$this->assertSame(static::SET_UNIT_NO_OVERFLOW_SAMPLE, $results['end'] + $results['start'] + $results['current']);
}
public function testSubUnitNoOverflow()
{
$results = [
'current' => 0,
'start' => 0,
'end' => 0,
'failure' => [],
];
for ($i = 0; $i < static::SET_UNIT_NO_OVERFLOW_SAMPLE; $i++) {
$year = mt_rand(2000, 2500);
$month = mt_rand(1, 12);
$day = mt_rand(1, 28);
$hour = mt_rand(0, 23);
$minute = mt_rand(0, 59);
$second = mt_rand(0, 59);
$microsecond = mt_rand(0, 999999);
$units = ['millennium', 'century', 'decade', 'year', 'quarter', 'month', 'day', 'hour', 'minute', 'second', 'week'];
$overflowUnit = $units[mt_rand(0, \count($units) - 1)];
$units = [
'year' => 10,
'month' => 12,
'day' => 9999,
'hour' => 24,
'minute' => 60,
'second' => 60,
'microsecond' => 1000000,
];
$valueUnit = array_keys($units)[mt_rand(0, \count($units) - 1)];
$value = mt_rand(0, 1) === 1 ?
mt_rand(-9999, 9999) :
mt_rand(-60, 60);
$date = Carbon::create($year, $month, $day, $hour, $minute, $second + $microsecond / 1000000);
$original = $date->copy();
$date->subUnitNoOverflow($valueUnit, $value, $overflowUnit);
$start = $original->copy()->startOf($overflowUnit);
$end = $original->copy()->endOf($overflowUnit);
if ($date->lessThan($start) || $date->greaterThan($end)) {
$results['failure'][] = [
'year' => $year,
'month' => $month,
'day' => $day,
'hour' => $hour,
'minute' => $minute,
'second' => $second,
'microsecond' => $microsecond,
'valueUnit' => $valueUnit,
'value' => $value,
'overflowUnit' => $overflowUnit,
'date' => $date->format('Y-m-d H:i:s.u e O'),
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | true |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/ComparisonTest.php | tests/Carbon/ComparisonTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use DateTime;
use Tests\AbstractTestCase;
class ComparisonTest extends AbstractTestCase
{
public function testEqualToTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 1)->eq(Carbon::createFromDate(2000, 1, 1)));
}
public function testEqualToFalse()
{
$this->assertFalse(Carbon::createFromDate(2000, 1, 1)->eq(Carbon::createFromDate(2000, 1, 2)));
}
public function testEqualWithTimezoneTrue()
{
$this->assertTrue(Carbon::create(2000, 1, 1, 12, 0, 0, 'America/Toronto')->eq(Carbon::create(2000, 1, 1, 9, 0, 0, 'America/Vancouver')));
}
public function testEqualWithTimezoneFalse()
{
$timezones = ['Europe/London', 'America/Toronto', 'America/Vancouver', 'Asia/Tokyo'];
foreach ($timezones as $a) {
foreach ($timezones as $b) {
$from = Carbon::createFromDate(2000, 1, 1, $a);
$to = Carbon::createFromDate(2000, 1, 1, $b);
$diff = $from->floatDiffInHours($to, false) + Carbon::now($a)->dst - Carbon::now($b)->dst;
$this->assertTrue(\in_array($diff, $a === $b ? [0.0] : [0.0, 24.0, -24.0], true));
}
}
Carbon::setTestNow();
foreach ($timezones as $a) {
foreach ($timezones as $b) {
$from = Carbon::createFromDate(2000, 1, 1, $a);
$to = Carbon::createFromDate(2000, 1, 1, $b);
$diff = $from->floatDiffInHours($to, false) + Carbon::now($a)->dst - Carbon::now($b)->dst;
$diff = round($diff * 1800) / 1800; // 2-seconds precision
$this->assertTrue(\in_array($diff, $a === $b ? [0.0] : [0.0, 24.0, -24.0], true));
}
}
}
public function testNotEqualToTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 1)->ne(Carbon::createFromDate(2000, 1, 2)));
}
public function testNotEqualToFalse()
{
$this->assertFalse(Carbon::createFromDate(2000, 1, 1)->ne(Carbon::createFromDate(2000, 1, 1)));
}
public function testGreaterThanTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 1)->gt(Carbon::createFromDate(1999, 12, 31)));
}
public function testGreaterThanFalse()
{
$this->assertFalse(Carbon::createFromDate(2000, 1, 1)->gt(Carbon::createFromDate(2000, 1, 2)));
}
public function testGreaterThanWithTimezoneTrue()
{
$dt1 = Carbon::create(2000, 1, 1, 12, 0, 0, 'America/Toronto');
$dt2 = Carbon::create(2000, 1, 1, 8, 59, 59, 'America/Vancouver');
$this->assertTrue($dt1->gt($dt2));
}
public function testGreaterThanWithString()
{
Carbon::setToStringFormat('d.m.Y \a\t h:i a');
$this->assertTrue(Carbon::parse('2022-05-03')->gt('2021-05-03'));
$this->assertFalse(Carbon::parse('2021-05-03')->gt('2022-05-03'));
Carbon::setToStringFormat(null);
}
public function testGreaterThanWithTimezoneFalse()
{
$dt1 = Carbon::create(2000, 1, 1, 12, 0, 0, 'America/Toronto');
$dt2 = Carbon::create(2000, 1, 1, 9, 0, 1, 'America/Vancouver');
$this->assertFalse($dt1->gt($dt2));
}
public function testGreaterThanOrEqualTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 1)->gte(Carbon::createFromDate(1999, 12, 31)));
}
public function testGreaterThanOrEqualTrueEqual()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 1)->gte(Carbon::createFromDate(2000, 1, 1)));
}
public function testGreaterThanOrEqualFalse()
{
$this->assertFalse(Carbon::createFromDate(2000, 1, 1)->gte(Carbon::createFromDate(2000, 1, 2)));
}
public function testLessThanTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 1)->lt(Carbon::createFromDate(2000, 1, 2)));
}
public function testLessThanFalse()
{
$this->assertFalse(Carbon::createFromDate(2000, 1, 1)->lt(Carbon::createFromDate(1999, 12, 31)));
}
public function testLessThanOrEqualTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 1)->lte(Carbon::createFromDate(2000, 1, 2)));
}
public function testLessThanOrEqualTrueEqual()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 1)->lte(Carbon::createFromDate(2000, 1, 1)));
}
public function testLessThanOrEqualFalse()
{
$this->assertFalse(Carbon::createFromDate(2000, 1, 1)->lte(Carbon::createFromDate(1999, 12, 31)));
}
public function testBetweenEqualTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->between(Carbon::createFromDate(2000, 1, 1), Carbon::createFromDate(2000, 1, 31), true));
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->isBetween(Carbon::createFromDate(2000, 1, 1), Carbon::createFromDate(2000, 1, 31), true));
$this->assertTrue(Carbon::createMidnightDate(2000, 1, 15)->between(Carbon::createFromDate(2000, 1, 1), Carbon::createFromDate(2000, 1, 15), true));
$this->assertTrue(Carbon::createMidnightDate(2000, 1, 15)->isBetween(Carbon::createFromDate(2000, 1, 1), Carbon::createFromDate(2000, 1, 15), true));
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->between(new DateTime('2000-01-01'), new DateTime('2000-01-31'), true));
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->isBetween(new DateTime('2000-01-01'), new DateTime('2000-01-31'), true));
$this->assertTrue(Carbon::createMidnightDate(2000, 1, 15)->between(new DateTime('2000-01-15'), new DateTime('2000-01-31'), true));
$this->assertTrue(Carbon::createMidnightDate(2000, 1, 15)->isBetween(new DateTime('2000-01-15'), new DateTime('2000-01-31'), true));
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->between('2000-01-01', '2000-01-31', true));
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->isBetween('2000-01-01', '2000-01-31', true));
$this->assertTrue(Carbon::createMidnightDate(2000, 1, 15)->between('2000-01-01', '2000-01-15', true));
$this->assertTrue(Carbon::createMidnightDate(2000, 1, 15)->isBetween('2000-01-01', '2000-01-15', true));
$this->assertTrue(Carbon::create(2000, 1, 15, 17, 20, 54)->between('2000-01-15 17:20:50', '2000-01-15 17:20:54', true));
$this->assertTrue(Carbon::create(2000, 1, 15, 17, 20, 54)->isBetween('2000-01-15 17:20:50', '2000-01-15 17:20:54', true));
$this->assertTrue(Carbon::create(2000, 1, 15, 17, 20, 54)->between('2000-01-15 17:20:54', '2000-01-15 17:20:56', true));
$this->assertTrue(Carbon::create(2000, 1, 15, 17, 20, 54)->isBetween('2000-01-15 17:20:54', '2000-01-15 17:20:56', true));
}
public function testBetweenNotEqualTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->between(Carbon::createFromDate(2000, 1, 1), Carbon::createFromDate(2000, 1, 31), false));
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->isBetween(Carbon::createFromDate(2000, 1, 1), Carbon::createFromDate(2000, 1, 31), false));
$this->assertFalse(Carbon::createFromDate(2000, 1, 15)->between(Carbon::createFromDate(2000, 1, 1), Carbon::createFromDate(2000, 1, 15), false));
$this->assertFalse(Carbon::createFromDate(2000, 1, 15)->isBetween(Carbon::createFromDate(2000, 1, 1), Carbon::createFromDate(2000, 1, 15), false));
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->between(new DateTime('2000-01-01'), new DateTime('2000-01-31'), false));
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->isBetween(new DateTime('2000-01-01'), new DateTime('2000-01-31'), false));
$this->assertFalse(Carbon::createFromDate(2000, 1, 15)->between(new DateTime('2000-01-01'), new DateTime('2000-01-15'), false));
$this->assertFalse(Carbon::createFromDate(2000, 1, 15)->isBetween(new DateTime('2000-01-01'), new DateTime('2000-01-15'), false));
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->between('2000-01-01', '2000-01-31', false));
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->isBetween('2000-01-01', '2000-01-31', false));
$this->assertFalse(Carbon::createMidnightDate(2000, 1, 15)->between('2000-01-15', '2000-01-31', false));
$this->assertFalse(Carbon::createMidnightDate(2000, 1, 15)->isBetween('2000-01-15', '2000-01-31', false));
$this->assertTrue(Carbon::create(2000, 1, 15, 17, 20, 54)->between('2000-01-15 17:20:50', '2000-01-15 17:20:55', false));
$this->assertTrue(Carbon::create(2000, 1, 15, 17, 20, 54)->isBetween('2000-01-15 17:20:50', '2000-01-15 17:20:55', false));
$this->assertFalse(Carbon::create(2000, 1, 15, 17, 20, 54)->between('2000-01-15 17:20:50', '2000-01-15 17:20:54', false));
$this->assertFalse(Carbon::create(2000, 1, 15, 17, 20, 54)->isBetween('2000-01-15 17:20:50', '2000-01-15 17:20:54', false));
$this->assertFalse(Carbon::create(2000, 1, 15, 17, 20, 54)->between('2000-01-15 17:20:54', '2000-01-15 17:20:56', false));
$this->assertFalse(Carbon::create(2000, 1, 15, 17, 20, 54)->isBetween('2000-01-15 17:20:54', '2000-01-15 17:20:56', false));
}
public function testBetweenExcludedTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->betweenExcluded(Carbon::createFromDate(2000, 1, 1), Carbon::createFromDate(2000, 1, 31)));
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->betweenExcluded(new DateTime('2000-01-01'), new DateTime('2000-01-31')));
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->betweenExcluded('2000-01-01', '2000-01-31'));
}
public function testBetweenIncludedTrue()
{
$this->assertTrue(Carbon::createMidnightDate(2000, 1, 15)->betweenIncluded(Carbon::createFromDate(2000, 1, 1), Carbon::createFromDate(2000, 1, 31)));
$this->assertTrue(Carbon::createMidnightDate(2000, 1, 15)->betweenIncluded(new DateTime('2000-01-01'), new DateTime('2000-01-31')));
$this->assertTrue(Carbon::createMidnightDate(2000, 1, 15)->betweenIncluded('2000-01-15', '2000-01-31'));
$this->assertTrue(Carbon::createMidnightDate(2000, 1, 15)->betweenIncluded('2000-01-01', '2000-01-15'));
}
public function testBetweenIncludedFalse()
{
$this->assertFalse(Carbon::createMidnightDate(2000, 1, 15)->betweenIncluded(Carbon::createFromDate(2000, 1, 16), Carbon::createFromDate(2000, 1, 31)));
$this->assertFalse(Carbon::createMidnightDate(2000, 1, 15)->betweenIncluded(new DateTime('2000-01-16'), new DateTime('2000-01-31')));
$this->assertFalse(Carbon::createMidnightDate(2000, 1, 15)->betweenIncluded('2000-01-16', '2000-01-31'));
}
public function testBetweenEqualFalse()
{
$this->assertFalse(Carbon::createFromDate(1999, 12, 31)->between(Carbon::createFromDate(2000, 1, 1), Carbon::createFromDate(2000, 1, 31), true));
}
public function testBetweenNotEqualFalse()
{
$this->assertFalse(Carbon::createFromDate(2000, 1, 1)->between(Carbon::createFromDate(2000, 1, 1), Carbon::createFromDate(2000, 1, 31), false));
}
public function testBetweenEqualSwitchTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->between(Carbon::createFromDate(2000, 1, 31), Carbon::createFromDate(2000, 1, 1), true));
}
public function testBetweenNotEqualSwitchTrue()
{
$this->assertTrue(Carbon::createFromDate(2000, 1, 15)->between(Carbon::createFromDate(2000, 1, 31), Carbon::createFromDate(2000, 1, 1), false));
}
public function testBetweenEqualSwitchFalse()
{
$this->assertFalse(Carbon::createFromDate(1999, 12, 31)->between(Carbon::createFromDate(2000, 1, 31), Carbon::createFromDate(2000, 1, 1), true));
}
public function testBetweenNotEqualSwitchFalse()
{
$this->assertFalse(Carbon::createFromDate(2000, 1, 1)->between(Carbon::createFromDate(2000, 1, 31), Carbon::createFromDate(2000, 1, 1), false));
}
public function testMinIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->min());
}
public function testMinWithNow()
{
$dt = Carbon::create(2012, 1, 1, 0, 0, 0)->min();
$this->assertCarbon($dt, 2012, 1, 1, 0, 0, 0);
}
public function testMinWithInstance()
{
$dt1 = Carbon::create(2013, 12, 31, 23, 59, 59);
$dt2 = Carbon::create(2012, 1, 1, 0, 0, 0)->min($dt1);
$this->assertCarbon($dt2, 2012, 1, 1, 0, 0, 0);
}
public function testMaxIsFluid()
{
$dt = Carbon::now();
$this->assertInstanceOfCarbon($dt->max());
}
public function testMaxWithNow()
{
$dt = Carbon::create(2099, 12, 31, 23, 59, 59)->max();
$this->assertCarbon($dt, 2099, 12, 31, 23, 59, 59);
}
public function testMaxWithInstance()
{
$dt1 = Carbon::create(2012, 1, 1, 0, 0, 0);
$dt2 = Carbon::create(2099, 12, 31, 23, 59, 59)->max($dt1);
$this->assertCarbon($dt2, 2099, 12, 31, 23, 59, 59);
}
public function testIsBirthday()
{
$dt = Carbon::now();
// Birthday test can't work on February 29th
if ($dt->format('m-d') === '02-29') {
Carbon::setTestNowAndTimezone($dt->subDay());
$dt = Carbon::now();
}
$aBirthday = $dt->subYear();
$this->assertTrue($aBirthday->isBirthday());
$notABirthday = $dt->subDay();
$this->assertFalse($notABirthday->isBirthday());
$alsoNotABirthday = $dt->addDays(2);
$this->assertFalse($alsoNotABirthday->isBirthday());
$dt1 = Carbon::createFromDate(1987, 4, 23);
$dt2 = Carbon::createFromDate(2014, 9, 26);
$dt3 = Carbon::createFromDate(2014, 4, 23);
$this->assertFalse($dt2->isBirthday($dt1));
$this->assertTrue($dt3->isBirthday($dt1));
}
public function testClosest()
{
$instance = Carbon::create(2015, 5, 28, 12, 0, 0);
$dt1 = Carbon::create(2015, 5, 28, 11, 0, 0);
$dt2 = Carbon::create(2015, 5, 28, 14, 0, 0);
$closest = $instance->closest($dt1, $dt2);
$this->assertSame($dt1, $closest);
}
public function testClosestWithEquals()
{
$instance = Carbon::create(2015, 5, 28, 12, 0, 0);
$dt1 = Carbon::create(2015, 5, 28, 12, 0, 0);
$dt2 = Carbon::create(2015, 5, 28, 14, 0, 0);
$closest = $instance->closest($dt1, $dt2);
$this->assertSame($dt1, $closest);
}
public function testClosestWithMicroseconds()
{
$baseDate = Carbon::parse('2018-10-11 20:59:06.500000');
$closestDate = Carbon::parse('2018-10-11 20:59:06.600000');
$farthestDate = Carbon::parse('2018-10-11 20:59:06.300000');
$this->assertSame('06.600000', $baseDate->closest($closestDate, $farthestDate)->format('s.u'));
}
public function testClosestWithFarDates()
{
$baseDate = Carbon::parse('2018-10-11 20:59:06.500000');
$closestDate = Carbon::parse('-4025-10-11 20:59:06.600000');
$farthestDate = Carbon::parse('9995-10-11 20:59:06.300000');
$this->assertSame('06.600000', $baseDate->closest($closestDate, $farthestDate)->format('s.u'));
}
public function testFarthest()
{
$instance = Carbon::create(2015, 5, 28, 12, 0, 0);
$dt1 = Carbon::create(2015, 5, 28, 11, 0, 0);
$dt2 = Carbon::create(2015, 5, 28, 14, 0, 0);
$farthest = $instance->farthest($dt1, $dt2);
$this->assertSame($dt2, $farthest);
}
public function testFarthestWithEquals()
{
$instance = Carbon::create(2015, 5, 28, 12, 0, 0);
$dt1 = Carbon::create(2015, 5, 28, 12, 0, 0);
$dt2 = Carbon::create(2015, 5, 28, 14, 0, 0);
$farthest = $instance->farthest($dt1, $dt2);
$this->assertSame($dt2, $farthest);
}
public function testFarthestWithMicroseconds()
{
$baseDate = Carbon::parse('2018-10-11 20:59:06.500000');
$closestDate = Carbon::parse('2018-10-11 20:59:06.600000');
$farthestDate = Carbon::parse('2018-10-11 20:59:06.300000');
$this->assertSame('06.300000', $baseDate->farthest($closestDate, $farthestDate)->format('s.u'));
}
public function testFarthestWithFarDates()
{
$baseDate = Carbon::parse('2018-10-11 20:59:06.500000');
$closestDate = Carbon::parse('-4025-10-11 20:59:06.600000');
$farthestDate = Carbon::parse('9995-10-11 20:59:06.300000');
$this->assertSame('06.300000', $baseDate->farthest($closestDate, $farthestDate)->format('s.u'));
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/CreateFromDateTest.php | tests/Carbon/CreateFromDateTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use DateTimeZone;
use Tests\AbstractTestCase;
class CreateFromDateTest extends AbstractTestCase
{
public function testCreateFromDateWithDefaults()
{
$d = Carbon::createFromDate();
$this->assertSame($d->timestamp, Carbon::create(null, null, null, null, null, null)->timestamp);
}
public function testCreateFromDate()
{
$d = Carbon::createFromDate(1975, 5, 21);
$this->assertCarbon($d, 1975, 5, 21);
}
public function testCreateFromDateWithYear()
{
$d = Carbon::createFromDate(1975);
$this->assertSame(1975, $d->year);
}
public function testCreateFromDateWithMonth()
{
$d = Carbon::createFromDate(null, 5);
$this->assertSame(5, $d->month);
}
public function testCreateFromDateWithDay()
{
$d = Carbon::createFromDate(null, null, 21);
$this->assertSame(21, $d->day);
}
public function testCreateFromDateWithTimezone()
{
$d = Carbon::createFromDate(1975, 5, 21, 'Europe/London');
$this->assertCarbon($d, 1975, 5, 21);
$this->assertSame('Europe/London', $d->tzName);
}
public function testCreateFromDateWithDateTimeZone()
{
$d = Carbon::createFromDate(1975, 5, 21, new DateTimeZone('Europe/London'));
$this->assertCarbon($d, 1975, 5, 21);
$this->assertSame('Europe/London', $d->tzName);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/CreateFromTimeTest.php | tests/Carbon/CreateFromTimeTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\Exceptions\InvalidFormatException;
use DateTimeImmutable;
use DateTimeZone;
use InvalidArgumentException;
use Tests\AbstractTestCase;
class CreateFromTimeTest extends AbstractTestCase
{
public function testCreateWithTestNow()
{
Carbon::setTestNow($testNow = Carbon::create(2011, 1, 1, 12, 13, 14));
$dt = Carbon::create(null, null, null, null, null, null);
$this->assertCarbon($dt, 2011, 1, 1, 12, 13, 14);
$this->assertTrue($testNow->eq($dt));
}
public function testCreateFromDateWithDefaults()
{
$d = Carbon::createFromTime();
$this->assertSame($d->timestamp, Carbon::create(null, null, null, 0, 0, 0)->timestamp);
}
public function testCreateFromDateWithNull()
{
$d = Carbon::createFromTime(null, null, null);
$this->assertSame($d->timestamp, Carbon::create(null, null, null, null, null, null)->timestamp);
}
public function testCreateFromTime()
{
$d = Carbon::createFromTime(23, 5, 21);
$this->assertCarbon($d, Carbon::now()->year, Carbon::now()->month, Carbon::now()->day, 23, 5, 21);
}
public function testCreateFromTimeWithTestNow()
{
Carbon::setTestNow();
$testTime = Carbon::createFromTime(12, 0, 0, 'GMT-25');
$today = Carbon::today('GMT-25')->modify('12:00');
$this->assertSame('12:00 -25:00', $testTime->format('H:i e'));
$this->assertSame($testTime->toIso8601String(), $today->toIso8601String());
$knownDate = Carbon::instance(new DateTimeImmutable('now UTC'));
Carbon::setTestNow($knownDate);
$testTime = Carbon::createFromTime(12, 0, 0, 'GMT-25');
$today = Carbon::today('GMT-25')->modify('12:00');
$this->assertSame('12:00 -25:00', $testTime->format('H:i e'));
$this->assertSame($testTime->toIso8601String(), $today->toIso8601String());
}
public function testCreateFromTimeGreaterThan99()
{
$this->expectExceptionObject(new InvalidArgumentException(
'second must be between 0 and 99, 100 given',
));
Carbon::createFromTime(23, 5, 100);
}
public function testCreateFromTimeWithHour()
{
$d = Carbon::createFromTime(22);
$this->assertSame(22, $d->hour);
$this->assertSame(0, $d->minute);
$this->assertSame(0, $d->second);
}
public function testCreateFromTimeWithMinute()
{
$d = Carbon::createFromTime(null, 5);
$this->assertSame(5, $d->minute);
}
public function testCreateFromTimeWithSecond()
{
$d = Carbon::createFromTime(null, null, 21);
$this->assertSame(21, $d->second);
}
public function testCreateFromTimeWithDateTimeZone()
{
$d = Carbon::createFromTime(12, 0, 0, new DateTimeZone('Europe/London'));
$this->assertCarbon($d, Carbon::now('Europe/London')->year, Carbon::now('Europe/London')->month, Carbon::now('Europe/London')->day, 12, 0, 0);
$this->assertSame('Europe/London', $d->tzName);
}
public function testCreateFromTimeWithTimeZoneString()
{
$d = Carbon::createFromTime(12, 0, 0, 'Europe/London');
$this->assertCarbon($d, Carbon::now('Europe/London')->year, Carbon::now('Europe/London')->month, Carbon::now('Europe/London')->day, 12, 0, 0);
$this->assertSame('Europe/London', $d->tzName);
}
public function testCreateFromTimeWithTimeZoneOnNow()
{
// disable test for now
// because we need Carbon::now() in Carbon::create() to work with given TZ
$test = Carbon::getTestNow();
Carbon::setTestNow();
$tz = 'Etc/GMT+12';
try {
$now = Carbon::now($tz);
} catch (InvalidFormatException $exception) {
if ($exception->getMessage() !== 'Unknown or bad timezone (Etc/GMT+12)') {
throw $exception;
}
$tz = 'GMT+12';
$now = Carbon::now($tz);
}
$dt = Carbon::createFromTime($now->hour, $now->minute, $now->second, $tz);
// re-enable test
Carbon::setTestNow($test);
// tested without microseconds
// because they appear within calls to Carbon
$this->assertSame($now->format('c'), $dt->format('c'));
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/TestingAidsTest.php | tests/Carbon/TestingAidsTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use DateTimeImmutable;
use DateTimeZone;
use Exception;
use InvalidArgumentException;
use stdClass;
use SubCarbon;
use Tests\AbstractTestCase;
class TestingAidsTest extends AbstractTestCase
{
public function testTestingAidsWithTestNowNotSet()
{
Carbon::setTestNow();
$this->assertFalse(Carbon::hasTestNow());
$this->assertNull(Carbon::getTestNow());
}
public function testTestingAidsWithTestNowSet()
{
Carbon::setTestNow($yesterday = Carbon::yesterday());
$this->assertTrue(Carbon::hasTestNow());
$this->assertEquals($yesterday, Carbon::getTestNow());
}
public function testTestingAidsWithTestNowSetToString()
{
Carbon::setTestNow('2016-11-23');
$this->assertTrue(Carbon::hasTestNow());
$this->assertEquals(Carbon::getTestNow(), Carbon::parse('2016-11-23'));
}
public function testConstructorWithTestValueSet()
{
Carbon::setTestNow($yesterday = Carbon::yesterday());
$this->assertEquals($yesterday, new Carbon());
$this->assertEquals($yesterday, new Carbon(null));
$this->assertEquals($yesterday, new Carbon(''));
$this->assertEquals($yesterday, new Carbon('now'));
}
public function testNowWithTestValueSet()
{
Carbon::setTestNow($yesterday = Carbon::yesterday());
$this->assertEquals($yesterday, Carbon::now());
}
public function testParseWithTestValueSet()
{
$testNow = Carbon::yesterday();
$this->wrapWithTestNow(function () use ($testNow) {
$this->assertEquals($testNow, Carbon::parse(null));
$this->assertEquals($testNow, Carbon::parse(''));
$this->assertEquals($testNow, Carbon::parse('now'));
}, $testNow);
}
public function testNowWithClosureValue()
{
$mockedNow = Carbon::parse('2019-09-21 12:34:56.123456');
$delta = 0;
Carbon::setTestNow(function (Carbon $now) use (&$mockedNow, &$delta) {
$this->assertInstanceOfCarbon($now);
return $mockedNow->copy()->tz($now->tz)->addMicroseconds($delta);
});
$this->assertSame('2019-09-21 12:34:56.123456', Carbon::now()->format('Y-m-d H:i:s.u'));
$this->assertSame('2019-09-21 00:00:00.000000', Carbon::today()->format('Y-m-d H:i:s.u'));
$this->assertSame('2019-09-22 00:00:00.000000', Carbon::create('tomorrow')->format('Y-m-d H:i:s.u'));
$this->assertSame('2018-06-15 12:34:00.000000', Carbon::create(2018, 6, 15, null, null)->format('Y-m-d H:i:s.u'));
$delta = 11111111;
$date = Carbon::now();
$this->assertSame('America/Toronto', $date->tzName);
$this->assertSame('2019-09-21 12:35:07.234567', $date->format('Y-m-d H:i:s.u'));
$date = Carbon::today();
$this->assertSame('America/Toronto', $date->tzName);
$this->assertSame('2019-09-21 00:00:00.000000', $date->format('Y-m-d H:i:s.u'));
$date = Carbon::create('tomorrow');
$this->assertSame('America/Toronto', $date->tzName);
$this->assertSame('2019-09-22 00:00:00.000000', $date->format('Y-m-d H:i:s.u'));
$date = Carbon::create(2018, 6, 15, null, null);
$this->assertSame('America/Toronto', $date->tzName);
$this->assertSame('2018-06-15 12:35:00.000000', $date->format('Y-m-d H:i:s.u'));
date_default_timezone_set('UTC');
$date = Carbon::now();
$this->assertSame('UTC', $date->tzName);
$this->assertSame('2019-09-21 16:35:07.234567', $date->format('Y-m-d H:i:s.u'));
$date = Carbon::today();
$this->assertSame('UTC', $date->tzName);
$this->assertSame('2019-09-21 00:00:00.000000', $date->format('Y-m-d H:i:s.u'));
$date = Carbon::create('tomorrow');
$this->assertSame('UTC', $date->tzName);
$this->assertSame('2019-09-22 00:00:00.000000', $date->format('Y-m-d H:i:s.u'));
$date = Carbon::create(2018, 6, 15, null, null);
$this->assertSame('UTC', $date->tzName);
$this->assertSame('2018-06-15 16:35:00.000000', $date->format('Y-m-d H:i:s.u'));
date_default_timezone_set('America/Toronto');
}
public function testParseRelativeWithTestValueSet()
{
$testNow = Carbon::parse('2013-09-01 05:15:05');
$this->wrapWithTestNow(function () {
$this->assertSame('2013-09-01 05:10:05', Carbon::parse('5 minutes ago')->toDateTimeString());
$this->assertSame('2013-08-25 05:15:05', Carbon::parse('1 week ago')->toDateTimeString());
$this->assertSame('2013-09-02 00:00:00', Carbon::parse('tomorrow')->toDateTimeString());
$this->assertSame('2013-09-01 00:00:00', Carbon::parse('today')->toDateTimeString());
$this->assertSame('2013-08-31 00:00:00', Carbon::parse('yesterday')->toDateTimeString());
$this->assertSame('2013-09-02 05:15:05', Carbon::parse('+1 day')->toDateTimeString());
$this->assertSame('2013-08-31 05:15:05', Carbon::parse('-1 day')->toDateTimeString());
$this->assertSame('2013-09-02 00:00:00', Carbon::parse('next monday')->toDateTimeString());
$this->assertSame('2013-09-03 00:00:00', Carbon::parse('next tuesday')->toDateTimeString());
$this->assertSame('2013-09-04 00:00:00', Carbon::parse('next wednesday')->toDateTimeString());
$this->assertSame('2013-09-05 00:00:00', Carbon::parse('next thursday')->toDateTimeString());
$this->assertSame('2013-09-06 00:00:00', Carbon::parse('next friday')->toDateTimeString());
$this->assertSame('2013-09-07 00:00:00', Carbon::parse('next saturday')->toDateTimeString());
$this->assertSame('2013-09-08 00:00:00', Carbon::parse('next sunday')->toDateTimeString());
$this->assertSame('2013-08-26 00:00:00', Carbon::parse('last monday')->toDateTimeString());
$this->assertSame('2013-08-27 00:00:00', Carbon::parse('last tuesday')->toDateTimeString());
$this->assertSame('2013-08-28 00:00:00', Carbon::parse('last wednesday')->toDateTimeString());
$this->assertSame('2013-08-29 00:00:00', Carbon::parse('last thursday')->toDateTimeString());
$this->assertSame('2013-08-30 00:00:00', Carbon::parse('last friday')->toDateTimeString());
$this->assertSame('2013-08-31 00:00:00', Carbon::parse('last saturday')->toDateTimeString());
$this->assertSame('2013-08-25 00:00:00', Carbon::parse('last sunday')->toDateTimeString());
$this->assertSame('2013-09-02 00:00:00', Carbon::parse('this monday')->toDateTimeString());
$this->assertSame('2013-09-03 00:00:00', Carbon::parse('this tuesday')->toDateTimeString());
$this->assertSame('2013-09-04 00:00:00', Carbon::parse('this wednesday')->toDateTimeString());
$this->assertSame('2013-09-05 00:00:00', Carbon::parse('this thursday')->toDateTimeString());
$this->assertSame('2013-09-06 00:00:00', Carbon::parse('this friday')->toDateTimeString());
$this->assertSame('2013-09-07 00:00:00', Carbon::parse('this saturday')->toDateTimeString());
$this->assertSame('2013-09-01 00:00:00', Carbon::parse('this sunday')->toDateTimeString());
$this->assertSame('2013-10-01 05:15:05', Carbon::parse('first day of next month')->toDateTimeString());
$this->assertSame('2013-09-30 05:15:05', Carbon::parse('last day of this month')->toDateTimeString());
}, $testNow);
}
public function testHasRelativeKeywords()
{
$this->assertFalse(Carbon::hasRelativeKeywords('sunday 2015-02-23'));
$this->assertTrue(Carbon::hasRelativeKeywords('today +2014 days'));
$this->assertTrue(Carbon::hasRelativeKeywords('next sunday -3600 seconds'));
$this->assertTrue(Carbon::hasRelativeKeywords('last day of this month'));
$this->assertFalse(Carbon::hasRelativeKeywords('last day of december 2015'));
$this->assertTrue(Carbon::hasRelativeKeywords('first sunday of next month'));
$this->assertFalse(Carbon::hasRelativeKeywords('first sunday of January 2017'));
}
public function testParseRelativeWithMinusSignsInDate()
{
$testNow = Carbon::parse('2013-09-01 05:15:05');
$this->wrapWithTestNow(function () {
$this->assertSame('2000-01-03 00:00:00', Carbon::parse('2000-1-3')->toDateTimeString());
$this->assertSame('2000-10-10 00:00:00', Carbon::parse('2000-10-10')->toDateTimeString());
}, $testNow);
$this->assertSame('2000-01-03 00:00:00', Carbon::parse('2000-1-3')->toDateTimeString());
$this->assertSame('2000-10-10 00:00:00', Carbon::parse('2000-10-10')->toDateTimeString());
}
public function testTimeZoneWithTestValueSet()
{
$testNow = Carbon::parse('2013-07-01 12:00:00', 'America/New_York');
$this->wrapWithTestNow(function () {
$this->assertSame('2013-07-01T12:00:00-04:00', Carbon::parse('now')->toIso8601String());
$this->assertSame('2013-07-01T11:00:00-05:00', Carbon::parse('now', 'America/Mexico_City')->toIso8601String());
$this->assertSame('2013-07-01T09:00:00-07:00', Carbon::parse('now', 'America/Vancouver')->toIso8601String());
}, $testNow);
}
public function testSetTestNowAndTimezoneWithBadTimezone(): void
{
$this->expectExceptionObject(new InvalidArgumentException(
"Timezone ID '-05:00' is invalid, did you mean 'America/Chicago'?\n".
"It must be one of the IDs from DateTimeZone::listIdentifiers(),\n".
'For the record, hours/minutes offset are relevant only for a particular moment, but not as a default timezone.'
));
Carbon::setTestNowAndTimezone(Carbon::parse('2018-05-06T12:00:00-05:00'));
}
public function testSetTestNowAndTimezoneWithBadTimezoneWithErrorAsException(): void
{
$this->expectExceptionObject(new InvalidArgumentException(
"Timezone ID '-05:00' is invalid, did you mean 'America/Chicago'?\n".
"It must be one of the IDs from DateTimeZone::listIdentifiers(),\n".
'For the record, hours/minutes offset are relevant only for a particular moment, but not as a default timezone.'
));
$this->withErrorAsException(function () {
Carbon::setTestNowAndTimezone(Carbon::parse('2018-05-06T12:00:00-05:00'));
});
}
public function testSetTestNowAndTimezoneWithNull(): void
{
Carbon::setTestNowAndTimezone();
Carbon::setTestNowAndTimezone(); // replay-able with no effect
foreach ([null, 'UTC', 'Asia/Tokyo'] as $originalTimezone) {
$originalTimezone
? date_default_timezone_set($originalTimezone)
: ($originalTimezone = date_default_timezone_get());
Carbon::setTestNowAndTimezone('2013-09-01 05:10:15 America/Vancouver', 'America/Vancouver');
$this->assertSame('America/Vancouver', date_default_timezone_get());
$this->assertSame('America/Vancouver', Carbon::now()->tzName);
Carbon::setTestNowAndTimezone();
$this->assertFalse(Carbon::hasTestNow());
$this->assertSame($originalTimezone, date_default_timezone_get());
$this->assertSame($originalTimezone, Carbon::now()->tzName);
}
}
public function testCreateFromPartialFormat()
{
Carbon::setTestNowAndTimezone('2013-09-01 05:10:15 America/Vancouver', 'America/Vancouver');
// Simple partial time.
$this->assertSame('2018-05-06T05:10:15-07:00', Carbon::createFromFormat('Y-m-d', '2018-05-06')->toIso8601String());
$this->assertSame('2013-09-01T10:20:30-07:00', Carbon::createFromFormat('H:i:s', '10:20:30')->toIso8601String());
// Custom timezone.
$this->assertSame('2013-09-01T10:20:00+03:00', Carbon::createFromFormat('H:i e', '10:20 Europe/Kiev')->toIso8601String());
$this->assertSame('2013-09-01T10:20:00+01:00', Carbon::createFromFormat('H:i', '10:20', 'Europe/London')->toIso8601String());
$this->assertSame('2013-09-01T11:30:00+07:00', Carbon::createFromFormat('H:i:s e', '11:30:00+07:00')->toIso8601String());
$this->assertSame('2013-09-01T11:30:00+05:00', Carbon::createFromFormat('H:i:s', '11:30:00', '+05:00')->toIso8601String());
// Escaped timezone.
$this->assertSame('2013-09-01T05:10:15-07:00', Carbon::createFromFormat('\e', 'e')->toIso8601String());
// Weird format, naive modify would fail here.
$this->assertSame('2005-08-09T05:10:15-07:00', Carbon::createFromFormat('l jS \of F Y', 'Tuesday 9th of August 2005')->toIso8601String());
$this->assertSame('2013-09-01T00:12:13-07:00', Carbon::createFromFormat('i:s', '12:13')->toIso8601String());
$this->assertSame('2018-09-05T05:10:15-07:00', Carbon::createFromFormat('Y/d', '2018/5')->toIso8601String());
// Resetting to epoch.
$this->assertSame('2018-05-06T00:00:00-07:00', Carbon::createFromFormat('!Y-m-d', '2018-05-06')->toIso8601String());
$this->assertSame('1970-01-01T10:20:30-08:00', Carbon::createFromFormat('Y-m-d! H:i:s', '2018-05-06 10:20:30')->toIso8601String());
$this->assertSame('2018-05-06T00:00:00-07:00', Carbon::createFromFormat('Y-m-d|', '2018-05-06')->toIso8601String());
$this->assertSame('1970-01-01T10:20:30-08:00', Carbon::createFromFormat('|H:i:s', '10:20:30')->toIso8601String());
$kyiv = $this->firstValidTimezoneAmong(['Europe/Kyiv', 'Europe/Kiev'])->getName();
// Resetting to epoch (timezone fun).
$this->assertSame('1970-01-01T00:00:00-08:00', Carbon::createFromFormat('|', '')->toIso8601String());
$this->assertSame('1970-01-01T00:00:00+03:00', Carbon::createFromFormat('e|', $kyiv)->toIso8601String());
$this->assertSame('1970-01-01T00:00:00+01:00', Carbon::createFromFormat('|', '', 'Europe/London')->toIso8601String());
$this->assertSame('1970-01-01T00:00:00-08:00', Carbon::createFromFormat('!', '')->toIso8601String());
$this->assertSame('1970-01-01T00:00:00+03:00', Carbon::createFromFormat('!e', $kyiv)->toIso8601String());
$this->assertSame('1970-01-01T00:00:00+01:00', Carbon::createFromFormat('!', '', 'Europe/London')->toIso8601String());
$this->assertSame('1970-01-01T00:00:00-08:00', Carbon::createFromFormat('e!', $kyiv)->toIso8601String());
// Escaped epoch resets.
$this->assertSame('2013-09-01T05:10:15-07:00', Carbon::createFromFormat('\|', '|')->toIso8601String());
$this->assertSame('2013-09-01T05:10:15-07:00', Carbon::createFromFormat('\!', '!')->toIso8601String());
$this->assertSame('2013-09-01T05:10:15+03:00', Carbon::createFromFormat('e \!', $kyiv.' !')->toIso8601String());
}
public function testCreateFromPartialFormatWithMicroseconds()
{
Carbon::setTestNowAndTimezone(Carbon::parse('2013-09-01 05:10:15.123456', 'America/Vancouver'));
$this->assertSame('2018-05-06 05:10:15.123456', Carbon::createFromFormat('Y-m-d', '2018-05-06')->format('Y-m-d H:i:s.u'));
$this->assertSame('2013-09-01 10:20:30.654321', Carbon::createFromFormat('H:i:s.u', '10:20:30.654321')->format('Y-m-d H:i:s.u'));
}
public function testCreateFromDateTimeInterface()
{
Carbon::setTestNowAndTimezone(date_create('2013-09-01 05:10:15.123456', new DateTimeZone('America/Vancouver')));
$this->assertSame('2018-05-06 05:10:15.123456', Carbon::createFromFormat('Y-m-d', '2018-05-06')->format('Y-m-d H:i:s.u'));
$this->assertSame('2013-09-01 10:20:30.654321', Carbon::createFromFormat('H:i:s.u', '10:20:30.654321')->format('Y-m-d H:i:s.u'));
}
public function testSetTestNow()
{
Carbon::setTestNow(null);
$n1 = Carbon::now();
$n2 = Carbon::now();
$this->assertTrue($n2 > $n1);
Carbon::setTestNow('2013-09-01 10:20:30.654321');
$n1 = Carbon::now();
$n2 = Carbon::now();
$this->assertFalse($n2 > $n1);
Carbon::setTestNow(false);
$n1 = Carbon::now();
$n2 = Carbon::now();
$this->assertTrue($n2 > $n1);
}
public function testSetTestNowGlobally(): void
{
require_once __DIR__.'/../Fixtures/SubCarbon.php';
SubCarbon::setTestNow('2018-05-06 05:10:15.123456');
$this->assertSame('2018-05-06 05:10:15.123456', SubCarbon::now()->format('Y-m-d H:i:s.u'));
$this->assertSame('2018-05-06 05:10:15.123456', Carbon::now()->format('Y-m-d H:i:s.u'));
$this->assertSame('2018-05-06 05:10:15.123456', CarbonImmutable::now()->format('Y-m-d H:i:s.u'));
}
public function testWithTestNow()
{
$self = $this;
$testNow = '2020-09-16 10:20:00';
$object = new stdClass();
$result = Carbon::withTestNow($testNow, static function () use ($self, $testNow, $object) {
$currentTime = Carbon::now();
$self->assertSame($testNow, $currentTime->format('Y-m-d H:i:s'));
return $object;
});
$this->assertSame($object, $result);
$currentTime = Carbon::now();
$this->assertNotSame($testNow, $currentTime->format('Y-m-d H:i:s'));
}
public function testWithTestNowRestoresPreviousTestNow()
{
Carbon::setTestNow('2024-01-01 12:00:00');
Carbon::withTestNow('2024-06-15 10:00:00', function () {
$this->assertEquals('2024-06-15', Carbon::now()->format('Y-m-d'));
});
$this->assertEquals('2024-01-01', Carbon::now()->format('Y-m-d'));
Carbon::setTestNow();
}
public function testWithTestNowWithException()
{
$testNow = '2020-09-16 10:20:00';
try {
Carbon::withTestNow($testNow, static function () {
throw new Exception();
});
} catch (Exception $e) {
// ignore
}
$currentTime = Carbon::now();
$this->assertNotSame($testNow, $currentTime->format('Y-m-d H:i:s'));
}
public function testWithModifyReturningDateTime()
{
Carbon::setTestNowAndTimezone(new class('2000-01-01 00:00 UTC') extends Carbon {
public function modify($modify)
{
return $this->toDateTimeImmutable()->modify($modify);
}
});
$currentTime = new Carbon('tomorrow');
$this->assertSame('2000-01-02 00:00:00 UTC', $currentTime->format('Y-m-d H:i:s e'));
}
public function testTimezoneConsistency()
{
Carbon::setTestNow();
date_default_timezone_set('UTC');
$currentDate = Carbon::now()->setTimezone('America/Los_Angeles');
$laDate = $currentDate->format('Y-m-d H:i:s e');
$utcDate = $currentDate->copy()->utc()->format('Y-m-d H:i:s e');
Carbon::setTestNow($currentDate);
$this->assertSame($utcDate, Carbon::now()->format('Y-m-d H:i:s e'));
$this->assertSame($utcDate, Carbon::now('UTC')->format('Y-m-d H:i:s e'));
Carbon::setTestNowAndTimezone($currentDate);
$this->assertSame($laDate, Carbon::now()->format('Y-m-d H:i:s e'));
$this->assertSame($utcDate, Carbon::now('UTC')->format('Y-m-d H:i:s e'));
}
public function testSleep()
{
$initial = Carbon::now('UTC');
Carbon::setTestNow($initial);
$before = microtime(true);
Carbon::sleep(5);
Carbon::sleep(20);
$after = microtime(true);
$this->assertLessThan(0.1, $after - $before);
$this->assertSame(
$initial->copy()->addSeconds(25)->format('Y-m-d H:i:s.u'),
Carbon::now('UTC')->format('Y-m-d H:i:s.u'),
);
Carbon::setTestNow(null);
$before = new DateTimeImmutable('now UTC');
Carbon::sleep(0.5);
$after = new DateTimeImmutable('now UTC');
$this->assertSame(
5,
(int) round(10 * ((float) $after->format('U.u') - ((float) $before->format('U.u')))),
);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/NowAndOtherStaticHelpersTest.php | tests/Carbon/NowAndOtherStaticHelpersTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use DateTime;
use DateTimeZone;
use Tests\AbstractTestCase;
class NowAndOtherStaticHelpersTest extends AbstractTestCase
{
public function testNow()
{
$dt = Carbon::now();
$this->assertSame($this->now->getTimestamp(), $dt->timestamp);
$this->assertSame($this->now->unix(), $dt->timestamp);
Carbon::setTestNow();
$before = $this->getTimestamp();
$dt = Carbon::now();
$after = $this->getTimestamp();
$this->assertGreaterThanOrEqual($before, $dt->timestamp);
$this->assertLessThanOrEqual($after, $dt->timestamp);
}
public function testGetPreciseTimestamp()
{
$dt = Carbon::parse('2018-01-06 12:34:10.987126');
$this->assertSame(1515260.0, $dt->getPreciseTimestamp(-3));
$this->assertSame(151526005.0, $dt->getPreciseTimestamp(-1));
$this->assertSame(1515260051.0, $dt->getPreciseTimestamp(0));
$this->assertSame(15152600510.0, $dt->getPreciseTimestamp(1));
$this->assertSame(151526005099.0, $dt->getPreciseTimestamp(2));
$this->assertSame(1515260050987.0, $dt->valueOf());
$this->assertSame(15152600509871.0, $dt->getPreciseTimestamp(4));
$this->assertSame(151526005098713.0, $dt->getPreciseTimestamp(5));
$this->assertSame(1515260050987126.0, $dt->getPreciseTimestamp(6));
$this->assertSame(151526005098712600.0, $dt->getPreciseTimestamp(8));
$this->assertSame(1515260050987126000.0, $dt->getPreciseTimestamp(9));
}
public function testGetTimestampMs()
{
$dt = Carbon::parse('2018-01-06 12:34:10.987126');
$this->assertSame(1515260050987, $dt->getTimestampMs());
}
public function testNowWithTimezone()
{
$dt = Carbon::now('Europe/London');
$this->assertSame($this->now->getTimestamp(), $dt->timestamp);
Carbon::setTestNow();
$before = $this->getTimestamp();
$dt = Carbon::now('Europe/London');
$after = $this->getTimestamp();
$this->assertGreaterThanOrEqual($before, $dt->timestamp);
$this->assertLessThanOrEqual($after, $dt->timestamp);
$this->assertSame('Europe/London', $dt->tzName);
}
public function testToday()
{
$dt = Carbon::today();
$this->assertSame(date('Y-m-d 00:00:00'), $dt->toDateTimeString());
}
public function testTodayWithTimezone()
{
$dt = Carbon::today('Europe/London');
$dt2 = new DateTime('now', new DateTimeZone('Europe/London'));
$this->assertSame($dt2->format('Y-m-d 00:00:00'), $dt->toDateTimeString());
}
public function testTomorrow()
{
$dt = Carbon::tomorrow();
$dt2 = new DateTime('tomorrow');
$this->assertSame($dt2->format('Y-m-d 00:00:00'), $dt->toDateTimeString());
}
public function testTomorrowWithTimezone()
{
$dt = Carbon::tomorrow('Europe/London');
$dt2 = new DateTime('tomorrow', new DateTimeZone('Europe/London'));
$this->assertSame($dt2->format('Y-m-d 00:00:00'), $dt->toDateTimeString());
}
public function testYesterday()
{
$dt = Carbon::yesterday();
$dt2 = new DateTime('yesterday');
$this->assertSame($dt2->format('Y-m-d 00:00:00'), $dt->toDateTimeString());
}
public function testYesterdayWithTimezone()
{
$dt = Carbon::yesterday('Europe/London');
$dt2 = new DateTime('yesterday', new DateTimeZone('Europe/London'));
$this->assertSame($dt2->format('Y-m-d 00:00:00'), $dt->toDateTimeString());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/CopyTest.php | tests/Carbon/CopyTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Tests\AbstractTestCase;
class CopyTest extends AbstractTestCase
{
public function testCopy()
{
$dating = Carbon::now();
$dating2 = $dating->copy();
$this->assertNotSame($dating, $dating2);
}
public function testClone()
{
$dating = Carbon::now();
$dating2 = $dating->clone();
$this->assertNotSame($dating, $dating2);
}
public function testCopyEnsureTzIsCopied()
{
$dating = Carbon::createFromDate(2000, 1, 1, 'Europe/London');
$dating2 = $dating->copy();
$this->assertSame($dating->tzName, $dating2->tzName);
$this->assertSame($dating->offset, $dating2->offset);
}
public function testCopyEnsureMicrosAreCopied()
{
$micro = 254687;
$dating = Carbon::createFromFormat('Y-m-d H:i:s.u', '2014-02-01 03:45:27.'.$micro);
$dating2 = $dating->copy();
$this->assertSame($micro, $dating2->micro);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/CreateFromTimeStringTest.php | tests/Carbon/CreateFromTimeStringTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use DateTimeZone;
use Tests\AbstractTestCase;
class CreateFromTimeStringTest extends AbstractTestCase
{
protected function setUp(): void
{
parent::setUp();
Carbon::setTestNow();
}
public function testCreateFromTimeString()
{
$d = Carbon::createFromTimeString('22:45');
$this->assertSame(22, $d->hour);
$this->assertSame(45, $d->minute);
$this->assertSame(0, $d->second);
$this->assertSame(0, $d->micro);
}
public function testCreateFromTimeStringWithSecond()
{
$d = Carbon::createFromTimeString('22:45:12');
$this->assertSame(22, $d->hour);
$this->assertSame(45, $d->minute);
$this->assertSame(12, $d->second);
$this->assertSame(0, $d->micro);
}
public function testCreateFromTimeStringWithMicroSecond()
{
$d = Carbon::createFromTimeString('22:45:00.625341');
$this->assertSame(22, $d->hour);
$this->assertSame(45, $d->minute);
$this->assertSame(0, $d->second);
$this->assertSame(625341, $d->micro);
}
public function testCreateFromTimeStringWithDateTimeZone()
{
$d = Carbon::createFromTimeString('12:20:30', new DateTimeZone('Europe/London'));
$this->assertCarbonTime($d, 12, 20, 30, 0);
$this->assertSame('Europe/London', $d->tzName);
}
public function testCreateFromTimeStringWithTimeZoneString()
{
$d = Carbon::createFromTimeString('12:20:30', 'Europe/London');
$this->assertCarbonTime($d, 12, 20, 30, 0);
$this->assertSame('Europe/London', $d->tzName);
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/WeekTest.php | tests/Carbon/WeekTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\CarbonInterface;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\AbstractTestCase;
class WeekTest extends AbstractTestCase
{
public const SAMPLE = [
'1990-12-20' => [
1990,
1990,
51,
51,
52,
52,
],
'1990-12-21' => [
1990,
1990,
51,
51,
52,
52,
],
'1990-12-22' => [
1990,
1990,
51,
51,
52,
52,
],
'1990-12-23' => [
1990,
1990,
52,
51,
52,
52,
],
'1990-12-24' => [
1990,
1990,
52,
52,
52,
52,
],
'1990-12-25' => [
1990,
1990,
52,
52,
52,
52,
],
'1990-12-26' => [
1990,
1990,
52,
52,
52,
52,
],
'1990-12-27' => [
1990,
1990,
52,
52,
52,
52,
],
'1990-12-28' => [
1990,
1990,
52,
52,
52,
52,
],
'1990-12-29' => [
1990,
1990,
52,
52,
52,
52,
],
'1990-12-30' => [
1991,
1990,
1,
52,
52,
52,
],
'1990-12-31' => [
1991,
1991,
1,
1,
52,
52,
],
'1991-01-01' => [
1991,
1991,
1,
1,
52,
52,
],
'1991-01-02' => [
1991,
1991,
1,
1,
52,
52,
],
'1991-01-03' => [
1991,
1991,
1,
1,
52,
52,
],
'1991-01-04' => [
1991,
1991,
1,
1,
52,
52,
],
'1991-01-05' => [
1991,
1991,
1,
1,
52,
52,
],
'1991-01-06' => [
1991,
1991,
2,
1,
52,
52,
],
'1991-01-07' => [
1991,
1991,
2,
2,
52,
52,
],
'1991-01-08' => [
1991,
1991,
2,
2,
52,
52,
],
'1991-01-09' => [
1991,
1991,
2,
2,
52,
52,
],
'1991-01-10' => [
1991,
1991,
2,
2,
52,
52,
],
'1991-12-20' => [
1991,
1991,
51,
51,
52,
52,
],
'1991-12-21' => [
1991,
1991,
51,
51,
52,
52,
],
'1991-12-22' => [
1991,
1991,
52,
51,
52,
52,
],
'1991-12-23' => [
1991,
1991,
52,
52,
52,
52,
],
'1991-12-24' => [
1991,
1991,
52,
52,
52,
52,
],
'1991-12-25' => [
1991,
1991,
52,
52,
52,
52,
],
'1991-12-26' => [
1991,
1991,
52,
52,
52,
52,
],
'1991-12-27' => [
1991,
1991,
52,
52,
52,
52,
],
'1991-12-28' => [
1991,
1991,
52,
52,
52,
52,
],
'1991-12-29' => [
1992,
1991,
1,
52,
52,
52,
],
'1991-12-30' => [
1992,
1992,
1,
1,
52,
52,
],
'1991-12-31' => [
1992,
1992,
1,
1,
52,
52,
],
'1992-01-01' => [
1992,
1992,
1,
1,
52,
53,
],
'1992-01-02' => [
1992,
1992,
1,
1,
52,
53,
],
'1992-01-03' => [
1992,
1992,
1,
1,
52,
53,
],
'1992-01-04' => [
1992,
1992,
1,
1,
52,
53,
],
'1992-01-05' => [
1992,
1992,
2,
1,
52,
53,
],
'1992-01-06' => [
1992,
1992,
2,
2,
52,
53,
],
'1992-01-07' => [
1992,
1992,
2,
2,
52,
53,
],
'1992-01-08' => [
1992,
1992,
2,
2,
52,
53,
],
'1992-01-09' => [
1992,
1992,
2,
2,
52,
53,
],
'1992-01-10' => [
1992,
1992,
2,
2,
52,
53,
],
'1992-12-20' => [
1992,
1992,
52,
51,
52,
53,
],
'1992-12-21' => [
1992,
1992,
52,
52,
52,
53,
],
'1992-12-22' => [
1992,
1992,
52,
52,
52,
53,
],
'1992-12-23' => [
1992,
1992,
52,
52,
52,
53,
],
'1992-12-24' => [
1992,
1992,
52,
52,
52,
53,
],
'1992-12-25' => [
1992,
1992,
52,
52,
52,
53,
],
'1992-12-26' => [
1992,
1992,
52,
52,
52,
53,
],
'1992-12-27' => [
1993,
1992,
1,
52,
52,
53,
],
'1992-12-28' => [
1993,
1992,
1,
53,
52,
53,
],
'1992-12-29' => [
1993,
1992,
1,
53,
52,
53,
],
'1992-12-30' => [
1993,
1992,
1,
53,
52,
53,
],
'1992-12-31' => [
1993,
1992,
1,
53,
52,
53,
],
'1993-01-01' => [
1993,
1992,
1,
53,
52,
52,
],
'1993-01-02' => [
1993,
1992,
1,
53,
52,
52,
],
'1993-01-03' => [
1993,
1992,
2,
53,
52,
52,
],
'1993-01-04' => [
1993,
1993,
2,
1,
52,
52,
],
'1993-01-05' => [
1993,
1993,
2,
1,
52,
52,
],
'1993-01-06' => [
1993,
1993,
2,
1,
52,
52,
],
'1993-01-07' => [
1993,
1993,
2,
1,
52,
52,
],
'1993-01-08' => [
1993,
1993,
2,
1,
52,
52,
],
'1993-01-09' => [
1993,
1993,
2,
1,
52,
52,
],
'1993-01-10' => [
1993,
1993,
3,
1,
52,
52,
],
'1993-12-20' => [
1993,
1993,
52,
51,
52,
52,
],
'1993-12-21' => [
1993,
1993,
52,
51,
52,
52,
],
'1993-12-22' => [
1993,
1993,
52,
51,
52,
52,
],
'1993-12-23' => [
1993,
1993,
52,
51,
52,
52,
],
'1993-12-24' => [
1993,
1993,
52,
51,
52,
52,
],
'1993-12-25' => [
1993,
1993,
52,
51,
52,
52,
],
'1993-12-26' => [
1994,
1993,
1,
51,
52,
52,
],
'1993-12-27' => [
1994,
1993,
1,
52,
52,
52,
],
'1993-12-28' => [
1994,
1993,
1,
52,
52,
52,
],
'1993-12-29' => [
1994,
1993,
1,
52,
52,
52,
],
'1993-12-30' => [
1994,
1993,
1,
52,
52,
52,
],
'1993-12-31' => [
1994,
1993,
1,
52,
52,
52,
],
'1994-01-01' => [
1994,
1993,
1,
52,
53,
52,
],
'1994-01-02' => [
1994,
1993,
2,
52,
53,
52,
],
'1994-01-03' => [
1994,
1994,
2,
1,
53,
52,
],
'1994-01-04' => [
1994,
1994,
2,
1,
53,
52,
],
'1994-01-05' => [
1994,
1994,
2,
1,
53,
52,
],
'1994-01-06' => [
1994,
1994,
2,
1,
53,
52,
],
'1994-01-07' => [
1994,
1994,
2,
1,
53,
52,
],
'1994-01-08' => [
1994,
1994,
2,
1,
53,
52,
],
'1994-01-09' => [
1994,
1994,
3,
1,
53,
52,
],
'1994-01-10' => [
1994,
1994,
3,
2,
53,
52,
],
'1994-12-20' => [
1994,
1994,
52,
51,
53,
52,
],
'1994-12-21' => [
1994,
1994,
52,
51,
53,
52,
],
'1994-12-22' => [
1994,
1994,
52,
51,
53,
52,
],
'1994-12-23' => [
1994,
1994,
52,
51,
53,
52,
],
'1994-12-24' => [
1994,
1994,
52,
51,
53,
52,
],
'1994-12-25' => [
1994,
1994,
53,
51,
53,
52,
],
'1994-12-26' => [
1994,
1994,
53,
52,
53,
52,
],
'1994-12-27' => [
1994,
1994,
53,
52,
53,
52,
],
'1994-12-28' => [
1994,
1994,
53,
52,
53,
52,
],
'1994-12-29' => [
1994,
1994,
53,
52,
53,
52,
],
'1994-12-30' => [
1994,
1994,
53,
52,
53,
52,
],
'1994-12-31' => [
1994,
1994,
53,
52,
53,
52,
],
'1995-01-01' => [
1995,
1994,
1,
52,
52,
52,
],
'1995-01-02' => [
1995,
1995,
1,
1,
52,
52,
],
'1995-01-03' => [
1995,
1995,
1,
1,
52,
52,
],
'1995-01-04' => [
1995,
1995,
1,
1,
52,
52,
],
'1995-01-05' => [
1995,
1995,
1,
1,
52,
52,
],
'1995-01-06' => [
1995,
1995,
1,
1,
52,
52,
],
'1995-01-07' => [
1995,
1995,
1,
1,
52,
52,
],
'1995-01-08' => [
1995,
1995,
2,
1,
52,
52,
],
'1995-01-09' => [
1995,
1995,
2,
2,
52,
52,
],
'1995-01-10' => [
1995,
1995,
2,
2,
52,
52,
],
'1995-12-20' => [
1995,
1995,
51,
51,
52,
52,
],
'1995-12-21' => [
1995,
1995,
51,
51,
52,
52,
],
'1995-12-22' => [
1995,
1995,
51,
51,
52,
52,
],
'1995-12-23' => [
1995,
1995,
51,
51,
52,
52,
],
'1995-12-24' => [
1995,
1995,
52,
51,
52,
52,
],
'1995-12-25' => [
1995,
1995,
52,
52,
52,
52,
],
'1995-12-26' => [
1995,
1995,
52,
52,
52,
52,
],
'1995-12-27' => [
1995,
1995,
52,
52,
52,
52,
],
'1995-12-28' => [
1995,
1995,
52,
52,
52,
52,
],
'1995-12-29' => [
1995,
1995,
52,
52,
52,
52,
],
'1995-12-30' => [
1995,
1995,
52,
52,
52,
52,
],
'1995-12-31' => [
1996,
1995,
1,
52,
52,
52,
],
'1996-01-01' => [
1996,
1996,
1,
1,
52,
52,
],
'1996-01-02' => [
1996,
1996,
1,
1,
52,
52,
],
'1996-01-03' => [
1996,
1996,
1,
1,
52,
52,
],
'1996-01-04' => [
1996,
1996,
1,
1,
52,
52,
],
'1996-01-05' => [
1996,
1996,
1,
1,
52,
52,
],
'1996-01-06' => [
1996,
1996,
1,
1,
52,
52,
],
'1996-01-07' => [
1996,
1996,
2,
1,
52,
52,
],
'1996-01-08' => [
1996,
1996,
2,
2,
52,
52,
],
'1996-01-09' => [
1996,
1996,
2,
2,
52,
52,
],
'1996-01-10' => [
1996,
1996,
2,
2,
52,
52,
],
'1996-12-20' => [
1996,
1996,
51,
51,
52,
52,
],
'1996-12-21' => [
1996,
1996,
51,
51,
52,
52,
],
'1996-12-22' => [
1996,
1996,
52,
51,
52,
52,
],
'1996-12-23' => [
1996,
1996,
52,
52,
52,
52,
],
'1996-12-24' => [
1996,
1996,
52,
52,
52,
52,
],
'1996-12-25' => [
1996,
1996,
52,
52,
52,
52,
],
'1996-12-26' => [
1996,
1996,
52,
52,
52,
52,
],
'1996-12-27' => [
1996,
1996,
52,
52,
52,
52,
],
'1996-12-28' => [
1996,
1996,
52,
52,
52,
52,
],
'1996-12-29' => [
1997,
1996,
1,
52,
52,
52,
],
'1996-12-30' => [
1997,
1997,
1,
1,
52,
52,
],
'1996-12-31' => [
1997,
1997,
1,
1,
52,
52,
],
'1997-01-01' => [
1997,
1997,
1,
1,
52,
52,
],
'1997-01-02' => [
1997,
1997,
1,
1,
52,
52,
],
'1997-01-03' => [
1997,
1997,
1,
1,
52,
52,
],
'1997-01-04' => [
1997,
1997,
1,
1,
52,
52,
],
'1997-01-05' => [
1997,
1997,
2,
1,
52,
52,
],
'1997-01-06' => [
1997,
1997,
2,
2,
52,
52,
],
'1997-01-07' => [
1997,
1997,
2,
2,
52,
52,
],
'1997-01-08' => [
1997,
1997,
2,
2,
52,
52,
],
'1997-01-09' => [
1997,
1997,
2,
2,
52,
52,
],
'1997-01-10' => [
1997,
1997,
2,
2,
52,
52,
],
'1997-12-20' => [
1997,
1997,
51,
51,
52,
52,
],
'1997-12-21' => [
1997,
1997,
52,
51,
52,
52,
],
'1997-12-22' => [
1997,
1997,
52,
52,
52,
52,
],
'1997-12-23' => [
1997,
1997,
52,
52,
52,
52,
],
'1997-12-24' => [
1997,
1997,
52,
52,
52,
52,
],
'1997-12-25' => [
1997,
1997,
52,
52,
52,
52,
],
'1997-12-26' => [
1997,
1997,
52,
52,
52,
52,
],
'1997-12-27' => [
1997,
1997,
52,
52,
52,
52,
],
'1997-12-28' => [
1998,
1997,
1,
52,
52,
52,
],
'1997-12-29' => [
1998,
1998,
1,
1,
52,
52,
],
'1997-12-30' => [
1998,
1998,
1,
1,
52,
52,
],
'1997-12-31' => [
1998,
1998,
1,
1,
52,
52,
],
'1998-01-01' => [
1998,
1998,
1,
1,
52,
53,
],
'1998-01-02' => [
1998,
1998,
1,
1,
52,
53,
],
'1998-01-03' => [
1998,
1998,
1,
1,
52,
53,
],
'1998-01-04' => [
1998,
1998,
2,
1,
52,
53,
],
'1998-01-05' => [
1998,
1998,
2,
2,
52,
53,
],
'1998-01-06' => [
1998,
1998,
2,
2,
52,
53,
],
'1998-01-07' => [
1998,
1998,
2,
2,
52,
53,
],
'1998-01-08' => [
1998,
1998,
2,
2,
52,
53,
],
'1998-01-09' => [
1998,
1998,
2,
2,
52,
53,
],
'1998-01-10' => [
1998,
1998,
2,
2,
52,
53,
],
'1998-12-20' => [
1998,
1998,
52,
51,
52,
53,
],
'1998-12-21' => [
1998,
1998,
52,
52,
52,
53,
],
'1998-12-22' => [
1998,
1998,
52,
52,
52,
53,
],
'1998-12-23' => [
1998,
1998,
52,
52,
52,
53,
],
'1998-12-24' => [
1998,
1998,
52,
52,
52,
53,
],
'1998-12-25' => [
1998,
1998,
52,
52,
52,
53,
],
'1998-12-26' => [
1998,
1998,
52,
52,
52,
53,
],
'1998-12-27' => [
1999,
1998,
1,
52,
52,
53,
],
'1998-12-28' => [
1999,
1998,
1,
53,
52,
53,
],
'1998-12-29' => [
1999,
1998,
1,
53,
52,
53,
],
'1998-12-30' => [
1999,
1998,
1,
53,
52,
53,
],
'1998-12-31' => [
1999,
1998,
1,
53,
52,
53,
],
'1999-01-01' => [
1999,
1998,
1,
53,
52,
52,
],
'1999-01-02' => [
1999,
1998,
1,
53,
52,
52,
],
'1999-01-03' => [
1999,
1998,
2,
53,
52,
52,
],
'1999-01-04' => [
1999,
1999,
2,
1,
52,
52,
],
'1999-01-05' => [
1999,
1999,
2,
1,
52,
52,
],
'1999-01-06' => [
1999,
1999,
2,
1,
52,
52,
],
'1999-01-07' => [
1999,
1999,
2,
1,
52,
52,
],
'1999-01-08' => [
1999,
1999,
2,
1,
52,
52,
],
'1999-01-09' => [
1999,
1999,
2,
1,
52,
52,
],
'1999-01-10' => [
1999,
1999,
3,
1,
52,
52,
],
'1999-12-20' => [
1999,
1999,
52,
51,
52,
52,
],
'1999-12-21' => [
1999,
1999,
52,
51,
52,
52,
],
'1999-12-22' => [
1999,
1999,
52,
51,
52,
52,
],
'1999-12-23' => [
1999,
1999,
52,
51,
52,
52,
],
'1999-12-24' => [
1999,
1999,
52,
51,
52,
52,
],
'1999-12-25' => [
1999,
1999,
52,
51,
52,
52,
],
'1999-12-26' => [
2000,
1999,
1,
51,
52,
52,
],
'1999-12-27' => [
2000,
1999,
1,
52,
52,
52,
],
'1999-12-28' => [
2000,
1999,
1,
52,
52,
52,
],
'1999-12-29' => [
2000,
1999,
1,
52,
52,
52,
],
'1999-12-30' => [
2000,
1999,
1,
52,
52,
52,
],
'1999-12-31' => [
2000,
1999,
1,
52,
52,
52,
],
'2000-01-01' => [
2000,
1999,
1,
52,
53,
52,
],
'2000-01-02' => [
2000,
1999,
2,
52,
53,
52,
],
'2000-01-03' => [
2000,
2000,
2,
1,
53,
52,
],
'2000-01-04' => [
2000,
2000,
2,
1,
53,
52,
],
'2000-01-05' => [
2000,
2000,
2,
1,
53,
52,
],
'2000-01-06' => [
2000,
2000,
2,
1,
53,
52,
],
'2000-01-07' => [
2000,
2000,
2,
1,
53,
52,
],
'2000-01-08' => [
2000,
2000,
2,
1,
53,
52,
],
'2000-01-09' => [
2000,
2000,
3,
1,
53,
52,
],
'2000-01-10' => [
2000,
2000,
3,
2,
53,
52,
],
'2000-12-20' => [
2000,
2000,
52,
51,
53,
52,
],
'2000-12-21' => [
2000,
2000,
52,
51,
53,
52,
],
'2000-12-22' => [
2000,
2000,
52,
51,
53,
52,
],
'2000-12-23' => [
2000,
2000,
52,
51,
53,
52,
],
'2000-12-24' => [
2000,
2000,
53,
51,
53,
52,
],
'2000-12-25' => [
2000,
2000,
53,
52,
53,
52,
],
'2000-12-26' => [
2000,
2000,
53,
52,
53,
52,
],
'2000-12-27' => [
2000,
2000,
53,
52,
53,
52,
],
'2000-12-28' => [
2000,
2000,
53,
52,
53,
52,
],
'2000-12-29' => [
2000,
2000,
53,
52,
53,
52,
],
'2000-12-30' => [
2000,
2000,
53,
52,
53,
52,
],
'2000-12-31' => [
2001,
2000,
1,
52,
53,
52,
],
'2001-01-01' => [
2001,
2001,
1,
1,
52,
52,
],
'2001-01-02' => [
2001,
2001,
1,
1,
52,
52,
],
'2001-01-03' => [
2001,
2001,
1,
1,
52,
52,
],
'2001-01-04' => [
2001,
2001,
1,
1,
52,
52,
],
'2001-01-05' => [
2001,
2001,
1,
1,
52,
52,
],
'2001-01-06' => [
2001,
2001,
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | true |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/InstanceTest.php | tests/Carbon/InstanceTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use DateTime;
use DateTimeZone;
use InvalidArgumentException;
use Tests\AbstractTestCase;
class InstanceTest extends AbstractTestCase
{
public function testInstanceFromDateTime()
{
$dating = Carbon::instance(DateTime::createFromFormat('Y-m-d H:i:s', '1975-05-21 22:32:11'));
$this->assertCarbon($dating, 1975, 5, 21, 22, 32, 11);
$dating = Carbon::parse(DateTime::createFromFormat('Y-m-d H:i:s', '1975-05-21 22:32:11'));
$this->assertCarbon($dating, 1975, 5, 21, 22, 32, 11);
}
public function testInstanceFromCarbon()
{
$dating = Carbon::instance(Carbon::create(1975, 5, 21, 22, 32, 11));
$this->assertCarbon($dating, 1975, 5, 21, 22, 32, 11);
}
public function testInstanceFromDateTimeKeepsTimezoneName()
{
$dating = Carbon::instance(DateTime::createFromFormat('Y-m-d H:i:s', '1975-05-21 22:32:11')->setTimezone(new DateTimeZone('America/Vancouver')));
$this->assertSame('America/Vancouver', $dating->tzName);
}
public function testInstanceFromCarbonKeepsTimezoneName()
{
$dating = Carbon::instance(Carbon::create(1975, 5, 21, 22, 32, 11)->setTimezone(new DateTimeZone('America/Vancouver')));
$this->assertSame('America/Vancouver', $dating->tzName);
}
public function testInstanceFromDateTimeKeepsMicros()
{
$micro = 254687;
$datetime = DateTime::createFromFormat('Y-m-d H:i:s.u', '2014-02-01 03:45:27.'.$micro);
$carbon = Carbon::instance($datetime);
$this->assertSame($micro, $carbon->micro);
}
public function testInstanceFromCarbonKeepsMicros()
{
$micro = 254687;
$carbon = Carbon::createFromFormat('Y-m-d H:i:s.u', '2014-02-01 03:45:27.'.$micro);
$carbon = Carbon::instance($carbon);
$this->assertSame($micro, $carbon->micro);
}
public function testTimezoneCopy()
{
$carbon = new Carbon('2017-06-27 13:14:15.123456', 'Europe/Paris');
$carbon = CarbonImmutable::instance($carbon);
$this->assertSame('2017-06-27 13:14:15.123456 Europe/Paris', $carbon->format('Y-m-d H:i:s.u e'));
}
public function testInstanceStateSetBySetStateMethod()
{
$carbon = Carbon::__set_state([
'date' => '2017-05-18 13:02:15.273420',
'timezone_type' => 3,
'timezone' => 'UTC',
]);
$this->assertInstanceOf(Carbon::class, $carbon);
$this->assertSame('2017-05-18 13:02:15.273420', $carbon->format('Y-m-d H:i:s.u'));
}
public function testInstanceStateSetBySetStateString()
{
$carbon = Carbon::__set_state('2017-05-18 13:02:15.273420');
$this->assertInstanceOf(Carbon::class, $carbon);
$this->assertSame('2017-05-18 13:02:15.273420', $carbon->format('Y-m-d H:i:s.u'));
}
public function testDeserializationOccursCorrectly()
{
$carbon = new Carbon('2017-06-27 13:14:15.000000');
$serialized = 'return '.var_export($carbon, true).';';
$deserialized = eval($serialized);
$this->assertInstanceOf(Carbon::class, $deserialized);
}
public function testMutableConversions()
{
$carbon = new Carbon('2017-06-27 13:14:15.123456', 'Europe/Paris');
$carbon = $carbon->locale('en_CA');
$copy = $carbon->toImmutable();
$this->assertEquals($copy, $carbon);
$this->assertNotSame($copy, $carbon);
$this->assertSame('en_CA', $copy->locale());
$this->assertInstanceOf(CarbonImmutable::class, $copy);
$this->assertTrue($copy->isImmutable());
$this->assertFalse($copy->isMutable());
$this->assertSame('2017-06-27 13:14:15.123456', $copy->format(CarbonInterface::MOCK_DATETIME_FORMAT));
$this->assertSame('Europe/Paris', $copy->tzName);
$this->assertNotSame($copy, $copy->modify('+1 day'));
$copy = $carbon->toMutable();
$this->assertEquals($copy, $carbon);
$this->assertNotSame($copy, $carbon);
$this->assertSame('en_CA', $copy->locale());
$this->assertInstanceOf(Carbon::class, $copy);
$this->assertFalse($copy->isImmutable());
$this->assertTrue($copy->isMutable());
$this->assertSame('2017-06-27 13:14:15.123456', $copy->format(CarbonInterface::MOCK_DATETIME_FORMAT));
$this->assertSame('Europe/Paris', $copy->tzName);
$this->assertSame($copy, $copy->modify('+1 day'));
}
public function testInvalidCast()
{
$this->expectExceptionObject(new InvalidArgumentException(
'DateTimeZone has not the instance() method needed to cast the date.',
));
$carbon = new Carbon('2017-06-27 13:14:15.123456', 'Europe/Paris');
$carbon->cast(DateTimeZone::class);
}
public function testChildCast()
{
$class = \get_class(new class() extends Carbon {
public function foo()
{
return 42;
}
});
$carbon = new Carbon('2017-06-27 13:14:15.123456', 'Europe/Paris');
/** @var object $casted */
$casted = $carbon->cast($class);
$this->assertInstanceOf($class, $casted);
$this->assertInstanceOf(Carbon::class, $casted);
$this->assertSame(42, $casted->foo());
$this->assertSame('2017-06-27', $casted->format('Y-m-d'));
}
public function testSiblingCast()
{
$class = \get_class(new class() extends DateTime {
public function foo()
{
return 42;
}
});
$carbon = new Carbon('2017-06-27 13:14:15.123456', 'Europe/Paris');
/** @var object $casted */
$casted = $carbon->cast($class);
$this->assertInstanceOf($class, $casted);
$this->assertInstanceOf(DateTime::class, $casted);
$this->assertSame(42, $casted->foo());
$this->assertSame('2017-06-27', $casted->format('Y-m-d'));
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/JsonSerializationTest.php | tests/Carbon/JsonSerializationTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Tests\AbstractTestCaseWithOldNow;
class JsonSerializationTest extends AbstractTestCaseWithOldNow
{
public function testCarbonAllowsCustomSerializer()
{
Carbon::serializeUsing(function (Carbon $carbon) {
return $carbon->getTimestamp();
});
$result = json_decode(json_encode(Carbon::now()), true);
$this->assertSame(1498569255, $result);
}
public function testCarbonAllowsCustomSerializerString()
{
Carbon::serializeUsing('Y-m-d');
$this->assertSame('"2017-06-27"', json_encode(Carbon::now()));
}
public function testCarbonAllowsCustomSerializerViaSettings()
{
$date = Carbon::now()->settings([
'toJsonFormat' => 'H:i:s',
]);
$this->assertSame('"13:14:15"', json_encode($date));
}
public function testCarbonCanSerializeToJson()
{
$this->assertSame('2017-06-27T13:14:15.000000Z', Carbon::now()->jsonSerialize());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/RelativeDateStringTest.php | tests/Carbon/RelativeDateStringTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Tests\AbstractTestCase;
class RelativeDateStringTest extends AbstractTestCase
{
public $scenarios = [
// ensure regular timestamps are flagged as relative
'2018-01-02 03:04:05' => ['date' => '2018-01-02', 'is_relative' => false],
'1500-01-02 12:00:00' => ['date' => '1500-01-02', 'is_relative' => false],
'1985-12-10' => ['date' => '1985-12-10', 'is_relative' => false],
'Dec 2017' => ['date' => '2017-12-01', 'is_relative' => false],
'25-Dec-2017' => ['date' => '2017-12-25', 'is_relative' => false],
'25 December 2017' => ['date' => '2017-12-25', 'is_relative' => false],
'25 Dec 2017' => ['date' => '2017-12-25', 'is_relative' => false],
'Dec 25 2017' => ['date' => '2017-12-25', 'is_relative' => false],
// dates not relative now
'first day of January 2008' => ['date' => '2008-01-01', 'is_relative' => false],
'first day of January 1999' => ['date' => '1999-01-01', 'is_relative' => false],
'last day of January 1999' => ['date' => '1999-01-31', 'is_relative' => false],
'last monday of January 1999' => ['date' => '1999-01-25', 'is_relative' => false],
'first day of January 0001' => ['date' => '0001-01-01', 'is_relative' => false],
'monday december 1750' => ['date' => '1750-12-07', 'is_relative' => false],
'december 1750' => ['date' => '1750-12-01', 'is_relative' => false],
'last sunday of January 2005' => ['date' => '2005-01-30', 'is_relative' => false],
'January 2008' => ['date' => '2008-01-01', 'is_relative' => false],
// dates relative to now
'first day of next month' => ['date' => '2017-02-01', 'is_relative' => true],
'sunday noon' => ['date' => '2017-01-01', 'is_relative' => true],
'sunday midnight' => ['date' => '2017-01-01', 'is_relative' => true],
'monday december' => ['date' => '2017-12-04', 'is_relative' => true],
'next saturday' => ['date' => '2017-01-07', 'is_relative' => true],
'april' => ['date' => '2017-04-01', 'is_relative' => true],
];
public function testKeywordMatching()
{
foreach ($this->scenarios as $string => $expected) {
$actual = Carbon::hasRelativeKeywords($string);
$this->assertSame(
$expected['is_relative'],
$actual,
"Failed relative keyword matching for scenario: {$string} (expected: {$expected['is_relative']})",
);
}
}
public function testRelativeInputStrings()
{
Carbon::setTestNow('2017-01-01 12:00:00');
foreach ($this->scenarios as $string => $expected) {
$actual = Carbon::parse($string)->format('Y-m-d');
$this->assertSame(
$expected['date'],
$actual,
"Failed relative date scenario: {$string}",
);
}
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/LastErrorTest.php | tests/Carbon/LastErrorTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\Traits\Creator;
use DateTime;
use PHPUnit\Framework\Attributes\RequiresPhp;
use Tests\AbstractTestCase;
class LastErrorTest extends AbstractTestCase
{
/**
* @var array
*/
protected $lastErrors;
/**
* @var array
*/
protected $noErrors;
protected function setUp(): void
{
parent::setUp();
$this->lastErrors = [
'warning_count' => 1,
'warnings' => ['11' => 'The parsed date was invalid'],
'error_count' => 0,
'errors' => [],
];
}
#[RequiresPhp('>=8.2')]
public function testCreateHandlesLastErrors()
{
$carbon = new Carbon('2017-02-30');
$datetime = new DateTime('2017-02-30');
$this->assertSame($this->lastErrors, $carbon->getLastErrors());
$this->assertSame($carbon->getLastErrors(), $datetime->getLastErrors());
$carbon = new Carbon('2017-02-15');
$this->assertFalse($carbon->getLastErrors());
}
public function testLastErrorsInitialization()
{
$obj = new class() {
use Creator;
/** @phpstan-ignore-next-line */
public function __construct($time = null, $tz = null)
{
}
public function triggerError()
{
self::setLastErrors([
'warning_count' => 1,
'warnings' => ['11' => 'The parsed date was invalid'],
'error_count' => 0,
'errors' => [],
]);
}
};
$this->assertFalse($obj::getLastErrors());
$obj->triggerError();
$this->assertSame($this->lastErrors, $obj::getLastErrors());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/ArraysTest.php | tests/Carbon/ArraysTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Carbon\Translator;
use Tests\AbstractTestCase;
use Tests\Carbon\Fixtures\DumpCarbon;
class ArraysTest extends AbstractTestCase
{
public function testToArray()
{
$dt = Carbon::now();
$dtToArray = $dt->toArray();
$this->assertIsArray($dtToArray);
$this->assertArrayHasKey('year', $dtToArray);
$this->assertSame($dt->year, $dtToArray['year']);
$this->assertArrayHasKey('month', $dtToArray);
$this->assertSame($dt->month, $dtToArray['month']);
$this->assertArrayHasKey('day', $dtToArray);
$this->assertSame($dt->day, $dtToArray['day']);
$this->assertArrayHasKey('dayOfWeek', $dtToArray);
$this->assertSame($dt->dayOfWeek, $dtToArray['dayOfWeek']);
$this->assertArrayHasKey('dayOfYear', $dtToArray);
$this->assertSame($dt->dayOfYear, $dtToArray['dayOfYear']);
$this->assertArrayHasKey('hour', $dtToArray);
$this->assertSame($dt->hour, $dtToArray['hour']);
$this->assertArrayHasKey('minute', $dtToArray);
$this->assertSame($dt->minute, $dtToArray['minute']);
$this->assertArrayHasKey('second', $dtToArray);
$this->assertSame($dt->second, $dtToArray['second']);
$this->assertArrayHasKey('micro', $dtToArray);
$this->assertSame($dt->micro, $dtToArray['micro']);
$this->assertArrayHasKey('timestamp', $dtToArray);
$this->assertSame($dt->timestamp, $dtToArray['timestamp']);
$this->assertArrayHasKey('timezone', $dtToArray);
$this->assertEquals($dt->timezone, $dtToArray['timezone']);
$this->assertArrayHasKey('formatted', $dtToArray);
$this->assertSame($dt->format(Carbon::DEFAULT_TO_STRING_FORMAT), $dtToArray['formatted']);
}
public function testDebugInfo()
{
$dt = Carbon::parse('2019-04-09 11:10:10.667952');
$debug = $dt->__debugInfo();
// Ignored as not in PHP 8
if (isset($debug['timezone_type'])) {
unset($debug['timezone_type']);
}
$this->assertSame([
'date' => '2019-04-09 11:10:10.667952',
'timezone' => 'America/Toronto',
], $debug);
$dt = Carbon::parse('2019-04-09 11:10:10.667952')->locale('fr_FR');
$debug = $dt->__debugInfo();
// Ignored as not in PHP 8
if (isset($debug['timezone_type'])) {
unset($debug['timezone_type']);
}
$this->assertSame([
'localTranslator' => Translator::get('fr_FR'),
'date' => '2019-04-09 11:10:10.667952',
'timezone' => 'America/Toronto',
], $debug);
}
public function testDebuggingWithFormatException()
{
$date = new DumpCarbon();
$date->breakFormat();
$this->assertIsArray($date->__debugInfo());
}
public function testDebuggingUninitializedInstances()
{
$date = new DumpCarbon();
$this->assertStringContainsString(DumpCarbon::class, $date->getDump());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/FluidSettersTest.php | tests/Carbon/FluidSettersTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Tests\AbstractTestCase;
class FluidSettersTest extends AbstractTestCase
{
public function testFluidYearSetter()
{
$d = Carbon::now();
$this->assertInstanceOfCarbon($d->year(1995));
$this->assertSame(1995, $d->year);
}
public function testFluidMonthSetter()
{
$d = Carbon::now();
$this->assertInstanceOfCarbon($d->month(3));
$this->assertSame(3, $d->month);
// Can go to september 1 to 30 (but if it's the 31, it will overflow)
$this->assertInstanceOfCarbon($d->startOfMonth()->setMonth(9));
$this->assertSame(9, $d->month);
$this->assertInstanceOfCarbon($d->months(3));
$this->assertSame(3, $d->month);
$this->assertInstanceOfCarbon($d->setMonths(9));
$this->assertSame(9, $d->month);
}
public function testFluidMonthSetterWithWrap()
{
$d = Carbon::createFromDate(2012, 8, 21);
$this->assertInstanceOfCarbon($d->month(13));
$this->assertSame(1, $d->month);
}
public function testFluidDaySetter()
{
$d = Carbon::now();
$this->assertInstanceOfCarbon($d->day(2));
$this->assertSame(2, $d->day);
}
public function testFluidDaySetterWithWrap()
{
$d = Carbon::createFromDate(2000, 1, 1);
$this->assertInstanceOfCarbon($d->day(32));
$this->assertSame(1, $d->day);
}
public function testFluidSetDate()
{
$d = Carbon::createFromDate(2000, 1, 1);
$this->assertInstanceOfCarbon($d->setDate(1995, 13, 32));
$this->assertCarbon($d, 1996, 2, 1);
}
public function testFluidHourSetter()
{
$d = Carbon::now();
$this->assertInstanceOfCarbon($d->hour(2));
$this->assertSame(2, $d->hour);
}
public function testFluidHourSetterWithWrap()
{
$d = Carbon::now();
$this->assertInstanceOfCarbon($d->hour(25));
$this->assertSame(1, $d->hour);
}
public function testFluidMinuteSetter()
{
$d = Carbon::now();
$this->assertInstanceOfCarbon($d->minute(2));
$this->assertSame(2, $d->minute);
}
public function testFluidMinuteSetterWithWrap()
{
$d = Carbon::now();
$this->assertInstanceOfCarbon($d->minute(61));
$this->assertSame(1, $d->minute);
}
public function testFluidSecondSetter()
{
$d = Carbon::now();
$this->assertInstanceOfCarbon($d->second(2));
$this->assertSame(2, $d->second);
}
public function testFluidSecondSetterWithWrap()
{
$d = Carbon::now();
$this->assertInstanceOfCarbon($d->second(62));
$this->assertSame(2, $d->second);
}
public function testFluidSetTime()
{
$d = Carbon::createFromDate(2000, 1, 1);
$this->assertInstanceOfCarbon($d->setTime(25, 61, 61));
$this->assertCarbon($d, 2000, 1, 2, 2, 2, 1);
}
public function testFluidTimestampSetter()
{
$d = Carbon::now();
$this->assertInstanceOfCarbon($d->timestamp(10));
$this->assertSame(10, $d->timestamp);
$this->assertInstanceOfCarbon($d->timestamp(1600887164.88952298));
$this->assertSame('2020-09-23 14:52:44.889523', $d->format('Y-m-d H:i:s.u'));
$this->assertInstanceOfCarbon($d->timestamp('0.88951247 1600887164'));
$this->assertSame('2020-09-23 14:52:44.889512', $d->format('Y-m-d H:i:s.u'));
$this->assertInstanceOfCarbon($d->timestamp('0.88951247/1600887164/12.56'));
$this->assertSame('2020-09-23 14:52:57.449512', $d->format('Y-m-d H:i:s.u'));
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/SettingsTest.php | tests/Carbon/SettingsTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use Tests\AbstractTestCase;
class SettingsTest extends AbstractTestCase
{
public function testSettings()
{
$paris = Carbon::parse('2018-01-31 00:00:00')->settings([
'timezone' => 'Europe/Paris',
'locale' => 'fr_FR',
'monthOverflow' => true,
'yearOverflow' => true,
]);
$this->assertEquals([
'timezone' => 'Europe/Paris',
'locale' => 'fr_FR',
'monthOverflow' => true,
'yearOverflow' => true,
], $paris->getSettings());
$saoPaulo = Carbon::parse('2018-01-31 00:00:00')->settings([
'timezone' => 'America/Sao_Paulo',
'locale' => 'pt',
'monthOverflow' => false,
'yearOverflow' => false,
]);
$this->assertEquals([
'timezone' => 'America/Sao_Paulo',
'locale' => 'pt',
'monthOverflow' => false,
'yearOverflow' => false,
], $saoPaulo->getSettings());
$this->assertSame('2 jours 1 heure avant', $paris->addMonth()->from(Carbon::parse('2018-03-05', 'UTC'), null, false, 3));
$this->assertSame('4 dias 21 horas antes', $saoPaulo->addMonth()->from(Carbon::parse('2018-03-05', 'UTC'), null, false, 3));
$this->assertSame('2 jours et une heure avant', $paris->from(Carbon::parse('2018-03-05', 'UTC'), ['parts' => 3, 'join' => true, 'aUnit' => true]));
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/SerializationTest.php | tests/Carbon/SerializationTest.php | <?php
declare(strict_types=1);
/**
* 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 Tests\Carbon;
use Carbon\Carbon;
use DateTime;
use Generator;
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\RequiresPhpExtension;
use ReflectionClass;
use ReflectionObject;
use ReflectionProperty;
use Tests\AbstractTestCase;
use Throwable;
class SerializationTest extends AbstractTestCase
{
protected string $serialized;
protected function setUp(): void
{
parent::setUp();
$this->serialized = \extension_loaded('msgpack')
? 'O:13:"Carbon\Carbon":4:{s:4:"date";s:26:"2016-02-01 13:20:25.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:15:"America/Toronto";s:18:"dumpDateProperties";a:2:{s:4:"date";s:26:"2016-02-01 13:20:25.000000";s:8:"timezone";s:15:"America/Toronto";}}'
: 'O:13:"Carbon\Carbon":3:{s:4:"date";s:26:"2016-02-01 13:20:25.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:15:"America/Toronto";}';
}
protected function cleanSerialization(string $serialization): string
{
return preg_replace('/s:\d+:\"[^"]*dumpDateProperties\"/', 's:18:"dumpDateProperties"', $serialization);
}
public function testSerialize()
{
$dt = Carbon::create(2016, 2, 1, 13, 20, 25);
$this->assertSame($this->serialized, $this->cleanSerialization($dt->serialize()));
$this->assertSame($this->serialized, $this->cleanSerialization(serialize($dt)));
}
public function testFromUnserialized()
{
$dt = Carbon::fromSerialized($this->serialized);
$this->assertCarbon($dt, 2016, 2, 1, 13, 20, 25);
$dt = unserialize($this->serialized);
$this->assertCarbon($dt, 2016, 2, 1, 13, 20, 25);
}
public function testSerialization()
{
$this->assertEquals(Carbon::now(), unserialize(serialize(Carbon::now())));
$dt = Carbon::parse('2018-07-11 18:30:11.654321', 'Europe/Paris')->locale('fr_FR');
$copy = unserialize(serialize($dt));
$this->assertSame('fr_FR', $copy->locale);
$this->assertSame('mercredi 18:30:11.654321', $copy->tz('Europe/Paris')->isoFormat('dddd HH:mm:ss.SSSSSS'));
}
public static function dataForTestFromUnserializedWithInvalidValue(): Generator
{
yield [null];
yield [true];
yield [false];
yield [123];
yield ['foobar'];
}
#[DataProvider('dataForTestFromUnserializedWithInvalidValue')]
public function testFromUnserializedWithInvalidValue(mixed $value)
{
$this->expectExceptionObject(new InvalidArgumentException(
"Invalid serialized value: $value",
));
Carbon::fromSerialized($value);
}
public function testDateSerializationReflectionCompatibility()
{
$tz = $this->firstValidTimezoneAmong(['America/Los_Angeles', 'US/Pacific'])->getName();
try {
$reflection = (new ReflectionClass(DateTime::class))->newInstanceWithoutConstructor();
@$reflection->date = '1990-01-17 10:28:07';
@$reflection->timezone_type = 3;
@$reflection->timezone = $tz;
$date = unserialize(serialize($reflection));
} catch (Throwable $exception) {
$this->markTestSkipped(
"It fails on DateTime so Carbon can't support it, error was:\n".$exception->getMessage()
);
}
$this->assertSame('1990-01-17 10:28:07', $date->format('Y-m-d h:i:s'));
$reflection = (new ReflectionClass(Carbon::class))->newInstanceWithoutConstructor();
@$reflection->date = '1990-01-17 10:28:07';
@$reflection->timezone_type = 3;
@$reflection->timezone = $tz;
$date = unserialize(serialize($reflection));
$this->assertSame('1990-01-17 10:28:07', $date->format('Y-m-d h:i:s'));
$reflection = new ReflectionObject(Carbon::parse('1990-01-17 10:28:07'));
$target = (new ReflectionClass(Carbon::class))->newInstanceWithoutConstructor();
/** @var ReflectionProperty[] $properties */
$properties = [];
foreach ($reflection->getProperties() as $property) {
$properties[$property->getName()] = $property;
}
$setValue = function ($key, $value) use (&$properties, &$target) {
if (isset($properties[$key])) {
$properties[$key]->setValue($target, $value);
return;
}
@$target->$key = $value;
};
$setValue('date', '1990-01-17 10:28:07');
$setValue('timezone_type', 3);
$setValue('timezone', $tz);
$date = unserialize(serialize($target));
$this->assertSame('1990-01-17 10:28:07', $date->format('Y-m-d h:i:s'));
}
#[RequiresPhpExtension('msgpack')]
public function testMsgPackExtension(): void
{
$string = '2018-06-01 21:25:13.321654 Europe/Vilnius';
$date = Carbon::parse('2018-06-01 21:25:13.321654 Europe/Vilnius');
$message = @msgpack_pack($date);
$copy = msgpack_unpack($message);
$this->assertSame($string, $copy->format('Y-m-d H:i:s.u e'));
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/NotLocaleAwareExceptionTest.php | tests/Carbon/Exceptions/NotLocaleAwareExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\NotLocaleAwareException;
use Generator;
use PHPUnit\Framework\Attributes\DataProvider;
use stdClass;
use Tests\AbstractTestCase;
class NotLocaleAwareExceptionTest extends AbstractTestCase
{
public static function dataForTestNotAPeriodException(): Generator
{
yield [
new stdClass(),
'stdClass does neither implements Symfony\Contracts\Translation\LocaleAwareInterface nor getLocale() method.',
];
yield [
'foo',
'string does neither implements Symfony\Contracts\Translation\LocaleAwareInterface nor getLocale() method.',
];
}
#[DataProvider('dataForTestNotAPeriodException')]
public function testNotAPeriodException(mixed $object, string $message): void
{
$exception = new NotLocaleAwareException($object);
$this->assertSame($message, $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/InvalidCastExceptionTest.php | tests/Carbon/Exceptions/InvalidCastExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\InvalidCastException;
use Tests\AbstractTestCase;
class InvalidCastExceptionTest extends AbstractTestCase
{
public function testInvalidCastException(): void
{
$exception = new InvalidCastException($message = 'message');
$this->assertSame($message, $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/ParseErrorExceptionTest.php | tests/Carbon/Exceptions/ParseErrorExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\ParseErrorException;
use Tests\AbstractTestCase;
class ParseErrorExceptionTest extends AbstractTestCase
{
public function testParseErrorException(): void
{
$exception = new ParseErrorException($expected = 'string', $actual = '');
$this->assertSame($expected, $exception->getExpected());
$this->assertSame($actual, $exception->getActual());
$this->assertSame('', $exception->getHelp());
$this->assertSame('Format expected string but data is missing', $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
public function testParseErrorExceptionWithActualAndHelp(): void
{
$exception = new ParseErrorException($expected = 'string', $actual = 'int', $help = 'help message');
$this->assertSame($expected, $exception->getExpected());
$this->assertSame($actual, $exception->getActual());
$this->assertSame($help, $exception->getHelp());
$this->assertSame("Format expected string but get 'int'\nhelp message", $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/UnknownGetterExceptionTest.php | tests/Carbon/Exceptions/UnknownGetterExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\UnknownGetterException;
use Tests\AbstractTestCase;
class UnknownGetterExceptionTest extends AbstractTestCase
{
public function testUnknownGetterException(): void
{
$exception = new UnknownGetterException($getter = 'foo');
$this->assertSame($getter, $exception->getGetter());
$this->assertSame("Unknown getter 'foo'", $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/UnknownUnitExceptionTest.php | tests/Carbon/Exceptions/UnknownUnitExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\UnknownUnitException;
use Tests\AbstractTestCase;
class UnknownUnitExceptionTest extends AbstractTestCase
{
public function testUnknownUnitException(): void
{
$exception = new UnknownUnitException($unit = 'foo');
$this->assertSame($unit, $exception->getUnit());
$this->assertSame("Unknown unit 'foo'.", $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/UnitNotConfiguredExceptionTest.php | tests/Carbon/Exceptions/UnitNotConfiguredExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\UnitNotConfiguredException;
use Tests\AbstractTestCase;
class UnitNotConfiguredExceptionTest extends AbstractTestCase
{
public function testUnitNotConfiguredException(): void
{
$exception = new UnitNotConfiguredException($unit = 'foo');
$this->assertSame($unit, $exception->getUnit());
$this->assertSame('Unit foo have no configuration to get total from other units.', $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/InvalidTimeZoneExceptionTest.php | tests/Carbon/Exceptions/InvalidTimeZoneExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\InvalidTimeZoneException;
use Tests\AbstractTestCase;
class InvalidTimeZoneExceptionTest extends AbstractTestCase
{
public function testInvalidTimeZoneException(): void
{
$exception = new InvalidTimeZoneException($message = 'message');
$this->assertSame($message, $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/BadFluentSetterExceptionTest.php | tests/Carbon/Exceptions/BadFluentSetterExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\BadFluentSetterException;
use Tests\AbstractTestCase;
class BadFluentSetterExceptionTest extends AbstractTestCase
{
public function testBadFluentSetterException(): void
{
$exception = new BadFluentSetterException($setter = 'foo');
$this->assertSame($setter, $exception->getSetter());
$this->assertSame("Unknown fluent setter 'foo'", $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/UnitExceptionTest.php | tests/Carbon/Exceptions/UnitExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\UnitException;
use Tests\AbstractTestCase;
class UnitExceptionTest extends AbstractTestCase
{
public function testUnitException(): void
{
$exception = new UnitException($message = 'message');
$this->assertSame($message, $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/ImmutableExceptionTest.php | tests/Carbon/Exceptions/ImmutableExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\ImmutableException;
use Tests\AbstractTestCase;
class ImmutableExceptionTest extends AbstractTestCase
{
public function testImmutableException(): void
{
$exception = new ImmutableException($value = 'foo');
$this->assertSame($value, $exception->getValue());
$this->assertSame('foo is immutable.', $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/BadComparisonUnitExceptionTest.php | tests/Carbon/Exceptions/BadComparisonUnitExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\BadComparisonUnitException;
use Tests\AbstractTestCase;
class BadComparisonUnitExceptionTest extends AbstractTestCase
{
public function testComparisonUnitException(): void
{
$exception = new BadComparisonUnitException($unit = 'foo');
$this->assertSame($unit, $exception->getUnit());
$this->assertSame("Bad comparison unit: 'foo'", $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/InvalidTypeExceptionTest.php | tests/Carbon/Exceptions/InvalidTypeExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\InvalidTypeException;
use Tests\AbstractTestCase;
class InvalidTypeExceptionTest extends AbstractTestCase
{
public function testInvalidTypeException(): void
{
$exception = new InvalidTypeException($message = 'message');
$this->assertSame($message, $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/UnknownMethodExceptionTest.php | tests/Carbon/Exceptions/UnknownMethodExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\UnknownMethodException;
use Tests\AbstractTestCase;
class UnknownMethodExceptionTest extends AbstractTestCase
{
public function testUnknownMethodException(): void
{
$exception = new UnknownMethodException($method = 'foo');
$this->assertSame($method, $exception->getMethod());
$this->assertSame('Method foo does not exist.', $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/InvalidDateExceptionTest.php | tests/Carbon/Exceptions/InvalidDateExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\InvalidDateException;
use Tests\AbstractTestCase;
class InvalidDateExceptionTest extends AbstractTestCase
{
public function testInvalidCastException(): void
{
$exception = new InvalidDateException('month', 13);
$this->assertSame('month', $exception->getField());
$this->assertSame(13, $exception->getValue());
$this->assertSame('month : 13 is not a valid value.', $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/UnknownSetterExceptionTest.php | tests/Carbon/Exceptions/UnknownSetterExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\UnknownSetterException;
use Tests\AbstractTestCase;
class UnknownSetterExceptionTest extends AbstractTestCase
{
public function testUnknownSetterException(): void
{
$exception = new UnknownSetterException($setter = 'foo');
$this->assertSame($setter, $exception->getSetter());
$this->assertSame("Unknown setter 'foo'", $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/NotAPeriodExceptionTest.php | tests/Carbon/Exceptions/NotAPeriodExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\NotAPeriodException;
use Tests\AbstractTestCase;
class NotAPeriodExceptionTest extends AbstractTestCase
{
public function testNotAPeriodException(): void
{
$exception = new NotAPeriodException($message = 'message');
$this->assertSame($message, $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/InvalidPeriodParameterExceptionTest.php | tests/Carbon/Exceptions/InvalidPeriodParameterExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\InvalidPeriodParameterException;
use Tests\AbstractTestCase;
class InvalidPeriodParameterExceptionTest extends AbstractTestCase
{
public function testInvalidPeriodParameterException(): void
{
$exception = new InvalidPeriodParameterException($message = 'message');
$this->assertSame($message, $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/UnreachableExceptionTest.php | tests/Carbon/Exceptions/UnreachableExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\UnreachableException;
use Tests\AbstractTestCase;
class UnreachableExceptionTest extends AbstractTestCase
{
public function testUnreachableException(): void
{
$exception = new UnreachableException($message = 'message');
$this->assertSame($message, $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/OutOfRangeExceptionTest.php | tests/Carbon/Exceptions/OutOfRangeExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\OutOfRangeException;
use Tests\AbstractTestCase;
class OutOfRangeExceptionTest extends AbstractTestCase
{
public function testOutOfRangeException(): void
{
$exception = new OutOfRangeException('month', 1, 12, -1);
$this->assertSame('month', $exception->getUnit());
$this->assertSame(1, $exception->getMin());
$this->assertSame(12, $exception->getMax());
$this->assertSame(-1, $exception->getValue());
$this->assertSame('month must be between 1 and 12, -1 given', $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
briannesbitt/Carbon | https://github.com/briannesbitt/Carbon/blob/6e037cd6239a150d74a54c62e300b269e88a89e3/tests/Carbon/Exceptions/InvalidPeriodDateExceptionTest.php | tests/Carbon/Exceptions/InvalidPeriodDateExceptionTest.php | <?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 Tests\Carbon\Exceptions;
use Carbon\Exceptions\InvalidPeriodDateException;
use Tests\AbstractTestCase;
class InvalidPeriodDateExceptionTest extends AbstractTestCase
{
public function testInvalidPeriodDateException(): void
{
$exception = new InvalidPeriodDateException($message = 'message');
$this->assertSame($message, $exception->getMessage());
$this->assertSame(0, $exception->getCode());
$this->assertNull($exception->getPrevious());
}
}
| php | MIT | 6e037cd6239a150d74a54c62e300b269e88a89e3 | 2026-01-04T15:02:34.459238Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.