将开始/结束时间转换为每小时间隔PHP

时间:2016-10-07 04:08:35

标签: php

我有一个简单的表单,允许用户输入开始时间和结束时间。提交后,我需要在开始和结束时间之间的每小时创建每小时间隔。例如,如果他们选择开始时间'下午3:00'和结束时间'晚上7:00',我想在我的数据库中创建4条记录,如下所示:

开始结束 下午3:00 pm下午4:00 下午4:00 pm 下午5:00 pm 下午6点到晚上7点

用户正在从具有以下值的选择菜单中进行选择:

        <option value="10:00am">10:00am</option>
        <option value="11:00am">11:00am</option>
        <option value="12:00pm">12:00pm</option>
        <option value="1:00pm">1:00pm</option>
        <option value="2:00pm">2:00pm</option>
        <option value="3:00pm">3:00pm</option>
        <option value="4:00pm">4:00pm</option>
        <option value="5:00pm">5:00pm</option>
        <option value="6:00pm">6:00pm</option>
        <option value="7:00pm">7:00pm</option>
        <option value="8:00pm">8:00pm</option>
        <option value="9:00pm">9:00pm</option>
        <option value="10:00pm">10:00pm</option>
        <option value="11:00pm">11:00pm</option>

我正在检索开始时间和结束时间:

$startTime =  $_POST['timeStart'];
$endTime = $_POST['timeEnd'] ;

我假设我需要做一个foreach但不确定如何在循环中获取时间间隔并设置每个时间间隔的开始/结束时间?

1 个答案:

答案 0 :(得分:1)

按照传统方法使用strtotimedate函数并循环显示结果。

试试这个:

$startTime = strtotime($startTime);   /* Find the timestamp of start time */
$endTime = strtotime($endTime);       /* Find the timestamp of end time */
$input = array();
/* Run a loop from start timestamp to end timestamp */
for ($i = $startTime; $i < $endTime; $i+=3600) {
    $input[] = array(
        "start_time" => date("h:ia", $i), 
        "end_time" => date("h:ia", ($i+3600))
    );
}

对于输入$_POST['timeStart'] = '3:00pm';$_POST['timeEnd'] = '7:00pm';,输出将为:

Array
(
 [0] => Array
    (
        [start_time] => 03:00pm
        [end_time] => 04:00pm
    )

  [1] => Array
    (
        [start_time] => 04:00pm
        [end_time] => 05:00pm
    )

  [2] => Array
    (
        [start_time] => 05:00pm
        [end_time] => 06:00pm
    )

  [3] => Array
    (
        [start_time] => 06:00pm
        [end_time] => 07:00pm
    )

 )