douqilai4263 2018-07-22 05:54
浏览 85
已采纳

如何从24小时制(HHMM)中减去分钟数?

I'm getting the opening and closing time of a store in HHMM format (0000 to 2359):

$openingtime = intval($open->time);
$closingtime = intval($close->time);

Then I get the current time in the same format:

$nowtime = intval(date("G") . date("i"));

I want to know whether the current time is between 15 minutes before the opening time, and 45 minutes before the closing time.

I have this, but it is inaccurate:

if(($nowtime >= ($openingtime - 15)) && ($nowtime <= ($closingtime - 45))){
    // current time is between 15 minutes before opening and 45 minutes before closing
}

If the time is 2300, then 2300 - 15 = 2285, which isn't a valid time.

How can I resolve this?

Also, I assume I need to do something at the overlap of the day (0000), but I'm not sure what I need to do there.

  • 写回答

2条回答 默认 最新

  • dsgawmla208057 2018-07-22 06:10
    关注

    You can create DateTime object like that:

    $open = date_create_from_format('Hi', '1000');
    $close = date_create_from_format('Hi', '1900');
    

    Then you can use DateTimeInterval

    $interval15 = new \DateInterval('P0Y0DT0H15M');
    $interval45 = new \DateInterval('P0Y0DT0H45M');
    

    Then you can sub it from closing time and from open:

    $now = new DateTime();
    if ($now >= $open->sub($interval15) && $now <= $close->sub($interval45)) {
        // logic
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?