From b66970f6cbe55cdad34181eafd302f26832e1b62 Mon Sep 17 00:00:00 2001 From: Olivier Laviale Date: Sat, 2 Nov 2024 20:38:57 +0100 Subject: [PATCH] Date::from() accepts DateTimeInterface --- lib/DateTime.php | 4 ++-- tests/DateTimeTest.php | 8 ++++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/DateTime.php b/lib/DateTime.php index 16a30f1..77e1ada 100644 --- a/lib/DateTime.php +++ b/lib/DateTime.php @@ -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 { @@ -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()); } diff --git a/tests/DateTimeTest.php b/tests/DateTimeTest.php index fb0449c..fccdceb 100644 --- a/tests/DateTimeTest.php +++ b/tests/DateTimeTest.php @@ -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'))); @@ -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);