Which PHP function can return the current date/time?
date(format, timestamp)
The date
function returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp
is optional and defaults to the value of time().
And the parameters are -
format - Required. Specifies the format of the timestamp
timestamp - (Optional) Specifies a timestamp. Default is the current date and time
The required format parameter of the date()
function specifies how to format the date (or time)
.
Here are some characters that are commonly used for dates:
Other characters, like "/", ".", or "-"
can also be inserted between the characters to add additional formatting.
The example below formats today's date in three different ways:
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
// Simply:
$date = date('Y-m-d H:i:s');
// Or:
$date = date('Y/m/d H:i:s');
// This would return the date in the following formats respectively:
$date = '2012-03-06 17:33:07';
// Or
$date = '2012/03/06 17:33:07';
/**
* This time is based on the default server time zone.
* If you want the date in a different time zone,
* say if you come from Nairobi, Kenya like I do, you can set
* the time zone to Nairobi as shown below.
*/
date_default_timezone_set('Africa/Nairobi');
// Then call the date functions
$date = date('Y-m-d H:i:s');
// Or
$date = date('Y/m/d H:i:s');
// date_default_timezone_set() function is however
// supported by PHP version 5.1.0 or above.
For a time-zone reference, see List of Supported Timezones.
According to the article How to Get Current Datetime (NOW) with PHP, there are two common ways to get the current date. To get current datetime (now) with PHP, you can use the date
class with any PHP version, or better the datetime
class with PHP >= 5.2.
Various date format expressions are available here.
This expression will return NOW in format Y-m-d H:i:s
.
<?php
echo date('Y-m-d H:i:s');
?>
This expression will return NOW in format Y-m-d H:i:s
.
<?php
$dt = new DateTime();
echo $dt->format('Y-m-d H:i:s');
?>
echo date('y-m-d'); // Today
This will return today's date.
You can either use the $_SERVER['REQUEST_TIME'] variable (available since PHP 5.1.0) or the time() function to get the current Unix timestamp.
You can use this code:
<?php
$currentDateTime = date('Y-m-d H:i:s');
echo $currentDateTime;
?>