MySQL 计算时间差

我想要显示的格式为相差X天X小时X分钟X秒
利用 TIMESTAMPDIFF() 计算两个时间相差的时间

SELECT CONCAT(
	FLOOR(TIMESTAMPDIFF(SECOND, '2019-08-12 00:14:30', '2019-09-04 08:44:53') / 86400), '天',
	TIMESTAMPDIFF(HOUR, '2019-08-12 00:14:30', '2019-09-04 08:44:53') % 24, '小时',
	TIMESTAMPDIFF(MINUTE, '2019-08-12 00:14:30', '2019-09-04 08:44:53') % 60, '分',
	TIMESTAMPDIFF(SECOND, '2019-08-12 00:14:30', '2019-09-04 08:44:53') % 60, '秒'
) SPENDTIME

结果:

23天8小时30分23秒

但是如果你知道了相差了多少秒,那么可以利用 NOW()DATE_ADD() 来进行计算

SELECT
CONCAT(
	FLOOR(TIMESTAMPDIFF(SECOND, NOW(), DATE_ADD(NOW(), INTERVAL SPENDTIME SECOND)) / 86400), '天',
	TIMESTAMPDIFF(HOUR, NOW(), DATE_ADD(NOW(), INTERVAL SPENDTIME SECOND)) % 24, '小时',
	TIMESTAMPDIFF(MINUTE, NOW(), DATE_ADD(NOW(), INTERVAL SPENDTIME SECOND)) % 60, '分',
	TIMESTAMPDIFF(SECOND, NOW(), DATE_ADD(NOW(), INTERVAL SPENDTIME SECOND)) % 60, '秒'
)
FROM (
	SELECT
	AVG(UNIX_TIMESTAMP(COMPLETE_TIME) - UNIX_TIMESTAMP(IMPLEMENT_TIME)) SPENDTIME
	FROM WKORDER_TASK_TASKINFO
) a
    原文作者:Kris Choi
    原文地址: https://blog.csdn.net/psychicsirk/article/details/100666670
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞