How can I convert a DateTimeImmutable
object into a DateTime
object?
There is a pull request for a DateTime::createFromImmutable()
method in PHP. It had been integrated (1, 2), just to be removed later for no reason. Now it seems to be back in, but only for PHP 7.3 and higher.
So this is probably the easiest way right now:
$dateTime = new \DateTime();
$dateTime->setTimestamp($dateTimeImmutable->getTimestamp());
If you need to include timezone information:
$dateTime = new \DateTime(null, $dateTimeImmutable->getTimezone());
$dateTime->setTimestamp($dateTimeImmutable->getTimestamp());
To convert with proper timezone:
For PHP >= 7.3
DateTime::createFromImmutable(dateTimeImmutable);
For PHP <= 7.2
DateTime::createFromFormat(
DateTimeInterface::ATOM,
$dateTimeImmutable->format(DateTimeInterface::ATOM)
);
You can do this as a one-liner:
$dateTime = new DateTime("@{$dateTimeImmutable->getTimeStamp()}");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With