PHP DateTime __construct() Method
The PHP DateTime::__construct() method returns a new DateTime object. The date_create() function is an alias of this method.
By default, this method 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 DateTime::__construct() method.
<?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 $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 DateTime object using //current time and timezone $date = new DateTime(); //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 DateTime object $date = new DateTime($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