Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Check if time is between two times regardless of date

Tags:

php

time

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
like image 895
user1393817 Avatar asked Nov 25 '14 16:11

user1393817


People also ask

How do you check if a time is between two times in PHP?

$current_time = date('h:i:s a'); and if we use >= , <= in if condition then we'll get accurate answer..

How can I get minutes between two dates in PHP?

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);

How can I get days between two dates in PHP?

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.


2 Answers

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

like image 75
Glavić Avatar answered Sep 19 '22 08:09

Glavić


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;
    }
}
like image 32
Edward Avatar answered Sep 18 '22 08:09

Edward