26

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

1
  • 5
    If you want to do this because a method you wrote requires a DateTime, you can make it require a DateTimeInterface instead.
    – user276648
    May 18, 2018 at 15:39

3 Answers 3

29

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());
4
  • 7
    I 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
  • 1
    Note that this will discard the microseconds, which are available since PHP 7.1.
    – dezlov
    Nov 28, 2017 at 17:33
  • 3
    I 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.
    – simPod
    Mar 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
17

To convert with proper timezone:

For PHP >= 7.3

DateTime::createFromImmutable(dateTimeImmutable);

For PHP <= 7.2

DateTime::createFromFormat(
   DateTimeInterface::ATOM, 
   $dateTimeImmutable->format(DateTimeInterface::ATOM)
);
2

You can do this as a one-liner:

$dateTime = new DateTime("@{$dateTimeImmutable->getTimeStamp()}");
2
  • 4
    It could be done in more simple way: $dateTime = (new DateTime())->setTimestamp($dateTimeImmutable->getTimeStamp());
    – Arkemlar
    Mar 15, 2018 at 9:54
  • 3
    Such 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());
    – Arkemlar
    Apr 3, 2018 at 16:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.