I have a PHP script for a select dropdown box to display times in 15 minute intervals; however, I’d like to have it default to the closest current time (rounding up or down based on 15 minute interval). Any ideas?
date_default_timezone_set($_SESSION['TIME_ZONE'])
<label id="time_label" for="time" class="label">Time:</label>
<select id="time" name="time">
<option value="">Select</option>
<?
$start = strtotime('12:00am');
$end = strtotime('11:59pm');
for ($i = $start; $i <= $end; $i += 900){
echo '<option>' . date('g:i a', $i);
}
?>
</select>
Here is a convenient way to get the current time rounded up or down:
You can use the following demo to test, just add either 450 or 900 to the
$timevariable.Edit: As per the comments below, there is one condition that will fail because the rounded up time results in a rollover to the next day. To fix it, modify the
$selectedline to:This ignores the date portion and just checks the time. I’ve updated the demo below to reflect this change.
Demo