PHP 中的 NOW() 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1995562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NOW() function in PHP
提问by MoeAmine
Is there a PHP function that returns the date and time in the same format as the MySQL function NOW()?
是否有一个 PHP 函数以与 MySQL 函数相同的格式返回日期和时间NOW()?
I know how to do it using date(), but I am asking if there is a function only for this.
我知道如何使用date(),但我问是否有仅用于此的功能。
For example, to return:
例如,返回:
2009-12-01 00:00:00
回答by hsz
date('Y-m-d H:i:s')
Look here for more details: http://pl.php.net/manual/en/function.date.php
在这里查看更多详细信息:http: //pl.php.net/manual/en/function.date.php
回答by vascowhite
回答by user1786647
Use this function:
使用这个功能:
function getDatetimeNow() {
$tz_object = new DateTimeZone('Brazil/East');
//date_default_timezone_set('Brazil/East');
$datetime = new DateTime();
$datetime->setTimezone($tz_object);
return $datetime->format('Y\-m\-d\ h:i:s');
}
回答by streetparade
Try this:
尝试这个:
date("Y-m-d H:i:s");
回答by Julian
Short answer
简答
$now = date_create()->format('Y-m-d H:i:s');
Read below for the long answer.
阅读下面的长答案。
The mimicry of the MySQL NOW() function in PHP
PHP 中 MySQL NOW() 函数的模仿
Here is a list of ways in PHP that mimic the MySQL NOW()function.
这是 PHP 中模仿 MySQLNOW()函数的方法列表。
// relative date
$now = date_create('now')->format('Y-m-d H:i:s'); // works in php 5.2 and higher
$now = date_create()->format('Y-m-d H:i:s'); // also works in php 5.2
$now = new DateTime('now')->format('Y-m-d H:i:s'); // syntax error!!!
$now = (new DateTime('now'))->format('Y-m-d H:i:s'); // works in php 5.4 and higher
$now = date('Y-m-d H:i:s'); // Slightly higher performance, but less usable for date/time manipulations
// From Unix timestamp
// Using date_create() with a Unix timestamp will give you a FALSE,
// and if you try to invoke format() on a FALSE then you'll get a:
// Fatal error: Call to a member function format() on boolean
// So if you work with Unix timestamps then you could use: date_create_from_format().
$unixTimeStamp = 1420070400; // 01/01/2015 00:00:00
$y2015 = date_create_from_format('U', $unixTimeStamp, timezone_open('Europe/Amsterdam'))->format('Y-m-d H:i:s');
$y2015 = date('Y-m-d H:i:s', $unixTimeStamp);
I think that date_create()->format('Y-m-d H:i:s')is the best way because this approach allows you to handle time/time-zone manipulations easier than date('Y-m-d H:i:s')and it works since php 5.2.
我认为这date_create()->format('Y-m-d H:i:s')是最好的方法,因为这种方法使您可以比date('Y-m-d H:i:s')php 5.2更容易处理时间/时区操作,并且它可以工作。
MySQL NOW() functionMySQL NOW() 函数
The MySQL function NOW()gives the dateTime value in this format: 'YYYY-MM-DD HH:MM:SS'. See here: https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_now.
MySQL 函数NOW()以这种格式给出 dateTime 值:'YYYY-MM-DD HH:MM:SS'. 请参阅此处:https: //dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_now。
An interesting fact is that it's possible to get the datetime format by running this query: SHOW VARIABLES LIKE 'd%e_format', the result could be something like this:
一个有趣的事实是,可以通过运行此查询来获取日期时间格式:SHOW VARIABLES LIKE 'd%e_format',结果可能是这样的:
Variable_name Value
date_format %Y-%m-%d
datetime_format %Y-%m-%d %H:%i:%s
The variables up here are read-only variables. So you can't change it.
上面的变量是只读变量。所以你不能改变它。
I guess the MySQL NOW()function gets it's format from the datetime_formatvariable.
我猜 MySQLNOW()函数从datetime_format变量中获取它的格式。
The advantages of date_create()->format() instead date() summary
date_create()->format() 代替 date() 的优点总结
The favorable facts of date_create('now')->format('Y-m-d H:i:s')over date('Y-m-d H:i:s')are:
date_create('now')->format('Y-m-d H:i:s')over的有利事实date('Y-m-d H:i:s')是:
- easier to handle time manipulations
- easier to handle timezones
- o.o.p.
- 更容易处理时间操作
- 更容易处理时区
- 哎呀
The disadvantages of date_create()->format() instead date()
date_create()->format() 代替 date() 的缺点
The function date()has a slightly better performance than date_create()->format(). See benchmark test below.
该函数的date()性能略好于date_create()->format(). 请参阅下面的基准测试。
$start = time();
for ($i = 0; $i <= 5000000; $i++) {
$a = date_create('now')->format('Y-m-d H:i:s');
}
$end = time();
$elapsedTimeA = $end - $start;
echo 'Case A, elapsed time in seconds: ' . $elapsedTimeA;
echo '<br>';
$start = time();
for ($i = 0; $i <= 5000000; $i++) {
$b = date('Y-m-d H:i:s');
}
$end = time();
$elapsedTimeB = $end - $start;
echo 'Case B, elapsed time in seconds: ' . $elapsedTimeB;
echo '<br>';
// OUTPUT
Case A, elapsed time in seconds: 31
Case B, elapsed time in seconds: 14
The upper case shows that date()is faster. However, if we change the test scenario a bit, then outcome will be different. See below:
大写字母表示date()速度更快。但是,如果我们稍微改变一下测试场景,那么结果就会有所不同。见下文:
$start = time();
$dt = date_create('now');
for ($i = 0; $i <= 5000000; $i++) {
$a = $dt->format('Y-m-d H:i:s');
}
$end = time();
$elapsedTimeA = $end - $start;
echo 'Case A, elapsed time in seconds: ' . $elapsedTimeA;
echo '<br>';
$start = time();
for ($i = 0; $i <= 5000000; $i++) {
$b = date('Y-m-d H:i:s');
}
$end = time();
$elapsedTimeB = $end - $start;
echo 'Case B, elapsed time in seconds: ' . $elapsedTimeB;
echo '<br>';
// OUTPUT
Case A, elapsed time in seconds: 14
Case B, elapsed time in seconds: 15
The DateTime method: format()is faster here than date().
DateTime 方法:format()在这里比date().
The advantages of date_create()->format() instead date() detailed
date_create()->format()代替date()的优点详解
Read on for the detailed explanation.
请继续阅读以获取详细说明。
easier to handle time manipulations
更容易处理时间操作
date_create()accepts a relative date/time format (like now, yesterdayor +1 day) see this link, example:
date_create()接受相对日期/时间格式(如now,yesterday或+1 day)请参阅此链接,例如:
$tomorrow = date_create('+1 day')->format('Y-m-d H:i:s');
date()accepts a relative date/time format as well, like this:
date()也接受相对日期/时间格式,如下所示:
$tomorrow = date('Y-m-d H:i:s', strtotime('+1 day'));
$tomorrow = date('Y-m-d H:i:s', (time() + 86400)); // 86400 seconds = 1 day
easier to handle timezones
更容易处理时区
When timezones matter then the usage of date_create()->format()makes a lot more sense then date()because date()uses the default time zone which is configured in php.iniat the date.timezonedirective. Link: http://php.net/manual/en/datetime.configuration.php#ini.date.timezone.
当时区很重要时,那么使用date_create()->format()更有意义,date()因为date()使用php.ini在date.timezone指令中配置的默认时区。链接:http: //php.net/manual/en/datetime.configuration.php#ini.date.timezone。
It is possible to change the timezone during run-time. Example:
可以在运行时更改时区。例子:
date_default_timezone_set('Asia/Tokyo');.
date_default_timezone_set('Asia/Tokyo');.
The downside of that is that it will affect all date/time functions. This problem doesn't exists if you are using date_create()->format()in combination with timezone_open().
这样做的缺点是它会影响所有日期/时间函数。如果您date_create()->format()与timezone_open().
PHP supports major timezones. The funny thing is that it even supports the Arctic circle, and Antarctica. Have you ever heard about Longyearbyen? If not, then don't worry, neither did I until I read the official PHP documentation.
PHP 支持主要时区。有趣的是,它甚至支持北极圈和南极洲。你听说过Longyearbyen吗?如果没有,那么请不要担心,直到我阅读官方 PHP 文档之前我也没有。
$nowLongyearbyen = date_create('now', timezone_open('Arctic/Longyearbyen'))->format('Y-m-d H:i:s');
See a list of all supported timezones: http://php.net/manual/en/timezones.php.
查看所有支持的时区列表:http: //php.net/manual/en/timezones.php。
o.o.p.
哎呀
O.O.P. uses state-full Objects. So I prefer to think in this way:
OOP 使用全状态对象。所以我更喜欢这样思考:
// Create a DateTime Object.
// Use the DateTime that applies for tomorrow.
// Give me the datetime in format 'Y-m-d H:i:s'
$tomorrow = date_create('+1 day')->format('Y-m-d H:i:s');
Then to think in this way:
然后这样想:
// Give me a date time string in format 'Y-m-d H:i:s',
// use strtotime() to calculate the Unix timestamp that applies for tomorrow.
$tomorrow = date('Y-m-d H:i:s', strtotime('+1 day'));
Therefore I would say that the date_create()->format()approach is more readable to me then date().
因此,我会说这种date_create()->format()方法对我来说更具可读性date()。
date_create() VS new DateTime()
date_create() VS new DateTime()
The favorable facts of date_create()over new DateTime()are:
date_create()over的有利事实new DateTime()是:
- Namespaces
- 命名空间
Namespaces
命名空间
If you work in a namespace and want to initialise a DateTime object with the new keyword, then you have to do it like this:
如果您在命名空间中工作并想使用 new 关键字初始化 DateTime 对象,那么您必须这样做:
namespace my_namespace;
// The backslash must be used if you are in a namespace.
// Forgetting about the backslash results in a fatal error.
$dt = new \DateTime();
There is nothing wrong with this, but the downside of the above is that people forget sporadically about the backslash. By using the date_create()constructor function you don't have to worry about namespaces.
这没有什么错,但上面的缺点是人们偶尔会忘记反斜杠。通过使用date_create()构造函数,您不必担心命名空间。
$dt = date_create(); // in or not in a namespace it works in both situations
Example of date_create()->format()
date_create()->format() 示例
I use this approach for my projects if I have to fill an array. Like this:
如果我必须填充数组,我会在我的项目中使用这种方法。像这样:
$array = array(
'name' => 'John',
'date_time' => date_create('now')->format('Y-m-d H:i:s'), // uses the default timezone
'date_time_japan' => date_create('now', timezone_open('Asia/Tokyo'))->format('Y-m-d H:i:s'),
);
回答by santi
回答by Shriganesh Shintre
MySQL function NOW()returns the current timestamp. The only way I found for PHP is using the following code.
MySQL 函数NOW()返回当前时间戳。我为 PHP 找到的唯一方法是使用以下代码。
$curr_timestamp = date('Y-m-d H:i:s');
回答by Richard87
One more answer I find easy to use:
我发现另一个易于使用的答案:
echo date('c');
// 2015-07-27T00:00:00+02:00
This is ISO 8601 date (added in PHP 5)which MySQL uses
这是MySQL 使用的ISO 8601 日期(在 PHP 5 中添加)
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!
MySQL 5.7 默认不允许在日期时间中使用时区。您可以使用SQL_MODE=ALLOW_INVALID_DATES. 有关更多详细信息,请参阅此处的答案:https: //stackoverflow.com/a/35944059/2103434。但这也意味着保存到数据库时会丢失时区!
By default MySQL uses the system's timezone, and as long as PHP uses the same timezoneyou should be okay. In my case CET / UTC+2.
默认情况下 MySQL 使用系统的时区,只要 PHP 使用相同的时区,你应该没问题。就我而言,CET / UTC+2。
That means that if I insert 2015-07-27T00:00:00+02:00to the database, only 2015-07-27T00:00:00will be stored (but that is the correct local time!).
这意味着如果我插入2015-07-27T00:00:00+02:00到数据库中,只会2015-07-27T00:00:00被存储(但这是正确的本地时间!)。
When I load the time back in to PHP,
当我将时间加载回 PHP 时,
$importedDate = new \DateTime('2015-07-27T00:00:00')
it will automatically assume it's +02:00timezone since it's the default. Printing this will be correct again:
它会自动假定它是+02:00时区,因为它是默认的。打印这将再次正确:
echo $importedDate->format('c');
// 2015-07-27T00:00:00+02:00
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:
为安全起见,始终在服务器上使用 UTC,在 MySQL 和 PHP 中指定它,然后仅在显示日期时将其转换为用户的语言环境:
date_default_timezone_set('UTC');
$importedDate = new \DateTime('2015-07-27T00:00:00+02:00');
echo $importedDate->format('c');
// 2015-07-27T00:00:00+02:00
$importedDate->setTimezone(new \DateTimeZone("America/New_York"));
echo $importedDate->format('c');
// 2015-07-26T18:00:00-04:00

