mysql在午夜过后开放

时间:2013-10-28 19:31:23

标签: php mysql database time

我正在建立一个api,我有一个午夜开放的酒吧列表。 我发现他们目前是开放还是关闭时遇到了问题。

让我们举例说,其中一个酒吧有这些营业时间:

Monday 
open time = 20:00
closed time = 05:00

Tuesday 
open time = 20:00
closed time = 04:00

如果我想知道一个柱子当前是否打开且当前时间是04:00(星期一是星期一),这将导致当前柱子关闭,因为它的星期二和关闭时间= 04:00 < / p>

但实际结果应该是酒吧开放至05:00(星期一星期一)

我有20多个酒吧的清单,我需要知道他们当前是开放还是关闭。 这可以在mysql或php中完成吗?我应该如何设置我的数据库表?

我将此作为我当前的设置

表名:openhours 字段:

 id          int(11)
 bar_id      int(11)
 open_time   time
 close_time  time
 day         tinyint(1)

表记录:

 id: 1
 bar_id: 1
 open_time: 20:00:00
 closed_time: 05:00:00
 day: 0

 id: 2
 bar_id: 1
 open_time: 20:00:00
 closed_time: 04:00:00
 day: 1

此查询适用于不会超过午夜的开放日

SELECT `open_time`, `closed_time`, IF(CURTIME() BETWEEN `open_time` 
AND `closed_time`,'open','closed') AS `status` FROM `openhours` 
WHERE `day` = DATE_FORMAT(NOW(), '%w')

但是我如何处理过去的午夜问题?

它尝试了类似的东西,但它不太正确

  SELECT open_time, close_time, day, (CASE WHEN ((open_time <= close_time 
  AND open_time <= CURTIME() AND close_time >= CURTIME()) OR (open_time >= close_time 
  AND (CURTIME() <= close_time OR CURTIME() >= open_time))) THEN 'open' ELSE 'closed' 
  END) AS status FROM openhours WHERE bar_id = 2 and CASE WHEN (day = WEEKDAY(NOW())    
  AND (CURTIME() < open_time)) THEN CASE WHEN (day = (WEEKDAY(NOW()) - 1) 
  AND (CURTIME() < close_time)) THEN day = (WEEKDAY(NOW()) - 1) 
  ELSE day = WEEKDAY(NOW()) END ELSE day = WEEKDAY(NOW()) END

提前致谢!

3 个答案:

答案 0 :(得分:0)

您可以使用UNIX_TIMESTAMP()来解决此类问题:

SELECT `open_time`, `closed_time`, IF(UNIX_TIMESTAMP(CURTIME()) BETWEEN UNIX_TIMESTAMP(`open_time`) AND UNIX_TIMESTAMP(`closed_time`),'open','closed') AS `status` FROM `openhours` WHERE `day` = DATE_FORMAT(NOW(), '%w')

我希望我明白你的观点:)

答案 1 :(得分:0)

你想要这样的东西

case closed < open
 not between open and closed
else 
 between open and closed 

如果返回true,则栏已打开

答案 2 :(得分:0)

一种选择是存储超过一周开始的秒数,这样你根本不需要担心午夜。

将这些添加到您的表格中:

open_time_i   int(11)
closed_time_i int(11)

并使您的数据看起来像这样:

id: 1
bar_id: 1
open_time: 20:00:00
open_time_i: 72000
closed_time: 05:00:00
closed_time_i: 104400
day: 0

id: 2
bar_id: 1
open_time: 20:00:00
open_time_i: 158400
closed_time: 04:00:00
closed_time_i: 187200
day: 1

然后您的查找可能如下所示:

$seconds = time() - strtotime('this week last sunday', date("Y-m-d", time()))

SELECT `open_time`, `closed_time`, IF(
  $seconds BETWEEN `open_time_i` AND `closed_time_i`
    OR
  (("closed_time_i" >= 604800 AND $seconds BETWEEN 0 AND ("closed_time_i" - 604800)))
,'open','closed') AS `status` FROM `openhours`

第二个语句之间检查该栏是否在周变更后打开。