【问题标题】:Range time with interval in phpphp中带间隔的范围时间
【发布时间】:2015-02-12 15:11:19
【问题描述】:

我正在用 PHP 创建一个每日计划器,每 30 分钟我写一个表格行并检查约会是否匹配。但是,我遇到了约会时间部分的问题,例如我必须检查时间:15:34:58 - 16:34:58,我在15:3016:00 之间没有匹配。这是我的代码:

try {
    $inizio=new DateTime($r["data"]." ".$r["ora"]); // for me is 15:34:58
    $fine=new DateTime($r["data_fin"]." ".$r["ora_fin"]); // for me is 16:34:58
    $timetoCheck=new DateTime(date("Y-m-d")." ".$h.":".$m.":00"); //dinamically change in 15:30 16:00 and so on..
    $intervallo=new DateInterval("PT30M");
    $range=new DatePeriod($inizio, $intervallo, $fine);
    foreach ($range as $fase){
        if (($timetoCheck>=$inizio) and ($timetoCheck<=$fine)) {
            echo $fase->format("H:i:s")." ". $inizio->format("H:i:s")." - ".$fine->format("H:i:s")."<br/><a href='#' id='evento_".$r["key_id"]."'>".$r["titolo"]."</a><br/>";
        }
    }
} catch (Exception $ecc){
    $logger->error($ecc->getMessage());
}

【问题讨论】:

  • 如果您希望任何人尝试帮助,请从此表中剪切相关代码。
  • 如果没有任何内容,您可能不需要每 30 分钟写一行。
  • @James 我经常检查,我不能提前知道我是否会找到一些东西,但为什么我的 if 不匹配 15:30-16:00 之间的约会,如果它从 15 开始: 34 岁?
  • 您可以通过条件对此进行处理。如果是null,那么它不会返回任何事件。你会发现,如果一年中每 30 分钟添加一行,那么在不需要的时候,你最终会得到 17531 行。

标签: php datetime


【解决方案1】:

尝试不同的时间比较方式?

$dateTime = new DateTime("15:40:10");
$startTime = new DateTime("15:30:00");
$endTime = new DateTime("16:00:00");
if ($dateTime->diff($startTime)->format('%R') == '-' && $dateTime->diff($endTime)->format('%R') == '+') {
    // current time is within the appointment period
} else {
    // current time is either before or after the appointment period
}

http://php.net/datetime.diff

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    • 2019-05-26
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    相关资源
    最近更新 更多