转换 \日期时间不可变为 \日期时间

2022-08-30 19:49:46

如何将 DateTimeImmutable 对象转换为 DateTime 对象?


答案 1

PHP 中有一个对方法的拉取请求。它已被整合(12),只是为了以后无缘无故地被删除。现在它似乎又回来了,但仅适用于PHP 7.3及更高版本。DateTime::createFromImmutable()

所以这可能是现在最简单的方法:

$dateTime = new \DateTime();
$dateTime->setTimestamp($dateTimeImmutable->getTimestamp());

如果您需要包含时区信息:

$dateTime = new \DateTime(null, $dateTimeImmutable->getTimezone());
$dateTime->setTimestamp($dateTimeImmutable->getTimestamp());

答案 2

要使用正确的时区进行转换:

对于 PHP >= 7.3

DateTime::createFromImmutable(dateTimeImmutable);

对于 PHP <= 7.2

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

推荐