PHP : Check if requested time is between two given time slots

PHP : Check if requested time is between two given time slots

Sometime in development, you will need to write script to check if given time is in between from and to time.

For this case we will work on some date operation which is quite easy in PHP.

Here I have created a function which takes from time, to time and input time to check:

<?php

function checkIfExist($fromTime, $toTime, $input) {
    
    $fromDateTime = DateTime::createFromFormat("!H:i", $fromTime);    
    $toDateTime = DateTime::createFromFormat('!H:i', $toTime);
    $inputDateTime= DateTime::createFromFormat('!H:i', $input);
    if ($fromDateTime> $toDateTime) $toDateTime->modify('+1 day');
    return ($fromDateTime <= $inputDateTime&& $inputDateTime<= $toDateTime) || ($fromDateTime <= $inputDateTime->modify('+1 day') && $inputDateTime<= $toDateTime);
}

$result=checkIfExist("08:00","18:00","09:00");
echo $result; // output 1 - true

?>

As you can see I have used inbuilt function DateTime::createFromFormat() of PHP to parse time string according to required format and it returns a new date time object.

Phone: (+91) 8800417876
Noida, 201301