使用数据库中的时间范围填充下拉时间

时间:2014-01-28 18:25:00

标签: php sql

我试图以30分钟的间隔填充下拉菜单中的时间(改变到不同间隔的能力也会很好)。

我目前正在使用以下代码填充下拉菜单(通过搜索在线搜索此内容)。

$sqlHours   = "SELECT Open, Close FROM TimeTable";

       $rsSQLHours = odbc_exec($conn, $sqlHours);
       $strOpen    = trim(odbc_result($rsSQLHours, "Open"));
       $strClose   = trim(odbc_result($rsSQLHours, "Close"));

       $DeliHourOpen  = substr($strOpen, 0, 2);
       $DeliMinOpen   = substr($strOpen, 3, 2);
       $DeliHourClose = substr($strClose, 0, 2);
       $DeliMinClose  = substr($strClose, 3, 2);

      for($hours=$DeliHourOpen; $hours<=$DeliHourClose; $hours++) 
      for($mins=$DeliMinOpen; $mins<60; $mins+=30) 
      echo '<option value='.$hours.':'.$mins.'>'.date('h:i A', strtotime($hours.':'.$mins)).'</option>'; ?>

编辑:我将数据以24小时格式存储在数据库中,例如08:00:00或22:00:00。我使用date()只是以AM / PM方式格式化显示的输出,以方便用户使用。

我在关闭时间为20:00时会出现问题,下拉菜单会在晚上8:30进行。如果我从&lt; = $ DeliHourClose中删除=,那么它将仅显示7:30 PM。我需要它来显示关闭时间。

数据库中的字段为“时间”,格式为“H:i:s”。

此外,虽然下拉列表可以填充从打开到关闭的一系列时间,但我需要它从当前时间+ 30分钟开始。

因此,如果开放时间是上午8:00,而且是上午7:00,我希望在下拉菜单中首次看到上午8:00。但如果是上午9:00,下拉列表中的第一个选项需要是上午9:30。

我有一般的想法,它需要某种if / else来比较当前时间与下拉列表中的时间,但我不知道如何去做,我正在使用的格式为下拉。

如果可能的话,我希望有更易于管理的格式。

是否有更容易/更好的方法来生成可能会更改的时间间隔的范围?然后用适当的时间填充下拉列表?

非常感谢任何帮助或建议。

使用Microsoft SQL数据库。

编辑:表格中存储了多个位置。一旦我开始工作并添加更多位置,我将添加一个WHERE Location = XXX子句。目前只有一个位置,因此没有WHERE子句。

我使用的是time数据类型而不是datetime,因为我不希望y / m / d附加到打开/关闭时间。

1 个答案:

答案 0 :(得分:1)

您需要使用time()生成时间戳,这样您就可以获得unix时间戳,然后根据需要进行转换,这样您就可以添加时间并直接添加秒给定的unix时间戳。

资源:http://fr.php.net/time

编辑:我们很清楚并进一步解释:UNIX时间戳是自1970年1月1日以来的秒数,因此echo time();将返回1390934768,您只需要处理正如文档所示,它就在那里。

此代码whille将其作为数组返回:8 8.5 9 9.5 10 10.5 11 11.5 12 12.5 13 13.5 14 14.5 15 15.5 16 16.5 17 17.5 18 18.5 19

<?php
//Function returning unix time from simple time stamp (8 or 17.5 or whatever)
function ttounix($t) {
$tunix = $t * 60 * 60;
return $tunix;
}

//Function returning simple timestamp from unix timestamp
function unixtot($u) {
$tt = $u / 60 / 60;
return $tt;
}

$gap = 30 * 60; //gap in seconds
$t1 = 8; //opening time from db
$t2 = 19; //closing time from db 

//setting vars
$n = 0;
$count = array();

//Getting processed time stamps into vars
$o = ttounix($t1);
$c = ttounix($t2);

//Populating the array
while ( $o <= $c ) { 

$count[$n] = $o;

$o += $gap;
$n++;

}

//Output
foreach ($count as $output) { 
echo unixtot(intval($output)) . '<br />';
}

?>