如果差异大于35天,如何计算两个日期之间的约会?
这是我的疑问:
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天的差异。
答案 0 :(得分:1)
https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_timediff说:
TIMEDIFF()返回的结果仅限于TIME值允许的范围。
https://dev.mysql.com/doc/refman/5.7/en/time.html说:
TIME值的范围可以是&#39; -838:59:59&#39;到&#39; 838:59:59&#39;
然后我们意识到
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 |
+------+----------+