Reputation: 2284
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>
Upvotes: 1
Views: 2748
Reputation: 59709
Here is a convenient way to get the current time rounded up or down:
$time = time();
$rounded_time = $time % 900 > 450 ? $time += (900 - $time % 900): $time -= $time % 900;
$start = strtotime('12:00am');
$end = strtotime('11:59pm');
for( $i = $start; $i <= $end; $i += 900)
{
$selected = ( $rounded_time == $i) ? ' selected="selected"' : '';
echo '<option' . $selected . '>' . date('g:i a', $i) . '</option>';
}
You can use the following demo to test, just add either 450 or 900 to the $time
variable.
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 $selected
line to:
$selected = ( ($rounded_time - $i) % (86400) == 0) ? ' selected="selected"' : '';
This ignores the date portion and just checks the time. I've updated the demo below to reflect this change.
Upvotes: 2
Reputation: 1281
<label id="time_label" for="time" class="label">Time:</label>
<select id="time" name="time">
<option value="">Select</option>
<?php
$start = strtotime('12:00am');
$end = strtotime('11:59pm');
$now = strtotime('now');
$nowPart = $now % 900;
if ( $nowPart >= 450) {
$nearestToNow = $now - $nowPart + 900;
if ($nearestToNow > $end) { // bounds check
$nearestToNow = $start;
}
} else {
$nearestToNow = $now - $nowPart;
}
for ($i = $start; $i <= $end; $i += 900){
$selected = '';
if ($nearestToNow == $i) {
$selected = ' selected="selected"';
}
echo "\t<option" . $selected . '>' . date('g:i a', $i) . "\n";
}
?>
</select>
Here some debug code I left in:
<?php
echo '<p></p>DEBUG $now = '. date('Y-m-d g:ia', $now) . "<br />\n";
echo "DEBUG \$nowPart = $nowPart<br />\n";
echo 'DEBUG $nearestToNow = '. date('Y-m-d g:ia', $nearestToNow) . "<br />\n";
?>
Upvotes: 3