我已经忙了好几个小时,但是我无法让它工作。
SQL
SELECT DATEDIFF(end_time, start_time) as `difference` FROM timeattendance WHERE timeattendance_id = '1484'
start_time = 2012-01-01 12:00:00
end_time = 2012-01-02 13:00:00
差异是25(小时)。但我得到的输出是1(天)。
如何获得25小时的输出?
答案 0 :(得分:77)
如何使用TIMESTAMPDIFF?
SELECT TIMESTAMPDIFF(HOUR, start_time, end_time)
as `difference` FROM timeattendance WHERE timeattendance_id = '1484'
答案 1 :(得分:7)
您最好使用TIMEDIFF而不是DATEDIFF,因为DATEDIFF会在比较之前将所有时间都转换为日期。执行TIMEDIFF后,您可以获得具有HOUR功能的小时数。
SELECT HOUR(TIMEDIFF(end_time, start_time)) as `difference`;
答案 2 :(得分:3)
正如MySQL reference中所述,DATEDIFF
只需要几天的时间。
如果两个日期都在1970年之后,您可以减去时间戳:
SELECT ( UNIX_TIMESTAMP("2012-01-02 13:00:00") -
UNIX_TIMESTAMP("2012-01-01 12:00:00") ) / 3600 ...
或:
SELECT TIMEDIFF ( "2012-01-02 13:00:00", "2012-01-01 12:00:00") / 3600 ...
答案 3 :(得分:3)
您可以使用TIMEDIFF和HOUR功能来提取小时。
SELECT HOUR(TIMEDIFF(end_time, start_time)) as `difference` FROM timeattendance WHERE timeattendance_id = '1484'
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timediff
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_hour