Is there a PHP function that returns the date and time in the same format as the MySQL function NOW()
?
I know how to do it using date()
, b
My answer is superfluous, but if you are OCD, visually oriented and you just have to see that now keyword in your code, use:
date( 'Y-m-d H:i:s', strtotime( 'now' ) );
With PHP version >= 5.4 DateTime can do this:-
echo (new \DateTime())->format('Y-m-d H:i:s');
See it working.
MySQL function NOW()
returns the current timestamp. The only way I found for PHP is using the following code.
$curr_timestamp = date('Y-m-d H:i:s');
Try this:
date("Y-m-d H:i:s");
You can use the PHP date function with the correct format as the parameter,
echo date("Y-m-d H:i:s");
I like the solution posted by user1786647, and I've updated it a little to change the timezone to a function argument and add optional support for passing either a Unix time or datetime string to use for the returned datestamp.
It also includes a fallback for "setTimestamp" for users running version lower than PHP 5.3:
function DateStamp($strDateTime = null, $strTimeZone = "Europe/London") {
$objTimeZone = new DateTimeZone($strTimeZone);
$objDateTime = new DateTime();
$objDateTime->setTimezone($objTimeZone);
if (!empty($strDateTime)) {
$fltUnixTime = (is_string($strDateTime)) ? strtotime($strDateTime) : $strDateTime;
if (method_exists($objDateTime, "setTimestamp")) {
$objDateTime->setTimestamp($fltUnixTime);
}
else {
$arrDate = getdate($fltUnixTime);
$objDateTime->setDate($arrDate['year'], $arrDate['mon'], $arrDate['mday']);
$objDateTime->setTime($arrDate['hours'], $arrDate['minutes'], $arrDate['seconds']);
}
}
return $objDateTime->format("Y-m-d H:i:s");
}