5

ユーザーの送信を受け入れるシステムがあり、送信を受信すると、システムはすべてのタイムスロットを調べて適切なタイムスロットを見つけます。問題は、終了時刻が翌日になる場合、開始時刻と終了時刻をチェックできる必要があることです。

次の例を見てください: タイムスロットは、当日の午後 10 時 30 分に開始し、翌日の午後 4 時に終了します。現在の時刻が午後 10 時 30 分~午後 11 時 59 分 59 秒の場合、提出物はそのタイムスロットに割り当てられます。ただし、現在の時刻が午前 0 時から午後 4 時の間である場合、タイムスロットはスキップされます。

これは私がこれまでに持っているものです:

function check_time($from, $to, $time) {
    $time = strtotime($time);
    $from = strtotime($from);
    $to_ = strtotime($to);
    $to = $to_ <= $from ? strtotime($to . " tomorrow") : $to_;
    return ($time >= $from && $time <= $to);
}

$timeslots = array(
    array("16:00:00", "22:30:00"),
    array("22:30:00", "16:00:00")
);
foreach ($timeslots as $slot) {
    if (check_time($slot[0], $slot[1], date("H:i:s")))
        {
            echo "true\n";
        }
    else 
        {
            echo "false\n";     
        }
}

現在の時刻が 23:00:00 の場合、結果は次のようになります。

false
true

ただし、現在の時刻が 12:00:00 の場合、結果は次のようになります。

false
false

技術的には2つの時間の間にありますが。

それが新しい日である場合、strtotime結果$fromはその日の後半になるという事実に関係していることを私は知っています。したがって、昨日の午後 10 時 30 分をチェックする代わりに、今夜の午後 10 時 30 分をチェックします。

$from私の問題は、時間を翌日に強制する方法と同様に、必要に応じて時間を前日に切り替える方法を思いつかないように見えることです$to

4

2 に答える 2

8

これは、予想よりもはるかに簡単です。t1、 、t2およびの 3 つの時間があると仮定しますtn。これらの時間は、それぞれ from、to、および user 時間を表します。これらの時間を 6 桁の数字 (000000 から 235959 まで) として扱い、以下を確認します。

  • t1t2が深夜境界の同じ側にある 場合
    • tnとの間t1にあるかどうかをチェックするt2
  • そうしないと
    • が と の間にtnないことを確認するt2t1

コードとテスト:

function check_time($t1, $t2, $tn) {
    $t1 = +str_replace(":", "", $t1);
    $t2 = +str_replace(":", "", $t2);
    $tn = +str_replace(":", "", $tn);
    if ($t2 >= $t1) {
        return $t1 <= $tn && $tn < $t2;
    } else {
        return ! ($t2 <= $tn && $tn < $t1);
    }
}
$tests = array(
    array("16:00:00", "22:30:00", "15:00:00"),
    array("16:00:00", "22:30:00", "16:00:00"),
    array("16:00:00", "22:30:00", "22:29:59"),
    array("16:00:00", "22:30:00", "22:30:00"),
    array("16:00:00", "22:30:00", "23:59:59"),
    array("22:30:00", "16:00:00", "22:29:59"),
    array("22:30:00", "16:00:00", "22:30:00"),
    array("22:30:00", "16:00:00", "15:59:59"),
    array("22:30:00", "16:00:00", "16:00:00"),
    array("22:30:00", "16:00:00", "17:00:00")
);
foreach($tests as $test) {
    list($t1, $t2, $t0) = $test;
    echo "$t1 - $t2 contains $t0: " . (check_time($t1, $t2, $t0) ? "yes" : "no") . "\n";
}
// OUTPUT
//
// 16:00:00 - 22:30:00 contains 15:00:00: no
// 16:00:00 - 22:30:00 contains 16:00:00: yes
// 16:00:00 - 22:30:00 contains 22:29:59: yes
// 16:00:00 - 22:30:00 contains 22:30:00: no
// 16:00:00 - 22:30:00 contains 23:59:59: no
// 22:30:00 - 16:00:00 contains 22:29:59: no
// 22:30:00 - 16:00:00 contains 22:30:00: yes
// 22:30:00 - 16:00:00 contains 15:59:59: yes
// 22:30:00 - 16:00:00 contains 16:00:00: no
// 22:30:00 - 16:00:00 contains 17:00:00: no
于 2013-06-17T10:16:18.300 に答える