• PHP Video Tutorials

PHP date_create() Function



Definition and Usage

The date_create() function is an alias of the DateTime::__construct, a constructor of the DateTime class. Where, a DateTime class represents date and time in PHP. The date_create() function accepts a date time string and time zone (optional) as parameters and, creates a DateTime object accordingly.

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

Syntax

date_create([$date_time, $timezone]);

Parameters

Sr.No Parameter & Description
1

date_time (Optional)

This is the date/time string (in supported formats) for which you need to create a DateTime object.

2

timezone (Optional)

This represents the timezone of the given time.

Return Values

PHP date_create() function returns the created DateTime object.

PHP Version

This function was first introduced in PHP Version 5.2.0 and, works with all the later versions.

Example

Try out following example in here, we are creating a DateTime object, formatting it, and printing the result −

<?php
   //Date string
   $date_string = "25-09-1989";
   //Creating a DateTime object
   $date_time_Obj = date_create($date_string);
   //formatting the date to print it
   $format = date_format($date_time_Obj, "d-m-Y H:i:s");
   print($format);
?>

This will produce following result −

25-09-1989 00:00:00

Example

Following example creates date formats it as date and time separately −

<?php
   $dateString = '11-06-2012 12:50 GMT';
   $dateTime = date_create($dateString);
   print("Date: ".$dateTime->format('d-m-y')); 
   print("\n");
   print("Time: ".$dateTime->format('H:i:s')); 
?>

This will produce following result −

Date: 11-06-12
Time: 12:50:00

Example

Following example creates a DateTime object by specifying both date string and time zone −

<?php
   //Date string
   $date_string = "25-09-1989, 07:32:41 GMT";
   //Creating a DateTime object
   $tz = 'Indian/Mahe';   
   $date_time_Obj = date_create($date_string, new DateTimeZone($tz));
   //formatting the date to print it
   $format = date_format($date_time_Obj, "d-m-y H:i:s");
   print($format);
?>

This will produce following result −

Array
25-09-89 07:32:41

Example

In the following example we are invoking the date_create() function without any parameters. It creates the object of the current time −

<?php
   //Creating a DateTime object
   $date_time_Obj = date_create();
   //formatting the date to print it
   print(date_format($date_time_Obj, "d-m-y H:i:s"));
?>

This produces the following result −

04-05-20 12:41:31
php_function_reference.htm
Advertisements