检查时间是否在一定范围内

时间:2020-04-28 21:23:31

标签: php datetime

我正在使用php 7.4,并且正在创建一个应检查某些条件的函数,例如:

  • 检查是否已通过 xx 分钟-$timeToLastPostinMinutes-直到计划过程开始为止
  • 今天是允许的日子
  • 今天是一个在允许范围内的时隙
  • 如果满足所有条件,则返回添加了 xx 分钟的Datetime

我创建了以下函数,应检查上述两个条件:

<?php

/**
 * Weekdays: [1, 2, 3, 4, 5, 6, 7],
 * Times are as an array specified, from-to: [["09:00", "11:00"], ["18:00", "24:00"]],
 * TimeTolastPost example 15 for 15 minutes
 * @param Datetime $lastPostdateTime
 * @param $weekdays
 * @param $times
 * @param $timeToLastPostinMinutes
 * @throws Exception
 */
function createPostSchedule(Datetime $lastPostdateTime, $allowedWeekdays, $allowedTimes, $timeToLastPostinMinutes, $timeToWaitInMin)
{
    $today = new DateTime();

    // if $lastPostdateTime is x Minutes ($timeToWaitInMin) in the past, then start the schedule process
    if ($lastPostdateTime->add(new DateInterval('PT' . $timeToWaitInMin . 'M'))->getTimestamp() > $today->getTimestamp()) {
        $today->format('N');
        // check if today is in the day array
        if(in_array(intval($today->format('N')), $allowedWeekdays)) {
            // check if time is in the slot
            foreach ($allowedTimes as $key => $val) {
                if (strtotime($val[0]) > $today->getTimestamp() && strtotime($val[1]) < $today->getTimestamp()) {
                    if($timeToLastPostinMinutes != 0) {
                        return $lastPostdateTime->add(new DateInterval('PT' . $timeToLastPostinMinutes . 'M'));
                    }
                }
            }
        }
    }
}

$dateTime = DateTime::createFromFormat('m-d-Y H:i:s', '10-16-2020 15:55:33');

$postSchedule = createPostSchedule($dateTime, [1, 2, 3, 4, 5], [["09:00", "24:00"]], 15, 1440);

echo $postSchedule->format('Y-m-d H:i:s');

但是,我找回null

我认为比较时隙可能会有问题。但是,他们正在相互比较两个时间戳,这似乎是正确的吗?

有什么建议让我退回null

感谢您的答复!

1 个答案:

答案 0 :(得分:1)

您正在将每个时隙的开始和结束都与相同的值-当前时间戳进行比较。很明显,当前时间戳不可能同时低于时隙开始时间和高于时隙结束时间。您需要撤消比较:

<IfModule mod_setenvif.c>
    SetEnvIf Request_URI "\.(jpe?g|png|webp)$" REQUEST_image
</IfModule>
<IfModule mod_headers.c>
    Header append Vary Accept env=REQUEST_image
</IfModule>