Skip to content

Commit

Permalink
Update Chronos::createFromTimestamp() to behave the same as in PHP 8.4
Browse files Browse the repository at this point in the history
  • Loading branch information
ADmad committed Jul 13, 2024
1 parent 7593c47 commit b714a0c
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 14 deletions.
15 changes: 7 additions & 8 deletions src/Chronos.php
Original file line number Diff line number Diff line change
Expand Up @@ -742,17 +742,16 @@ 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 (PHP_VERSION_ID >= 80400) {
$instance = parent::createFromTimestamp($timestamp);
if ($timezone !== null) {
$instance = $instance->setTimezone(static::safeCreateDateTimeZone($timezone));
}

if (is_int($timestamp)) {
return $instance->setTimestamp($timestamp);
return $instance;
}

return $instance->modify('@' . $timestamp);
return new static('@' . $timestamp, $timezone);
}

/**
Expand Down
11 changes: 5 additions & 6 deletions tests/TestCase/DateTime/CreateFromTimestampTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,22 +24,21 @@ 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);
}

public function testCreateFromTimestampUsesDefaultTimezone()
{
$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);
}

public function testCreateFromTimestampWithDateTimeZone()
{
$d = Chronos::createFromTimestamp(0, new DateTimeZone('UTC'));
$this->assertSame('UTC', $d->tzName);
$this->assertSame('+00:00', $d->tzName);
$this->assertDateTime($d, 1970, 1, 1, 0, 0, 0);
}

Expand All @@ -48,6 +47,6 @@ 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);
$this->assertSame('+00:00', $d->tzName);
}
}

0 comments on commit b714a0c

Please sign in to comment.