Solution in PHP
In my view, since we are working with schedules, the easiest is to use the class Datetime PHP. First, let’s define the tests shown in the statement:
$tests = [
[
"inicio" => "07:00:00",
"final" => "09:00:00",
"busca" => "08:00:00",
"saida" => true
],[
"inicio" => "19:00:00",
"final" => "22:00:00",
"busca" => "23:00:00",
"saida" => false
],[
"inicio" => "18:00:00",
"final" => "03:00:00",
"busca" => "01:00:00",
"saida" => true
],
];
The three proposed tests, composed of the initial, final, the search and the expected output. To run the tests, we used a loop basic:
foreach($tests as $test)
{
// ...
}
First step is to define the objects relating to the times:
foreach($tests as $test)
{
$ininio = new DateTime($test["inicio"]);
$final = new DateTime($test["final"]);
$busca = new DateTime($test["busca"]);
}
As it is clear that it should be independent of the day and that even the interval can start in one day and end in another, as is the case with the third test, we need to make a simple check: if the final time is less than the initial, add at the end an interval of one day.
foreach($tests as $test)
{
$ininio = new DateTime($test["inicio"]);
$final = new DateTime($test["final"]);
$busca = new DateTime($test["busca"]);
if ($final <= $inicio) {
$final->add(new DateInterval("P1D"));
}
}
Read more about the class Dateinterval in the documentation. Thus, if the final time is less than the initial one, it is added 24h in it, becoming the same time of the next day.
The same logic applies to the time sought: if it is lower than the initial time, it should be considered as the next day and therefore be added 24h also.
foreach($tests as $test)
{
$ininio = new DateTime($test["inicio"]);
$final = new DateTime($test["final"]);
$busca = new DateTime($test["busca"]);
if ($final <= $inicio) {
$final->add(new DateInterval("P1D"));
}
if ($busca <= $inicio) {
$busca->add(new DateInterval("P1D"));
}
}
With this, just check the interval:
foreach($tests as $test)
{
$ininio = new DateTime($test["inicio"]);
$final = new DateTime($test["final"]);
$busca = new DateTime($test["busca"]);
if ($final <= $ininio) {
$final->add(new DateInterval("P1D"));
}
if ($busca <= $ininio) {
$busca->add(new DateInterval("P1D"));
}
if ($busca >= $ininio && $busca <= $final) {
echo "Sim";
} else {
echo "Não";
}
echo ", esperado " . ($test["saida"] ? "sim" : "não") . PHP_EOL;
}
I added to the output message the expected value for each test, to serve as a comparison. When executing the code, we will have the output:
Sim, esperado sim
Não, esperado não
Sim, esperado sim
See the code working on Repl.it or in the Ideone.
01:00:00 is at the interval informed, yes, now. From 18h in the afternoon to 03h in the morning, and the 01:00:00 means that it is 1 am/dawn. If you want to check 1 pm then you should inform 13:00:00
– Seu Madruga
Doesn’t that solve? http://stackoverflow.com/questions/19070116/php-check-if-date-between-two-dates
– Marcos Xavier