2012-10-08 63 views
2

场景之间检查提供的日期时间值位于一定的时间间隔

UDPATE

请忽略的注释部分。思考替代后,我想出了这个:

比方说,我有

$date = '2012-10-03 13:00:00' 

的时间间隔范围是

2012-10-03 12:00:00 to 2012-10-03 14:00:00 

现在$date为在上述时间范围之间。有关如何比较日期时间和日期时间范围的任何想法?我遇到过比较正式日期或正式时间但不是同时比较的函数。任何帮助非常感谢。

/*I'm building a school timetable and want to make sure that a room cannot be assigned to two different periods if it is already occupied. I have datetime values of **`2012-10-03 13:00:00`** (the start time of a period. Let's call it **abc** for reference) and **`2012-10-03 13:30:00`** (the end time of a period. Let's call it **xyz** for reference). 

My database table contains columns for room number assigned for a period and the start and end time of that period. Something like this: 

    room_no | start_time   | end_time 
     5  2012-10-03 13:00:00 2012-10-03 14:30:00 

This means for October 3, 2012 room 5 is occupied between 1pm and 2:30pm. So the datetime values that I have (abc & xyz) will have to be assigned to a room other than 5. 

I'm at a loss of ideas on how to go about validating this scenario, i.e. make sure that the period with time interval between abc & xyz cannot be assigned room number 5. 

Any help would be appreciated. Thanks in advance 

PS : I'm not asking for code. I'm looking for ideas on how to proceed with the issue at hand. Also, is there a way a query can be build to return a row if `abc` or `xyz` lie between `start_time` and `end_time` as that would be great and reduce a lot of workload. I could simply use the number of rows returned to validate (if greater than 0, then get the room number and exclude it from the result)*/ 

回答

1
if(StartTime - BookingTime < 0 && BookingTime - EndTime < 0) 
{ 
    // Booking time is already taken 
} 

您可以使用TIMEDIFF()在SQL中执行此操作。

+0

所以在我的情况下,预约时间将由'abc'引用的时间? – asprin

+0

我的例子是显示是否已经过指定的时间。所以如果在下午3点到5点之间预订,预订时间是下午4点,它将进入该语句。如果您正在验证新请求,则您需要比较新的预订时间和结束预订时间,以确保它不会重叠。 – MatthewMcGovern

+0

但是,这是否意味着循环遍历表中的每条记录以获取每行的开始时间和结束时间?如果说有300多行,这不会很昂贵吗? – asprin

0

我正在做类似的事情,也许更简单的方法来编码它不会使用时间,但时间槽?我认为这样做的方式是桌子预订(日期,插槽标识符,房间)表格插槽(可能是插槽ID和时间),并且每个预订使用一定数量的插槽..然后,当您查找房间可用时它显示你每个日期什么插槽是免费的..只是一个想法。

+0

感谢您的想法,但我希望避免改变,其中时间被存储在表的格式。如果没有其他解决办法,我会尝试你的方法 – asprin

0

基本上我认为你需要第一个可用的room_no分配给你的abc-xyz时间跨度。所以,你应该获取不在已经预订的集合中的第一个好价值。 示例查询可以是这样的

select room_no 
    from 
    bookings 
    where 
    room_no not in (
    select 
    room_no 
    from bookings 
    where start_time >= 'abc' and end_time <='xyz' 
) 
    limit 1 
+0

不是。这是由用户准备时间表来分配房间。所以这不是第一个可用房间的情况。他可以选择任何他想要的房间。因此,我试图从下拉列表中排除该空间,以便他无法选择它。 – asprin

+0

那么,在这种情况下,答案应该包含在那里:删除限制条款,你可以获得abc的所有可用空间,传入的xyz参数比你可以随心所欲地工作 – brazorf

相关问题