简体   繁体   中英

how to find the total numbers of hours of 2 dates in mysql query

i have this table called records:

+---------------------+---------------------+
| date_returned       | date_borrowed       |
+---------------------+---------------------+
| 2013-05-31 09:27:38 | 2013-05-31 08:48:14 |
| 2013-05-31 09:22:27 | 2013-05-31 08:53:06 |
| 2013-05-31 09:27:38 | 2013-05-31 09:22:35 |
| 2013-05-31 15:27:02 | 2013-05-31 09:22:39 |
| 2013-05-31 15:27:02 | 2013-05-31 10:04:22 |
+---------------------+---------------------+

i want to include the total hours as another column in the result. i read the manual but datediff seemed to be vague and just returns the difference as days.

Try:

SELECT 
    TIMEDIFF(date_borrowed, date_returned) AS diff
FROM
    tablename
SELECT 
    HOUR(TIMEDIFF(date_borrowed, date_returned)) as TotalHours
FROM
    tablename

How about converting to timestamp values - that'll let you subtract to get the difference in seconds, and you can manipulate as much as you want from there.

SELECT
    date_returned,
    date_borrowed,
    (UNIX_TIMESTAMP(date_returned) - UNIX_TIMESTAMP(date_borrowed)) / 3600 AS hours
FROM tablename

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM