I'm writing a script were I have to check if a time range is between two times, regardless of the date.
For example, I have this two dates:
$from = 23:00
$till = 07:00
I have the following time to check:
$checkFrom = 05:50
$checkTill = 08:00
I need to create script that will return true if one f the check values is between the $from/$till range. In this example, the function should return true because $checkFrom is between the $from/$till range. But also the following should be true:
$checkFrom = 22:00
$checkTill = 23:45
$current_time = date('h:i:s a'); and if we use >= , <= in if condition then we'll get accurate answer..
We will be using the built-in function date_diff() to get the time difference in minutes. For this, we will be needed a start date and end date to calculate their time difference in minutes using the date_diff() function. Syntax: date_diff($datetime1, $datetime2);
The date_diff() function is an inbuilt function in PHP that is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns FALSE on failure.
Try this function:
function isBetween($from, $till, $input) {
$f = DateTime::createFromFormat('!H:i', $from);
$t = DateTime::createFromFormat('!H:i', $till);
$i = DateTime::createFromFormat('!H:i', $input);
if ($f > $t) $t->modify('+1 day');
return ($f <= $i && $i <= $t) || ($f <= $i->modify('+1 day') && $i <= $t);
}
demo
based on 2astalavista's answer:
You need to format the time correctly, one way of doing that is using PHP's strtotime()
function, this will create a unix timestamp you can use to compare.
function checkUnixTime($to, $from, $input) {
if (strtotime($input) > strtotime($from) && strtotime($input) < strtotime($to)) {
return true;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With