MySQL 如果大于 35 天则计算日期差异

MySQL calculate date diff if greater than 35 days

如果两个日期相差大于 35 天,如何计算 datediff?

这是我的查询:

SELECT CONCAT(IF('2017-08-01 10:00:00' < NOW(), '-', ''), FLOOR(HOUR(TIMEDIFF(NOW(), '2017-08-01 10:00:00')) / 24), ' days ',
MOD(HOUR(TIMEDIFF(NOW(),'2017-08-01 10:00:00')), 24), ' hours ', MINUTE(TIMEDIFF(NOW(),'2017-08-01 10:00:00')), ' minutes') AS TimeLeft

但是显示计算错误

+------------------------------+
| TimeLeft                     |
+------------------------------+
| -34 days 22 hours 59 minutes |
+------------------------------+

应该至少相差 100 天。

https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_timediff 说:

The result returned by TIMEDIFF() is limited to the range allowed for TIME values.

https://dev.mysql.com/doc/refman/5.7/en/time.html 说:

TIME values may range from '-838:59:59' to '838:59:59'.

然后我们意识到

FLOOR(838 hours / 24 hours) = 34

这是一个可行的替代方案(至少到 2038 年):

mysql> select concat(
  ceil(tdiff/24/60/60), ' days, ',
  floor(mod(abs(tdiff)/60/60, 24)), ' hours, ',
  floor(mod(abs(tdiff)/60, 60)), ' minutes') as t
from (select unix_timestamp('2017-08-01 10:00:00') - unix_timestamp(now()) as tdiff) as t;
+---------------------------------+
| t                               |
+---------------------------------+
| -100 days, 13 hours, 10 minutes |
+---------------------------------+

这是另一个想法:

mysql> select to_days('1970-01-01')-to_days(td) as days, time(td) as hhmmss
 from (select from_unixtime(abs(unix_timestamp('2017-08-01 10:00:00') - unix_timestamp(now()))); 
+------+----------+
| days | hhmmss   |
+------+----------+
| -100 | 13:18:12 |
+------+----------+