mysql - 如何在几秒钟内获得两个时间戳之间的差异

有没有一种方法可以在 MySQL 中进行查询,以秒为单位提供两个时间戳之间的差异,或者我需要在 PHP 中执行此操作吗?如果是这样,我该怎么做?

最佳答案

您可以使用 TIMEDIFF()TIME_TO_SEC()功能如下:

SELECT TIME_TO_SEC(TIMEDIFF('2010-08-20 12:01:00', '2010-08-20 12:00:00')) diff;
+------+
| diff |
+------+
|   60 |
+------+
1 row in set (0.00 sec)

您也可以使用 UNIX_TIMESTAMP()功能为 @Amber suggested在另一个答案中:

SELECT UNIX_TIMESTAMP('2010-08-20 12:01:00') - 
       UNIX_TIMESTAMP('2010-08-20 12:00:00') diff;
+------+
| diff |
+------+
|   60 |
+------+
1 row in set (0.00 sec)

如果您使用 TIMESTAMP 数据类型,我猜 UNIX_TIMESTAMP() 解决方案会稍微快一些,因为 TIMESTAMP 值是已经存储为一个整数,表示自纪元 (Source) 以来的秒数。引用 docs :

When UNIX_TIMESTAMP() is used on a TIMESTAMP column, the function returns the internal timestamp value directly, with no implicit “string-to-Unix-timestamp” conversion.

Keep in mind that TIMEDIFF() return data type of TIME. TIME values may range from '-838:59:59' to '838:59:59' (roughly 34.96 days)

https://stackoverflow.com/questions/3528219/

相关文章:

php - PHP 内爆的 Python 等价物?

php - PDO mysql : How to know if insert was succes

javascript - 使用 ajax 请求下载文件

php - 命令不同步;你现在不能运行这个命令

php - 使用查询字符串和 anchor 标签形成正确的 URL

php - Composer : How to find the exact version of

php - 如何增加php中的执行超时?

php - 什么是 .tpl 文件? PHP,网页设计

php - 如何正确地在 PHP 中对字符串进行 URL 编码?

php - 如何修复 "Add myBundle to the asseticBundle conf