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 14, 2024
1 parent 7593c47 commit ccfccdc
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 19 deletions.
12 changes: 2 additions & 10 deletions src/Chronos.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down
20 changes: 11 additions & 9 deletions tests/TestCase/DateTime/CreateFromTimestampTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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);
}
}

0 comments on commit ccfccdc

Please sign in to comment.