Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP If an Hour Is Between Two Other Hours

Tags:

php

datetime

I need to work out if the current hour is between two other times. For example to check if the time is between 07:00 and 10:00 I could use:

$currentTime = new DateTime('09:00');
$startTime = new DateTime('07:00');
$endTime = new DateTime('10:00');

if ($currentTime->format('H:i') >= $startTime->format('H:i') && $currentTime->format('H:i') <= $endTime->format('H:i')) {
    // Do something
}

The problem I have is what happens if the time is 01:00 and I want to check if it's between 22:00 and 07:00. I'm not bothered that that it is another day, just if it falls between those two hours on a 24hr clock. Example 01:00 is between 22:00 and 07:00

22:00, 23:00, 00:00, 01:00, 02:00... 07:00

What I'm trying to achieve in the end is different prices can be set for a service between different times. So I currently loop through each hour working out what price bracket that hour falls into and the changing the price accordingly. If anyone has a more elegant solution for the problem I would be grateful to learn.

UPDATE:

Say I have a rule that says between 10pm and 7am I want to charge double. I loop through each hour from the start time to the end time and check if each hour falls between 22:00 (10pm) and 07:00 (7am) and if so it should be charged double. I want to avoid having to take in to account the date.

like image 498
user4143585 Avatar asked Nov 30 '22 18:11

user4143585


2 Answers

<?php
$currentTime = strtotime('1:00');
$startTime = strtotime('22:00');
$endTime = strtotime('7:00');

if (
        (
        $startTime < $endTime &&
        $currentTime >= $startTime &&
        $currentTime <= $endTime
        ) ||
        (
        $startTime > $endTime && (
        $currentTime >= $startTime ||
        $currentTime <= $endTime
        )
        )
) {
    echo 'open';
} else {
    echo 'clse';
}
like image 60
user1811893 Avatar answered Dec 04 '22 05:12

user1811893


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
}
like image 36
John Conde Avatar answered Dec 04 '22 03:12

John Conde