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()
, but I am asking if there is a function only for this.
For example, to return:
2009-12-01 00:00:00
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()
, but I am asking if there is a function only for this.
For example, to return:
2009-12-01 00:00:00
Not besides:
With PHP version >= 5.4 DateTime can do this:-
See it working.
Or you can use
DateTime
constants:Here's the list of them:
For debugging I prefer a shorter one though (3v4l.org):
Use this function:
One more answer I find easy to use:
This is ISO 8601 date (added in PHP 5) which MySQL uses
Edit
MySQL 5.7 do not allow timezone in the datetime by default. You can disable the error with
SQL_MODE=ALLOW_INVALID_DATES
. See the answer here for more details: https://stackoverflow.com/a/35944059/2103434. But that also means that the timezone will be lost when saving to the database!By default MySQL uses the system's timezone, and as long as PHP uses the same timezone you should be okay. In my case CET / UTC+2.
That means that if I insert
2015-07-27T00:00:00+02:00
to the database, only2015-07-27T00:00:00
will be stored (but that is the correct local time!).When I load the time back in to PHP,
it will automatically assume it's
+02:00
timezone since it's the default. Printing this will be correct again:To be safe, always use UTC on the server, specify it in MySQL and PHP, and then only convert it to your user's locale when displaying the date:
Look here for more details: http://pl.php.net/manual/en/function.date.php