Skip to content

Commit

Permalink
Date::from() accepts DateTimeInterface
Browse files Browse the repository at this point in the history
  • Loading branch information
olvlvl committed Nov 2, 2024
1 parent 1d510d5 commit b66970f
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/DateTime.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ class DateTime extends \DateTime implements \JsonSerializable
* @throws \DateMalformedStringException
*/
static public function from(
self|\DateTime|string $source,
self|\DateTimeInterface|string $source,
DateTimeZone|string|null $timezone = null
): static
{
Expand All @@ -215,7 +215,7 @@ static public function from(
return clone $source;
}

if ($source instanceof \DateTime)
if ($source instanceof \DateTimeInterface)
{
return new static($source->format('Y-m-d\TH:i:s.u'), $source->getTimezone());
}
Expand Down
8 changes: 8 additions & 0 deletions tests/DateTimeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ public function test_none()
$this->assertTrue($d->is_empty);
}

/**
* @throws \DateInvalidTimeZoneException
* @throws \DateMalformedStringException
*/
public function test_from()
{
$d = DateTime::from(new \DateTime('2001-01-01 01:01:01', new \DateTimeZone('Europe/Paris')));
Expand All @@ -98,6 +102,10 @@ public function test_from()
$this->assertEquals('UTC', $d->zone->name);
$this->assertEquals('2001-01-01 01:01:01', $d->as_db);

$d = DateTime::from(new \DateTimeImmutable('2001-01-01 01:01:01', new \DateTimeZone('UTC')));
$this->assertEquals('UTC', $d->zone->name);
$this->assertEquals('2001-01-01 01:01:01', $d->as_db);

$d = DateTime::from(new \DateTime('2001-01-01 01:01:01', new \DateTimeZone('UTC')), new \DateTimeZone('Europe/Paris'));
$this->assertEquals('UTC', $d->zone->name);
$this->assertEquals('2001-01-01 01:01:01', $d->as_db);
Expand Down

0 comments on commit b66970f

Please # to comment.