Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert \DateTimeImmutable to \DateTime

Tags:

php

datetime

How can I convert a DateTimeImmutable object into a DateTime object?

like image 981
Thomas Landauer Avatar asked Jan 23 '17 17:01

Thomas Landauer


3 Answers

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());
like image 100
Thomas Landauer Avatar answered Nov 12 '22 02:11

Thomas Landauer


To convert with proper timezone:

For PHP >= 7.3

DateTime::createFromImmutable(dateTimeImmutable);

For PHP <= 7.2

DateTime::createFromFormat(
   DateTimeInterface::ATOM, 
   $dateTimeImmutable->format(DateTimeInterface::ATOM)
);
like image 39
paq85 Avatar answered Nov 12 '22 02:11

paq85


You can do this as a one-liner:

$dateTime = new DateTime("@{$dateTimeImmutable->getTimeStamp()}");
like image 2
Tijmen Avatar answered Nov 12 '22 02:11

Tijmen