简体   繁体   中英

Convert Start/End Time into Hourly Intervals PHP

I have a simple form that lets users enter a start time and end time. Upon submission I need to create hourly intervals for every hour between the start and the end time. For example if they selected Start Time '3:00pm' and End Time '7:00pm' I would like to create 4 records in my database as follows:

Start End 3:00pm 4:00pm 4:00pm 5:00pm 5:00pm 6:00pm 6:00pm 7:00pm

Users are selecting from a select menu with these values:

        <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>

I'm retrieving the start time and end time like this:

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

I'm assuming I need to do a foreach but not sure how to grab the time intervals in a loop and set the start/end time for each interval?

Follow the conventional approach of using strtotime and date functions and loop through your result.

Try this:

$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))
    );
}

For input $_POST['timeStart'] = '3:00pm'; and $_POST['timeEnd'] = '7:00pm'; , the output will be:

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
    )

 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM