首页 > 解决方案 > 在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"
],

这在技术上是正确的,但我被困在如何使用该阵列来获得我想要的阵列。

有小费吗?也许我从一开始就错误地接近这个?

标签: phparrays

解决方案


您可以通过另一种简单的方式实现这一目标。只需使用以下方法设置开始时间和结束时间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


推荐阅读