PHP DateTimeImmutable __construct() Method
The PHP DateTimeImmutable::__construct() method returns a new DateTimeImmutable object. The date_create_immutable() function is an alias of this method.
Unlike DateTime object, this object does not allows any modifications, it creates a new object in case of changes and returns it. By default, this method creates an object of the current date/time.
Syntax
//Object-oriented style public DateTimeImmutable::__construct(datetime, timezone) //Procedural style date_create_immutable(datetime, timezone)
Parameters
datetime |
Optional. Specify a date/time string. It should be in valid Date and Time Formats. If omitted or null, indicates the current time. Default is the current time. |
timezone |
Optional. Specify a DateTimeZone object representing the timezone of datetime. If omitted or null, the current timezone will be used. Default is the current timezone.Note: The parameter and the current timezone are ignored when the datetime parameter is either a UNIX timestamp or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00). |
Return Value
Returns a new DateTimeImmutable object. Procedural style returns false on failure.
Exceptions
Emits Exception in case of an error.
Example: using both styles
The example below shows the usage of DateTimeImmutable::__construct() method.
<?php //datetime string $datetime_string = "14-Dec-2015"; //creating a DateTimeImmutable object using object-oriented style $date1 = new DateTimeImmutable($datetime_string); //creating a DateTimeImmutable object using procedural style $date2 = date_create_immutable($datetime_string); //formatting the datetime to print it echo $date1->format("Y/m/d H:i:s")."\n"; echo $date2->format("Y-m-d H:i:s")."\n"; ?>
The output of the above code will be:
2015/12/14 00:00:00 2015-12-14 00:00:00
Example: using current time and timezone
When parameters are omitted or null, it indicates the current time and timezone.
<?php //creating a DateTimeImmutable object using //current time and timezone $date = new DateTimeImmutable(); //formatting the datetime to print it echo $date->format("Y/m/d H:i:s")."\n"; //formatting date and time separately echo $date->format("Y/m/d")."\n"; echo $date->format("H:i:s")."\n"; ?>
The output of the above code will be:
2021/09/09 12:00:56 2021/09/09 12:00:56
Example: using timezone parameter
The example below describes how to use timezone parameter with this method.
<?php //datetime string $datetime_string = "14-Dec-2015, 10:45:32"; //DateTimeZone object $tz = new DateTimeZone('America/Chicago'); //creating a DateTimeImmutable object $date = new DateTimeImmutable($datetime_string, $tz); //formatting the datetime to print it echo $date->format("Y/m/d H:i:s P")."\n"; ?>
The output of the above code will be:
2015/12/14 10:45:32 -06:00
❮ PHP Date and Time Reference