The DateTimeImmutable::createFromMutable() function is an inbuilt function in PHP which is used to return the new DateTimeImmutable object encapsulating the given DateTime object.
Syntax:
DateTimeImmutable DateTimeImmutable::createFromMutable( DateTime $object )
Parameters: This function accepts a single parameter $object which is used to get the mutable DateTime object that you want to convert to an immutable version.
Return values: This function returns the DateTimeImmutable object on success or false on failure.
Example 1: Below programs illustrate the DateTimeImmutable::createFromMutable() function in PHP.
<?php
$dateTime = new DateTime("2020-04-12");
var_dump(DateTimeImmutable::createFromMutable($dateTime));
?>
Output:
object(DateTimeImmutable)#2 (3) {
["date"]=>
string(26) "2020-04-12 00:00:00.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(3) "UTC"
}
Example 2:
<?php
// Creating a new DateTime::add() object
$datetime = new DateTime("2019-10-03T10:00:00");
var_dump(DateTimeImmutable::createFromMutable($datetime));
// Creating a new DateTimeImmutable() object
$datetime = new DateTime();
// Initialising year, month and day
$Year = '2019';
$Month = '10';
$Day = '03';
// Calling the DateTimeImmutable::setDate() function
$datetime = $datetime->setDate($Year, $Month, $Day);
var_dump(DateTimeImmutable::createFromMutable($datetime));
?>
Output:
object(DateTimeImmutable)#2 (3) {
["date"]=>
string(26) "2019-10-03 10:00:00.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(3) "UTC"
}
object(DateTimeImmutable)#1 (3) {
["date"]=>
string(26) "2019-10-03 20:35:03.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(3) "UTC"
}
Reference: https://www.php.net/manual/en/datetimeimmutable.createfrommutable.php