PHP Function Reference

PHP date_create_immutable() Function



The PHP date_create_immutable() function returns new DateTimeImmutable object. This function is an alias of DateTimeImmutable::__construct() 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 function 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 date_create_immutable() function.

<?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 date_format($date1, "Y/m/d H:i:s")."\n";
  echo date_format($date2, "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 = date_create_immutable();

  //formatting the datetime to print it
  echo date_format($date, "Y/m/d H:i:s")."\n";

  //formatting date and time separately
  echo date_format($date, "Y/m/d")."\n";
  echo date_format($date, "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 function.

<?php
  //datetime string
  $datetime_string = "14-Dec-2015, 10:45:32";

  //DateTimeZone object
  $tz = new DateTimeZone('America/Chicago');

  //creating a DateTimeImmutable object
  $date = date_create_immutable($datetime_string, $tz);

  //formatting the datetime to print it
  echo date_format($date, "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