首页 > 解决方案 > 如何从 24 小时制 (HHMM) 中减去分钟?

问题描述

我正在获取 HHMM 格式(0000 到 2359)的商店的营业时间和关闭时间:

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

然后我以相同的格式获得当前时间:

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

我想知道当前时间是否在开市前 15 分钟和闭市前 45 分钟之间。

我有这个,但它不准确:

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

如果时间为 2300,则 2300 - 15 = 2285,这不是有效时间。

我该如何解决这个问题?

另外,我假设我需要在一天的重叠时间(0000)做一些事情,但我不确定我需要在那里做什么。

标签: php

解决方案


您可以这样创建DateTime对象:

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

然后你可以使用DateTimeInterval

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

然后你可以从关闭时间和打开时间分它:

$now = new DateTime();
if ($now >= $open->sub($interval15) && $now <= $close->sub($interval45)) {
    // logic
}

推荐阅读