PHP Function Reference

PHP date_create() Function



The PHP date_create() function returns new DateTime object. This function is an alias of DateTime::__construct() method.

By default, this function creates an object of the current date/time.

Syntax

//Object-oriented style
public DateTime::__construct(datetime, timezone)

//Procedural style
date_create(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 DateTime 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() function.

<?php
  //datetime string
  $datetime_string = "14-Dec-2015";

  //creating a DateTime object using object-oriented style
  $date1 = new DateTime($datetime_string);

  //creating a DateTime object using procedural style
  $date2 = date_create($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 DateTime object using 
  //current time and timezone
  $date = date_create();

  //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 DateTime object
  $date = date_create($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