php7 polyfill:
<?php
function PolyfillDateTimeCreateFromInterface(DateTimeInterface $dti):DateTime{
$tz = $dti->getTimezone();
$ret = DateTime::createFromFormat(DateTimeInterface::RFC3339, $dti->format(DateTimeInterface::RFC3339));
if(!!$tz){
$ret = $ret->setTimezone($tz);
}
return $ret;
}
?>
testing it:
<?php
$dt = new DateTimeImmutable("1970-01-01",timezone_open("Europe/Oslo"));
$dti = PolyfillDateTimeCreateFromInterface($dt);
var_dump($dti->format(DateTime::RFC3339), $dti->getTimezone());
die();
?>
gives:
string(25) "1970-01-01T00:00:00+01:00"
object(DateTimeZone)#2 (2) {
["timezone_type"]=>
int(3)
["timezone"]=>
string(11) "Europe/Oslo"
}
- and warning: using the TimeZone argument of the DateTime constructor is a trap, in the example above if i used the constructor argument instead of setTimezone(), it would become "timezone_type=>1 timezone=>+01:00" instead of "timezone=>europe/oslo", the actual timezone name would be lost.