Calculating time difference before 6am and after 10pm in MySQL

别等时光非礼了梦想. 提交于 2019-12-11 19:19:46

问题


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.


回答1:


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"



来源:https://stackoverflow.com/questions/22345607/calculating-time-difference-before-6am-and-after-10pm-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!