如何让时间下拉框默认为当前时间?
我有一个 PHP 脚本,用于选择下拉框以 15 分钟为间隔显示时间;但是,我希望将其默认为最接近的当前时间(根据 15 分钟间隔向上或向下舍入)。有什么想法吗?
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>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里有一个方便的方法来获取当前时间向上或向下舍入:
您可以使用下面的演示来测试,只需将 450 或 900 添加到
$time
变量即可。编辑:根据下面的评论,有一个条件会失败,因为四舍五入的时间会导致滚动到第二天。要修复此问题,请将
$selected
行修改为:这会忽略日期部分,仅检查时间。我更新了下面的演示以反映这一变化。
演示
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
$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:This ignores the date portion and just checks the time. I've updated the demo below to reflect this change.
Demo
这是我留下的一些调试代码:
Here some debug code I left in: