How to check how many hours of two datetimes is between a fixed timerange

itranger :

I have the following situation:

I have the a timerange from 17h to 22h.

E.g. then I have a row with the following informations:

Starttime (datetime): 2020-03-16 13:15:00
Endtime (datetime): 2020-03-16 19:45:00

How can I get the number of hours which is between the fixed timerange (--> 2:45h)

GMB :

Assuming that start/end time do not span over days, you can use timediff(), greatest() and least():

select timediff(
    greatest(time(start_time), '17:00:00'),
    least(time(endtime), '22:00:00')
)

greatest(time(start_time), '17:00:00') gives you 17h if the (time component of) start_time is less than 17h.

least(time(endtime), '22:00:00' produces 22h if the end time is greater than 22h.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=297930&siteId=1