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
The PHP equivalent is time()
: http://php.net/manual/en/function.time.php
I was looking for the same answer, and I have come up with this solution for PHP 5.3 or later:
$dtz = new DateTimeZone("Europe/Madrid"); //Your timezone
$now = new DateTime(date("Y-m-d"), $dtz);
echo $now->format("Y-m-d H:i:s");
Or you can use DateTime constants:
echo date(DateTime::W3C); // 2005-08-15T15:52:01+00:00
Here's the list of them:
ATOM = "Y-m-d\TH:i:sP" ; // -> 2005-08-15T15:52:01+00:00
COOKIE = "l, d-M-Y H:i:s T" ; // -> Monday, 15-Aug-2005 15:52:01 UTC
ISO8601 = "Y-m-d\TH:i:sO" ; // -> 2005-08-15T15:52:01+0000
RFC822 = "D, d M y H:i:s O" ; // -> Mon, 15 Aug 05 15:52:01 +0000
RFC850 = "l, d-M-y H:i:s T" ; // -> Monday, 15-Aug-05 15:52:01 UTC
RFC1036 = "D, d M y H:i:s O" ; // -> Mon, 15 Aug 05 15:52:01 +0000
RFC1123 = "D, d M Y H:i:s O" ; // -> Mon, 15 Aug 2005 15:52:01 +0000
RFC2822 = "D, d M Y H:i:s O" ; // -> Mon, 15 Aug 2005 15:52:01 +0000
RFC3339 = "Y-m-d\TH:i:sP" ; // -> 2005-08-15T15:52:01+00:00 ( == ATOM)
RFC3339_EXTENDED = "Y-m-d\TH:i:s.vP" ; // -> 2005-08-15T15:52:01.000+00:00
RSS = "D, d M Y H:i:s O" ; // -> Mon, 15 Aug 2005 15:52:01 +0000
W3C = "Y-m-d\TH:i:sP" ; // -> 2005-08-15T15:52:01+00:00
For debugging I prefer a shorter one though (3v4l.org):
echo date('ymd\THisP'); // 180614T120708+02:00
There is no built-in PHP now()
function, but you can do it using date()
.
Example
function now() {
return date('Y-m-d H:i:s');
}
You can use date_default_timezone_set()
if you need to change timezone.
Otherwise you can make use of Carbon - A simple PHP API extension for DateTime.
Use strftime:
strftime("%F %T");
%F
is the same as %Y-%m-%d
.
%T
is the same as %H:%M:%S
.
Here's a demo on ideone.
If you want to get time now including AM / PM
<?php
$time_now = date("Y-m-d h:i:s a");
echo $time_now;
?>
It outputs 2020-05-01 05:45:28 pm
or
<?php
$time_now = date("Y-m-d h:i:s A");
echo $time_now;
?>
It outputs 2020-05-01 05:45:28 PM