MySQL 如何获得两个日期之间的时差(以小时为单位)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10926739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 13:42:55  来源:igfitidea点击:

How to get time difference (in hours) between 2 dates

mysqlsqloracle

提问by Ofer

I am trying to get the time difference between 2 users, I need the difference in hours.

我正在尝试获取 2 个用户之间的时差,我需要以小时为单位的时差。

I tried to use DATEDIFF function but it's wrong.

我尝试使用 DATEDIFF 函数,但它是错误的。

Here is my code:

这是我的代码:

SELECT DATEDIFF(*,  
(SELECT max(u1.time_c)
FROM users u)
,
(SELECT max(u2.time_c)
FROM users u2) 

采纳答案by Florin Ghita

You must have a fromclause in your select statement. Something like

from的 select 语句中必须有一个子句。就像是

Select date1 - date2 from dual

returns number of days between date1 and date2.

返回 date1 和 date2 之间的天数。

If you want number of hours:

如果你想要小时数:

Select (date1 - date2)*24 from dual;

(this is only for oracle)

(这仅适用于oracle)

回答by Matt Dodge

From MySQL DATEDIFF docs:

来自MySQL DATEDIFF 文档

Only the date parts of the values are used in the calculation.

You will want to look at TIMEDIFF

你会想看看 TIMEDIFF

This will give you the number of hours in the difference in times (assuming your time_cfields are DATETIME or something similar)

这将为您提供时间差异的小时数(假设您的time_c字段是 DATETIME 或类似的内容)

SELECT HOUR(TIMEDIFF(  
  (SELECT max(u1.time_c) FROM users u),
  (SELECT max(u2.time_c) FROM users u2)
))