How can I convert a DateTimeImmutable
object into a DateTime
object?
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());
-
7I would
new \DateTime($immutable->format(\DateTime::ATOM))
. This is neat and least data loss (timezone etc) I can imagine at the moment. Sep 26, 2017 at 14:10 -
1Note that this will discard the microseconds, which are available since PHP 7.1.– dezlovNov 28, 2017 at 17:33
-
3I guess @AdrianFöder's solution is the best. Note that you should do
new \DateTime('now', $dateTimeImmutable->getTimezone());
. It doesn't accept null as a first argument.– simPodMar 23, 2018 at 9:58 -
It does accept null. It's one of the official examples, under
Example #2 Intricacies of DateTime::__construct()
: php.net/manual/en/datetime.construct.php I think the Parameters section of this doc is wrong. The example could instead be wrong, but it's probably widely used enough that it would be better to update the spec than to disallow it. Sep 14, 2018 at 22:59
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()}");
-
4It could be done in more simple way:
$dateTime = (new DateTime())->setTimestamp($dateTimeImmutable->getTimeStamp());
– ArkemlarMar 15, 2018 at 9:54 -
3Such an expression in a string is less verbose and code analysis features typically not undestand it, so code inspection features wont work. Also it might be slower due to string expression parsing however I doubt it makes sensible difference. Btw I found better alternative:
$dateTime = new DateTime('@'.$dateTimeImmutable->getTimestamp());
– ArkemlarApr 3, 2018 at 16:07
DateTime
, you can make it require aDateTimeInterface
instead.