简体   繁体   中英

PHP get current time in option select with cut-off time

I have the following script which works great:

<?php
function create_time_range($start, $end, $interval = '30 mins', $format = '12') {
    $startTime = strtotime($start); 
    $endTime   = strtotime($end);
    $returnTimeFormat = ($format == '12')?'g:i:s A':'G:i:s';

    $current   = time(); 
    $addTime   = strtotime('+'.$interval, $current); 
    $diff      = $addTime - $current;

    $times = array(); 
    while ($startTime < $endTime) { 
        $times[] = date($returnTimeFormat, $startTime); 
        $startTime += $diff; 
    } 
    $times[] = date($returnTimeFormat, $startTime); 
    return $times; 
}
$times = create_time_range('7:30', '18:30', '30 mins');
?>

<select name="time_picker">
    <option value="">Select Time</option>
    <?php foreach($times as $key=>$val){ ?>
    <option value="<?php echo $val; ?>"><?php echo $val; ?></option>
    <?php } ?>
</select>

However I would love to have this altered: First of all it should only show time slots available given my current time, second to include a 2 hour window as "cut-of time".

Practical example and ideal outcome: Let's assume it's 1PM, the option select would 1.) not even display the values before 1PM and 2.) only show me the next available slot being 3PM (2 hour window)

I've been struggling with this for a few days but no result at the moment. Some expert advise would be greatly appreciated

http://codepad.org/OT2Qyb00

You can do it like this:

<?php
function create_time_range($start, $end, $interval = '30 mins', $format = '12') {
$startTime = strtotime($start); 
$endTime   = strtotime($end);
$returnTimeFormat = ($format == '12')?'g:i A':'G:i';
$hour = date('H');
$minute = (date('i')>30)?'30':'00';
$current = strtotime("$hour:$minute"); 
$addTime   = strtotime('+'.$interval, $current); 
$diff      = $addTime - $current;
$times = array(); 
while ($current < $endTime) { 
    $times[] = date($returnTimeFormat, $current) . " " . "$hour:$minute"; 
    $current += $diff; 
} 
$times[] = date($returnTimeFormat, $current); 
return $times; 
}
$times = create_time_range('8:00', '18:00', '30 mins');
?>

<select name="time_picker">
<option value="">Select Time</option>
<?php foreach($times as $key=>$val){ ?>
<option value="<?php echo $val; ?>"><?php echo $val; ?></option>
<?php } ?>
</select>

Here I use the $current as a basetime and I create that one by getting current hour and then time rounded by 30 min and then create time from that.

I hope this can help ya.

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