The DateTime::createFromImmutable Method

The static method createFromImmutable of the DateTime class creates a new mutable DateTime object based on an immutable DateTimeImmutable object.

Syntax

phpDateTime::createFromImmutable(DateTimeImmutable $object): DateTime

Example

Let's create a mutable DateTime object from an immutable one:

php<?php
  $immutable = new DateTimeImmutable('2023-07-15');
  $mutable = DateTime::createFromImmutable($immutable);
  echo $mutable->format('Y-m-d');
?>

Code execution result:

php'2023-07-15'

Example

Let's demonstrate the difference between mutable and immutable objects:

php<?php
  $immutable = new DateTimeImmutable('2023-07-15');
  $mutable = DateTime::createFromImmutable($immutable);
  
  $mutable->modify('+1 day');
  $newImmutable = $immutable->modify('+1 day');
  
  echo $mutable->format('Y-m-d') . "\n";
  echo $newImmutable->format('Y-m-d');
?>

Code execution result:

php'2023-07-16'
'2023-07-16'

Example

Creating a mutable object with a time zone:

php<?php
  $timezone = new DateTimeZone('Europe/Moscow');
  $immutable = new DateTimeImmutable('now', $timezone);
  $mutable = DateTime::createFromImmutable($immutable);
  echo $mutable->format('Y-m-d H:i:s e');
?>

Code execution result:

php'2023-07-15 14:30:00 Europe/Moscow'

See Also