Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions lib/DateTimeImmutable.php
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,16 @@ public static function createFromMutable($dateTime): self
return self::createFromRegular($date);
}

public static function createFromInterface(\DateTimeInterface $object): self
{
if ($object instanceof \DateTime) {
$object = self::createFromMutable($object);
} elseif ($object instanceof DateTimeImmutable) {
$object = $object->getInnerDateTime();
}
return self::createFromRegular($object);
}

/**
* @param mixed[] $array
* @return DateTimeImmutable
Expand Down
20 changes: 20 additions & 0 deletions tests/DateTimeImmutableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,24 @@ public function testCreateFromMutable(): void

self::assertSame($safeDate->format(\DateTimeInterface::ATOM), $safeImmutableDate->format(\DateTimeInterface::ATOM));
}

/**
* @dataProvider createFromInterfaces
*/
public function testCreateFromInterface(\DateTimeInterface $dateTime): void
{
$safeImmutableDate = \Safe\DateTimeImmutable::createFromInterface($dateTime);

self::assertSame($dateTime->format(\DATE_ATOM), $safeImmutableDate->format(\DATE_ATOM));
}

public function createFromInterfaces(): array
{
return [
[new \DateTime('2022-11-29T14:17:34+00:00')],
[new \Safe\DateTime('2022-11-29T14:17:34+00:00')],
[new \DateTimeImmutable('2022-11-29T14:17:34+00:00')],
[new \Safe\DateTimeImmutable('2022-11-29T14:17:34+00:00')],
];
}
}