检查提供的日期时间值是否介于特定时间间隔之间

时间:2012-10-08 12:02:21

标签: php mysql

方案

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)*/

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

我正在研究类似的东西,也许更简单的代码编码方式不会使用时间而是时间段?我想这样做的方式是桌面预订(日期,插槽ID,房间)桌位(可能有插槽ID和TIME),每次预订使用一定数量的插槽..然后当你寻找房间可用时它会显示每个日期的插槽是免费的..只是一个想法。

答案 2 :(得分: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