2012-10-08 61 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