I'm Trying to get the timediff from my table and convert it to hours (it's for an hourly billed service)
SELECT TIME_TO_SEC(TIMEDIFF(endDate,startDate))/3600 FROM tasks >
where endDate and startDate are in datetime format
is there another way (more efficient) to do this task? Thanks !
The TIMEDIFF() function returns the difference between two time/datetime expressions. Note: time1 and time2 should be in the same format, and the calculation is time1 - time2.
mysql> SELECT t1, -> TIME_TO_SEC(t1) AS 'seconds', -> TIME_TO_SEC(t1)/60 AS 'minutes', -> TIME_TO_SEC(t1)/(60*60) AS 'hours', -> TIME_TO_SEC(t1)/(24*60*60) AS 'days' -> FROM time_val; +----------+---------+---------+-------+------+ | t1 | seconds | minutes | hours | days | +----------+---------+---------+-------+------ ...
To compute the total elapsed time, use TIME_TO_SEC( ) to convert the values to seconds before summing them. : TIME_TO_SEC « Date Time « SQL / MySQL. To compute the total elapsed time, use TIME_TO_SEC( ) to convert the values to seconds before summing them.
MySQL CURRENT_TIMESTAMP() Function The CURRENT_TIMESTAMP() function returns the current date and time. Note: The date and time is returned as "YYYY-MM-DD HH-MM-SS" (string) or as YYYYMMDDHHMMSS.
TIMEDIFF(endDate, startDate)
outputs in DateTime format, so flat that to timestamp and devide by (60*60)
SELECT (UNIX_TIMESTAMP(TIMEDIFF(endDate, startDate))/(60*60)) AS hours_difference FROM tasks
Edit: Alternatively,TimestampDiff may also provide a valid solution in more elegant way providing its example:
SELECT TIMESTAMPDIFF(MONTH,'2003-02-01','2003-05-01');
And your solution can be:
SELECT TIMESTAMPDIFF(HOUR, startDate, endDate) AS hours_different FROM tasks
NOTE the most voted up answer in this chain is INCORRECT! Using HOUR will only return hours as an integer. Below would correct the most popular answer to return hours as an integer and minutes as a decimal (ie 6.5 hours).
TIME_TO_SEC(TIMEDIFF(endDate, startDate))/3600 as hours
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With