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

时间:2021-10-05 21:31:16

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) 

2 个解决方案

#1


3  

You must have a from clause in your select statement. Something like

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

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)

#2


14  

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_c fields 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)
)) 

#1


3  

You must have a from clause in your select statement. Something like

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

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)

#2


14  

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_c fields 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)
))