PHP如果一个小时介于另外两个小时之间


PHP If an Hour Is Between Two Other Hours

我需要计算出当前小时是否介于其他两个时间之间。例如,为了检查时间是否在07:00到10:00之间,我可以使用:

$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
}

我的问题是如果时间是01:00会发生什么,我想检查一下是不是在22:00到07:00之间。我并不担心这是另一天,只要它在24小时时钟的两个小时之间。示例01:00介于22:00和07:00 之间

22:00、23:00、00:00、01:00、02:00…07:00

我最终想实现的是,在不同的时间可以为一项服务设定不同的价格。因此,我现在每小时都在循环计算该小时的价格,并相应地改变价格。如果有人能为这个问题找到更优雅的解决方案,我将不胜感激。

更新:

假设我有一条规定,在晚上10点到早上7点之间,我想收取双倍费用。我从开始时间到结束时间每小时循环一次,检查每小时是否在22:00(晚上10点)到07:00(早上7点)之间,如果是,应该加倍收费。我想避免把日期考虑在内。

<?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';
}

无需使用DateTime::format()进行比较。DateTime对象已经具有可比性。

要处理跨越午夜的时间段,您需要更改日期,以便准确反映实际日期。

$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
}

我找到了另一种方法,从第一个更流行的解决方案开始,它有一个对我不起作用的问题。

我必须在晚上10:00到早上06:00之间写一些东西,但比较不起作用,因为当我过了午夜时,endTime总是>开始时间。

所以,如果我不介意我以这种方式解决的那一天:

$currentTime = new DateTime();
$startTime = new DateTime('22:00');
$endTime = (new DateTime('06:00'))->modify('+1 day');
if ($currentTime->format("a") == "am") { 
   // echo "It's a new day <br />"; 
   $currentTime = $currentTime->modify('+1 day');
}

if ($currentTime >= $startTime && $currentTime <= $endTime) {
    echo "hello";
}
    //get current DateTime
    $date = new DateTime('now');
    $currentHour = 0;
    $currentMinutes = 0;
    foreach ($date as $item=>$value ) {
        if($item=="date"){
            $p = explode(" ",$value)[1];
            $hour = explode(":",$p);
            $currentHour = $hour[0];
            $currentMinutes = $hour[1];
        }
    }
    $returnVO["success"] = ((int)$currentHour<12 || ((int)$currentHour>=22 && (int)$currentMinutes > 0) ) ? false : true;
$hour = (int)date('H');
echo ($hour > 7 && $hour < 22) ? 'Open' : 'Close';

$hour = (int)date('H');
echo ($hour <= 7 || $hour >= 22) ?  'Close':'Open';