The problem is organizing logic (which is simple).
Basically for one time not to coincide with another, you need only two conditions:
If you want to get Non coincident hours - "free" are just these two:
- Event start date A greater (or equal to) than the end of event B
OR
- Event end date A less (or equal to) than event start B
Which in PHP is:
$livre = $inicio_pretendido >= $final_existente || $final_pretendido <= $inicio_existente
If you want Time coincident - "busy", only use these other two:
- Event start date A less (or equal to) than the end of event B
And
- Event end date A greater (or equal to) than the end of event B
Which in PHP is:
$ocupado = $inicio_pretendido <= $final_existente && $final_pretendido >= $inicio_existente
In both cases, you must adjust >=
or simply >
depending on whether or not an event finished exactly 9am can "live" with an event started 9am (it only depends on your specific scenario).
In SQL
Example of query to find free, but with "coexistence" at the time of the "turn":
SELECT * FROM tabela WHERE
( data1_inicio >= data2_fim OR data1_fim <= data2_inicio )
AND id_livro = 4
;
Note the ( )
in the part that tests the dates. It is also suggested to work with native dates in DB, instead of converting dynamically in seconds.
Visualizing:
Based on these 6 events:
AAAAAAAAAAAAAAAAAAA
| |
1 BBBBBBBBBBBB | Ocupado
2 | BBBBBBBBBBBBBB | Ocupado
3 | BBBBBBBBBBBBB Ocupado
4 BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB Ocupado
5 BBBB | | Livre
6 | | BBBBBBBBB Livre
We have this truth table with all possible comparisons:
1 A ini < B ini A ini < B fim A fim > B ini A fim < B fim Ocupado
2 A ini > B ini A ini < B fim A fim > B ini A fim < B fim Ocupado
3 A ini > B ini A ini < B fim A fim > B ini A fim > B fim Ocupado
4 A ini < B ini A ini < B fim A fim > B ini A fim > B fim Ocupado
5 A ini < B ini A ini < B fim A fim < B ini A fim < B fim Livre
6 A ini > B ini A ini > B fim A fim > B ini A fim > B fim Livre
Condicao 1 Condicao 2 Condicao 3 Condicao 4
(inutil) (util) (util) (inutil)
I didn’t really understand the meaning of these queries because there would have to be a second table with schedules available for scheduling, as it would be?
– Jesse Ribeiro