php - 在PHP中获取两次之间的时间范围
问题描述
我需要在两个给定小时之间获得一个小时范围,步长为 15 分钟,所以我得到了这个:
"book_time_range": [
"13:00-13:15",
"13:15-13:30",
"13:30-13:45",
"13:45-14:00",
"14:00-14:15",
"14:15-14:30",
"14:30-14:45",
"14:45-15:00",
"15:00-15:15",
"15:15-15:30"
],
据我所知:
public function hours_range_between_start_and_end(
$start = '13:00',
$end = '15:30',
$step = 900,
$format = 'H:i'
) {
$times_ranges = [];
$start = strtotime($start) - strtotime('TODAY');
$end = strtotime($end) - strtotime('TODAY');
foreach (range($start, $end, $step) as $increment)
{
$increment = gmdate('H:i', $increment);
list($hour, $minutes) = explode(':', $increment);
$date = new DateTime($hour . ':' . $minutes);
$times_ranges[] = $date->format($format);
}
return $times_ranges;
}
这给了我:
"book_time_range": [
"13:00",
"13:15",
"13:30",
"13:45",
"14:00",
"14:15",
"14:30",
"14:45",
"15:00",
"15:15",
"15:30"
],
这在技术上是正确的,但我被困在如何使用该阵列来获得我想要的阵列。
有小费吗?也许我从一开始就错误地接近这个?
解决方案
您可以通过另一种简单的方式实现这一目标。只需使用以下方法设置开始时间和结束时间DateTime::class
,然后在开始时间上增加 15 分钟,直到在 a 的帮助下到达结束时间while-loop
:
<?php
$begin = new DateTime('2020-05-28 13:00');
$end = new DateTime('2020-05-28 15:30');
$timeRanges = [];
while($begin < $end) {
$output = $begin->format('H:i') . " - ";
$begin->modify('+15 minutes'); /** Note, it modifies time by 15 minutes */
$output .= $begin->format('H:i');
$timeRanges[] = $output;
}
print_r($timeRanges);
在此处查看输出https://3v4l.org/r0E3R
推荐阅读
- java - 隐藏工厂实现
- linux - 如何将物理地址映射到适合 get_user_pages_fast() 的用户空间虚拟地址?
- android - Android WorkManager:如何处理正在进行的工作,例如蓝牙扫描
- python - 替换一系列熊猫中的值
- php - WordPress WooCommerce 问题描述
- powerpivot - 功率轴 ytd 计算
- google-sheets - Google 表格——如果 A 列是 x/y/z 值,则格式化行 x 颜色
- angular - 使用 webpack 时 Angular 不解析构造函数依赖项
- java - 类型参数数组
- react-native - React-native fontFamily:'Heebo-Medium'不支持斜体