简体   繁体   中英

How to compare if the time between two dates is between two other dates?

I want to compare if the time between $begin and $end is between starttime and endtime.

My table has the following layout:

id - name - starttime(in datetime) - endtime (in datetime)

Example entry in the table:

32 - test - 25.03.2019-5:00pm - 25.03.2019-6:15pm

Example:

$begin: 4:45pm
$end: 6:30pm

This example should give me the entry with the id 32 because the timeblock between $begin and $end is already in my table!

SELECT * FROM timetable WHERE FROM_UNIXTIME($begin) BETWEEN starttime AND endtime OR FROM_UNIXTIME($end) BETWEEN starttime AND endtime 

As you said in the comments, you have begin and end values in UNIX_TIMESTAMP so here is a query to check get the desired output:

Try this:

SELECT * 
FROM timetable 
WHERE $begin >= UNIX_TIMESTAMP(`starttime`)
AND $end <= UNIX_TIMESTAMP(`endtime`) 
AND $begin < $end

How it works:

$begin >= UNIX_TIMESTAMP(`starttime`)

It checks if begin time is greater than or equal to starttime saved in the database.

$end <= UNIX_TIMESTAMP(`endtime`) 

It checks if end time is less than or equal to endtime saved in the database.

$begin < $end

It checks if endtime is greater than start time.

Hope this helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM