From e89692af28eab3c7829a9d5fc855bd03ae2cfd68 Mon Sep 17 00:00:00 2001 From: kylekatarnls Date: Wed, 1 May 2024 08:43:08 +0200 Subject: [PATCH] Fallback to default timezone for mocked now --- src/Carbon/Traits/Test.php | 4 ++-- tests/Carbon/TestingAidsTest.php | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/Carbon/Traits/Test.php b/src/Carbon/Traits/Test.php index 8290032c9..c642dbdbf 100644 --- a/src/Carbon/Traits/Test.php +++ b/src/Carbon/Traits/Test.php @@ -148,8 +148,8 @@ private function mockConstructorParameters(&$time, ?CarbonTimeZone $timezone): v return; } - if ($timezone) { - $testInstance = $testInstance->setTimezone($timezone); + if ($testInstance instanceof DateTimeInterface) { + $testInstance = $testInstance->setTimezone($timezone ?? date_default_timezone_get()); } if (static::hasRelativeKeywords($time)) { diff --git a/tests/Carbon/TestingAidsTest.php b/tests/Carbon/TestingAidsTest.php index 3e3a92fb7..29d04bec6 100644 --- a/tests/Carbon/TestingAidsTest.php +++ b/tests/Carbon/TestingAidsTest.php @@ -391,6 +391,23 @@ public function modify($modify) $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');