How to Check If Time Is Between Two Times in PHP

How to check if time is between two times in PHP

$current_time = "4:59 pm";
$sunrise = "5:42 am";
$sunset = "6:26 pm";
$date1 = DateTime::createFromFormat('h:i a', $current_time);
$date2 = DateTime::createFromFormat('h:i a', $sunrise);
$date3 = DateTime::createFromFormat('h:i a', $sunset);
if ($date1 > $date2 && $date1 < $date3)
{
echo 'here';
}

See it in action

Reference

  • DateTime

PHP Check if time is between two times regardless of date

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

Check if time is between two times and interval

You can loop through the times in between the two given times and if it lands on an "interval" time, you can break from the for loop and echo out a success message.

For example:

$found = false;
for ($i=0; $i < 1440; $i++) {
$begin->add(new DateInterval('PT' . $interval . 'M'));
if($begin == $input) {
$found = true;
break;
} elseif($begin > $input || $begin > $end) {
$found = false;
break;
}
}

if($found) {
echo 'Success';
} else {
echo 'Fail';
}

Check if time is between two times PHP

So if $endtime is next day, simply add 2400 to it during the test.

$endtime = $endtime <= $starttime ? $endtime + 2400 : $endtime;

if ( ($current >= $starttime) && ($current <= $endtime) )

I need to check if time now is between two times


$start = new DateTime("11:59:59");
$end = new DateTime("13:59:59");
$now = new DateTime();

if($now < $end and $now > $start)
{
echo "Yes, now is between start and end";
}
else
{
// do something else
}

PHP If an Hour Is Between Two Other Hours

No need to use DateTime::format() for your comparisons. DateTime objects are already comparable.

To handle working with time periods that span midnight you will need to change the date so you have an accurate reflection of the actual date.

$currentTime = (new DateTime('01:00'))->modify('+1 day');
$startTime = new DateTime('22:00');
$endTime = (new DateTime('07:00'))->modify('+1 day');

if ($currentTime >= $startTime && $currentTime <= $endTime) {
// Do something
}


Related Topics



Leave a reply



Submit