DateTimeImmutable::createFromMutable

(PHP 5 >= 5.6.0, PHP 7)

DateTimeImmutable::createFromMutableReturns new DateTimeImmutable object encapsulating the given DateTime object

Description

public static DateTimeImmutable DateTimeImmutable::createFromMutable ( DateTime $datetime )

Parameters

datetime

The mutable DateTime object that you want to convert to an immutable version. This object is not modified, but instead a new DateTimeImmutable object is created containing the same date time and timezone information.

Examples

Example #1 Creating an immutable date time object

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

$immutable DateTimeImmutable::createFromMutable$date );
?>

Return Values

Returns a new DateTimeImmutable instance.

add a note add a note

User Contributed Notes 2 notes

up
0
max
6 months ago
The previous example will not properly work.

<?php

DateTimeImmutable
::createFromFormat('U', $date->getTimestamp(), $date->getTimezone());

?>

will always return a DateTimeImmutable object with a GMT timezone. createFromFormat seems to prefer the format to get the timeZone instead of the passed in timeZone.

This will work, but it is clunky:

<?php

$datei
= DateTimeImmutable::createFromFormat('U', $date->getTimestamp(), $date->getTimezone());
$datei = $datei->setTimezone($date->getTimezone());

?>
up
-1
woody dot gilk at gmail dot com
6 months ago
Here's a polyfill for PHP <= 5.6:

<?php

function datetime_create_from_mutable(DateTime $date)
{
    return
DateTimeImmutable::createFromFormat(
       
'U',
       
$date->getTimestamp(),
       
$date->getTimezone()
    );
}

?>
To Top