Get current date and time in PHP
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.
|
1 2 3 4 |
<?php $date = date('Y/m/d h:i:s a', time()); echo $date; ?> |
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.
|
1 2 3 4 |
<?php $date = date('Y/m/d h:i:s a'); echo $date; ?> |
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.
|
1 2 3 4 5 6 7 8 |
<?php date_default_timezone_set('Europe/London'); $date = date('Y/m/d h:i:s a', time()); $timezone = date_default_timezone_get(); echo $date . ' ' . $timezone; ?> |
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.
|
1 2 3 4 |
<?php $today = new DateTime(); echo $today->format('Y/m/d h:i:s a'); ?> |
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.
|
1 2 3 |
<?php echo (new DateTime)->format('Y/m/d h:i:s a'); ?> |
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.
|
1 2 3 4 |
<?php $today = new DateTime("now", new DateTimeZone('Europe/London')); echo $today->format('Y/m/d h:i:s a'); ?> |
That’s all there is to getting the current date and time in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)