Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql timediff to hours

Tags:

php

mysql

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 !

like image 499
momo Avatar asked Feb 01 '10 00:02

momo


People also ask

How do I get the time difference between hours in MySQL?

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.

How do I convert hours to minutes in MySQL?

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 | +----------+---------+---------+-------+------ ...

How does MySQL calculate elapsed time?

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.

What is current timestamp in MySQL?

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.


2 Answers

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 
like image 171
Trav L Avatar answered Sep 20 '22 22:09

Trav L


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 
like image 43
Funk Doc Avatar answered Sep 17 '22 22:09

Funk Doc