DateTimeImmutable::createFromInterface

(PHP 8)

DateTimeImmutable::createFromInterfaceRetorna um novo objeto DateTimeImmutable encapsulando o objeto DateTimeInterface informado

Descrição

public static DateTimeImmutable::createFromInterface(DateTimeInterface $object): DateTimeImmutable

Parâmetros

object

O objeto DateTimeInterface que necessita ser convertido para uma versão mutável. Este objeto não é modificado, em vez disso uma nova instância DateTimeImmutable é criada contendo as mesmas informações de data, horário e fuso.

Valor Retornado

Retorna uma nova instância de DateTimeImmutable.

Exemplos

Exemplo #1 Criando um objeto de data/hora imutável

<?php
$date
= new DateTime("2014-06-20 11:45 Europe/London");

$immutable = DateTimeImmutable::createFromInterface($date);

$date = new DateTimeImmutable("2014-06-20 11:45 Europe/London");
$also_immutable = DateTimeImmutable::createFromInterface($date);
?>

add a note add a note

User Contributed Notes 1 note

up
0
divinity76 at gmail dot com
2 years ago
php7 polyfill:
<?php
function PolyfillDateTimeImmutableCreateFromInterface(DateTimeInterface $dti):DateTimeImmutable{
   
$tz = $dti->getTimezone();
   
$ret = DateTimeImmutable::createFromFormat(DateTimeInterface::RFC3339, $dti->format(DateTimeInterface::RFC3339));
    if(!!
$tz){
       
// without this: timezone +01:00
        // with this: timezone Europe/Oslo
       
$ret = $ret->setTimezone($tz);
    }
    return
$ret;
}

?>

testing it:
<?php
$dt
= new DateTime("1970-01-01",timezone_open("Europe/Oslo"));
$dti = PolyfillDateTimeImmutableCreateFromInterface($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 DateTimeImmutable 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 timezone name would be lost.
To Top