略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: DateTime::createFromInterface

2024-12-22

DateTime::createFromInterface

(PHP 8)

DateTime::createFromInterfaceReturns new DateTime object encapsulating the given DateTimeInterface object

说明

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

参数

object

The DateTimeInterface object that needs to be converted to a mutable version. This object is not modified, but instead a new DateTime object is created containing the same date, time, and timezone information.

返回值

Returns a new DateTime instance.

范例

示例 #1 Creating a mutable date time object

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

$mutable DateTime::createFromInterface($date);

$date = new DateTime("2014-06-20 11:45 Europe/London");
$also_mutable DateTime::createFromInterface($date);
?>
add a noteadd a note

User Contributed Notes 2 notes

up
1
gabrielpl at gmail dot com
10 months ago
php7 polyfill:

<?php

// keep timezone and microseconds precision
function polyfillDateTimeCreateFromInterface(DateTimeInterface $dti): DateTime {
   
$tz = $dti->getTimezone();
    return new
DateTime($dti->format('Y-m-d H:i:s.u'), $tz ? $tz : null);
}

?>

Testing:

<?php

var_dump
(
  (
$a = new DateTimeImmutable()),
  (
$b = polyfillDateTimeCreateFromInterface($a)),
 
$a == $b
);

?>
up
-2
divinity76 at gmail dot com
11 months ago
php7 polyfill:

<?php

// php7 polyfill for php8' DateTime::createFromInterface
function PolyfillDateTimeCreateFromInterface(DateTimeInterface $dti):DateTime{
   
$tz = $dti->getTimezone();
   
$ret = DateTime::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 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.

官方地址:https://www.php.net/manual/en/datetime.createfrominterface.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3