php - 如何从 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)做一些事情,但我不确定我需要在那里做什么。
解决方案
您可以这样创建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
}
推荐阅读
- javascript - 为什么单击按钮时 JavaScript 有时无法正常工作?
- tomcat - 信息:在 java.library.path 上找不到允许使用 OpenSSL 的 Apache Tomcat Native 库:
- google-cloud-platform - 解决上传 CSV 到 Google Cloud Platform AI Dataset 的错误编码
- javascript - 为什么我使用 axios 的简单获取请求不会返回控制器返回的内容?
- java - 想要在java中更改csv文件中的数据时出错
- mysql - 从mysql日志中的行中删除特定单词
- r - R中是否有一种有效的方法可以将矩阵M2的每一行“粘贴”到矩阵M1的每一行以获得所有可能的组合?
- python - 我在使用 windows 安装 polyglot 时遇到问题
- git - 为什么或如何我的代码恢复到一周前的版本?
- reactjs - 如何使反应挂钩与 ref 保持一致