This article demonstrates how to get the current date and time in PHP.

1. Using date() function

The date() function takes the format and the Unix timestamp, and returns the date corresponding to the timestamp according to the given format. To get the current time in seconds since the Unix epoch, you can use the time() function.

Download  Run Code

 
Note that the timestamp is optional in the date() function, and it defaults to the timestamp returned by time(). That means you can get the current time in the specified format even if no timestamp is provided.

Download  Run Code

 
You might want to set the default timezone before invoking the date() or time() functions in your script using the date_default_timezone_set() function. Once set, this timezone will be used by all date/time functions within the script. To retrieve the default timezone set using date_default_timezone_set(), you can use the date_default_timezone_get() function.

Download  Run Code

2. Using DateTime class

The DateTime class provides representations of date and time in PHP. An empty DateTime constructor returns a new instance of DateTime initialzed with the current time using the current timezone. To get the date according to the given format, call the DateTime::format() function.

Download  Run Code

 
You may also access a class member on the same line as instantiating the class. This feature is called class member instantiation and is used below for briefly accessing the format() function of the DateTime class.

Download  Run Code

 
You can use the DateTimeZone class to set the time zone for the DateTime object. The following solution gets the current time in 'Europe/London' time zone using DateTime constructor. Note the use of the format "now" to obtain the current time. Alternatively, the DateTime::setTimezone() function can also be used to set the time zone later.

Download  Run Code

That’s all there is to getting the current date and time in PHP.