douhuan7862 2014-10-18 09:35
浏览 25
已采纳

检查时间是否介于两次之间

I have a deal which is available on every Friday from 22:00 to 4:00. But the problem is that after 00:00 it will turn to Saturday and my code will no longer find the deal.

Here is how I save the deals:

Array
(
    [0] => Array
        (
            [offerAvailableOn] => 5
            [open] => 22:00 
            [close] =>  04:00
        )
}

And this is my code to query for it:

$today = date('N');
$timeNow = date('H:i');

But when $today is Saturday, it won't find my offer.

  • 写回答

2条回答 默认 最新

  • douchun1961 2014-10-18 10:03
    关注

    You can make your open and close variables to include the day of the week. Have a look at this page of the manual:

    http://php.net/manual/en/datetime.formats.relative.php

    So open could be 'Friday 22:00' en close could be 'Saturday 04:00'. In PHP that would look like this:

    $deal = array('open'  => 'Friday 22:00',
                  'close' => 'Saturday 04:00');
    
    echo 'deal open: '.date('Y-m-d H:i:s', strtotime($deal['open'])).'<br>';
    echo 'deal close: '.date('Y-m-d H:i:s', strtotime($deal['close']));
    

    For me this gives now:

    deal open: 2014-10-24 22:00:00
    deal close: 2014-10-18 04:00:00
    

    Notice that the deal open time is bigger that the current time. So you have to think about your if conditions:

    $open  = strtotime($deal['open']);
    $close = strtotime($deal['close']);
    $now   = time();
    
    $dealIsOn = (($open > $now) && ($close < $now));
    

    Which might seem counter-intuitive at first, but is correct.

    Also notice that this system is quite flexible. With the same code you can select a day of the month. However, for a absolute dates you have to do another check:

    $open  = strtotime('2014-10-25 22:00:00');
    $close = strtotime('2014-10-26 22:00:00');
    $now   = time();
    
    $dealIsOn = (($open < $now) && ($close > $now));
    

    So I would introduce a flag in the array indicating whether or not the open and close variables are absolute or relative.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题