From ccfccdc9203474e7de07d2aedaab4d459a73db67 Mon Sep 17 00:00:00 2001 From: ADmad Date: Sat, 13 Jul 2024 22:06:10 +0530 Subject: [PATCH] Update Chronos::createFromTimestamp() to behave the same as in PHP 8.4 --- src/Chronos.php | 12 ++--------- .../DateTime/CreateFromTimestampTest.php | 20 ++++++++++--------- 2 files changed, 13 insertions(+), 19 deletions(-) diff --git a/src/Chronos.php b/src/Chronos.php index b46391d0..73dbbdf9 100644 --- a/src/Chronos.php +++ b/src/Chronos.php @@ -742,17 +742,9 @@ public static function createFromArray(array $values): static */ public static function createFromTimestamp(float|int $timestamp, DateTimeZone|string|null $timezone = null): static { - if (PHP_VERSION_ID >= 80400 && $timezone === null) { - return parent::createFromTimestamp($timestamp); - } - - $instance = static::now($timezone); - - if (is_int($timestamp)) { - return $instance->setTimestamp($timestamp); - } + $instance = PHP_VERSION_ID >= 80400 ? parent::createFromTimestamp($timestamp) : new static('@' . $timestamp); - return $instance->modify('@' . $timestamp); + return $timezone ? $instance->setTimezone($timezone) : $instance; } /** diff --git a/tests/TestCase/DateTime/CreateFromTimestampTest.php b/tests/TestCase/DateTime/CreateFromTimestampTest.php index 28da3e3a..96dc6261 100644 --- a/tests/TestCase/DateTime/CreateFromTimestampTest.php +++ b/tests/TestCase/DateTime/CreateFromTimestampTest.php @@ -24,16 +24,17 @@ class CreateFromTimestampTest extends TestCase public function testCreateReturnsDatingInstance() { $d = Chronos::createFromTimestamp(Chronos::create(1975, 5, 21, 22, 32, 5)->timestamp); - $this->assertDateTime($d, 1975, 5, 21, 22, 32, 5); + $this->assertDateTime($d, 1975, 5, 22, 2, 32, 5); + $this->assertSame('+00:00', $d->tzName); } - public function testCreateFromTimestampUsesDefaultTimezone() + public function testCreateFromTimestampUsesUTC() { $d = Chronos::createFromTimestamp(0); - // We know Toronto is -5 since no DST in Jan - $this->assertSame(1969, $d->year); - $this->assertSame(-5 * 3600, $d->offset); + $this->assertSame(1970, $d->year); + $this->assertSame(0, $d->offset); + $this->assertSame('+00:00', $d->tzName); } public function testCreateFromTimestampWithDateTimeZone() @@ -45,9 +46,10 @@ public function testCreateFromTimestampWithDateTimeZone() public function testCreateFromTimestampWithString() { - $d = Chronos::createFromTimestamp(0, 'UTC'); - $this->assertDateTime($d, 1970, 1, 1, 0, 0, 0); - $this->assertSame(0, $d->offset); - $this->assertSame('UTC', $d->tzName); + $d = Chronos::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); + $this->assertSame('America/Toronto', $d->tzName); } }