Question

I have one question regarding MySQL date / time functions. For now, I have query which looks like this:

SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(sum)))
FROM workingtime
WHERE user='magdalena'
AND type='work'
AND start BETWEEN '2014-03-01' AND '2014-03-12'
AND completed=1

So in my database there are 2 columns with timestamps, first one is "start", second one is "end". What I would like to execute in sigle query is this: I would like to have returned how much is the time difference between start and 6am + how much is the time difference between 10pm and end (with option for nex day...). I need this for night shift hours - so I need sum of nightshift hours together as a result.

Example:

start = 2014-02-26 03:30:00

end = 2014-02-26 12:16:59

I would like to get difference between start and 6am and 10pm and end. In this case: difference between 3:30:00 and 6:00:00 is 2:30:00. Difference between 10pm and end is nothing in this case, because end time is not over 10pm at all. So the result in this case will be 2:50:00. That is the output I would like to get.

Is this possible only with MySQL? Thank you guys, I appreciate it.

Was it helpful?

Solution

Use can use the TIMEDIFF function, like this:

select 
  CONCAT(HOUR(TIMEDIFF(starttime, CONCAT(DATE(starttime),' 06:00:00'))), ':', MINUTE(TIMEDIFF(starttime, CONCAT(DATE(starttime),' 06:00:00')))) AS startdiff,
  CONCAT(HOUR(TIMEDIFF(CONCAT(DATE(endtime),' 22:00:00'), endtime)), ':', MINUTE(TIMEDIFF(CONCAT(DATE(endtime),' 22:00:00'), endtime))) AS enddiff
from workingtime

Working demo: http://sqlfiddle.com/#!2/fc621/1

I was not able to understand the following part of your question: "with option for next day"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top