将 PHP time() 输出与 MySQL 的 now() 精确匹配
Matching a PHP time() output to precisely what MySQL's now() would be
我在一个代码库中工作,遇到了一个不幸的情况。
正在向 MySQL 数据库中插入一行,其中 time
列被设置为 null
,但该列是 nn
并且默认为 NOW()
.
但是,我需要那个值。如果不使用 select 查询来提取时间,有什么方法可以 确保 PHP 函数的输出是完全相同的值?
time() === now()
总是吗?时区设置会搞砸吗?这样做的代码有什么含义?
time() 函数 PHP return 自 1970 年以来以秒为单位的时间,关于:
time in php manual
MySQL中的函数等于:UNIX_TIMESTAMP相当于:unix_timestamp from MySQL manual
因此时间()==unix_timestamp()
希望对您有所帮助! :)
几件事
Mysql now() 和 PHP time() 不一样。 PHP time()
将是数字的 unix 时间戳表示,其中 mysql now()
将采用 Y-m-d H:i:s
格式
mysql> select now();
+---------------------+
| now() |
+---------------------+
| 2015-04-14 13:15:10 |
+---------------------+
1 row in set (0.00 sec)
而在 php 中 time()
将 return 变成 1428997570
在mysql中你可以使用函数unix_timestamp()
mysql> select unix_timestamp() ;
+------------------+
| unix_timestamp() |
+------------------+
| 1428997518 |
+------------------+
最重要的部分是,如果 apache 时区和 mysql 时区不匹配,那么您可能会使用 time()
和 unix_timestamp()
获得不同的值,因此比较失败
我在一个代码库中工作,遇到了一个不幸的情况。
正在向 MySQL 数据库中插入一行,其中 time
列被设置为 null
,但该列是 nn
并且默认为 NOW()
.
但是,我需要那个值。如果不使用 select 查询来提取时间,有什么方法可以 确保 PHP 函数的输出是完全相同的值?
time() === now()
总是吗?时区设置会搞砸吗?这样做的代码有什么含义?
time() 函数 PHP return 自 1970 年以来以秒为单位的时间,关于: time in php manual
MySQL中的函数等于:UNIX_TIMESTAMP相当于:unix_timestamp from MySQL manual
因此时间()==unix_timestamp()
希望对您有所帮助! :)
几件事
Mysql now() 和 PHP time() 不一样。 PHP time()
将是数字的 unix 时间戳表示,其中 mysql now()
将采用 Y-m-d H:i:s
mysql> select now();
+---------------------+
| now() |
+---------------------+
| 2015-04-14 13:15:10 |
+---------------------+
1 row in set (0.00 sec)
而在 php 中 time()
将 return 变成 1428997570
在mysql中你可以使用函数unix_timestamp()
mysql> select unix_timestamp() ;
+------------------+
| unix_timestamp() |
+------------------+
| 1428997518 |
+------------------+
最重要的部分是,如果 apache 时区和 mysql 时区不匹配,那么您可能会使用 time()
和 unix_timestamp()
获得不同的值,因此比较失败