2015-04-30 40 views
1

我試過在網上搜索這個,但是我會空白。如果在2小時之間,跨越午夜

基本上,我有這個:

If Hour(Now()) >= 8 And Hour(Now()) < 17 then response.write("TEST") 

這將顯示上午8點到下午5點之間的單詞測試 - 但我希望它能夠跨午夜。

我希望能夠說,如果時間在晚上10點到凌晨4點之間,那就表明一些事情。

我正在使用經典的ASP - 有沒有人可以幫助我 - 我瘋了!

目前,我只是把陳述兩次 - 就像這樣;

If Hour(Now()) >= 22 And Hour(Now()) < 23 then response.write("TEST") 
If Hour(Now()) >= 0 And Hour(Now()) < 4 then response.write("TEST") 

這是有效的,但必須有辦法做到這一點,而不必做2條語句?

回答

0

好了 - 所以我不得不寫我自己的函數:

function timeLimit(startTime, endTime) 
    h=hour(now()) 
    if startTime>endTime then 
     if h>=startTime or h<=endTime then 
      timeLimit=True 
     else 
      timeLimit=False 
     end if 
    elseif startTime<endTime then 
     if h>=startTime and h<=endTime then 
      timeLimit=True 
     else 
      timeLimit=False 
     end if 
    else 
     if h=startTime then 
      timeLimit=True 
     else 
      timeLimit=False 
     end if 
    end if 
end function 

這將制定出如果啓動時間數是大於結束時間數 - 如果是的話,就必須跨越午夜。它會採取相應的行動 - 根據投入情況返回真或假。

所以,如果我想顯示晚上8點和下午2點之間的話的「Hello World」,我這樣做:

if timeLimit(20, 14) then Response.Write "Hello World" 

如果我想表現的「Hello World」上午8點到下午5點之間,我會使用此:

if timeLimit(8, 17) then Response.Write "Hello World" 

如果我只是想表現的 「Hello World」 下午4點,我會用這樣的:

if timeLimit(16, 16) then Response.Write "Hello World" 

我希望這能幫助未來的人。

2

您可以嘗試

Dim h 
    h = Hour(Now()) 
    If h >= 22 Or h < 4 Then Response.Write("Test") 

或者

If Hour(DateAdd("h", 2, Now)) < 6 Then Response.Write("test") 

或者

Select Case Hour(Now()) 
    Case 22,23,0,1,2,3 : Response.Write("test") 
End Select 

編輯適應評論

Option Explicit 

WScript.Echo CStr(InTime("02:00", "18:00")) 
WScript.Echo CStr(InTime("18:00", "22:00")) 
WScript.Echo CStr(InTime("15:00", "04:00")) 

Function InTime(ByVal startTime, ByVal endTime) 
Dim thisTime 
    thisTime = CDate(FormatDateTime(Now(), vbShortTime)) 
    startTime = CDate(startTime) 
    endTime = CDate(endTime) 
    If endTime < startTime Then endTime = DateAdd("h", 24, endTime) 
    InTime = (thisTime >= startTime And thisTime <= endTime) 
End Function 
+0

這些都是好主意......他們會以解決問題的方式來解決問題,但我真的只需要將一個開始和結束時間作爲變量,然後讓代碼完成工作。我想知道如果一個功能是要走的路? –

+1

@BlindTrevor,答案已更新。根據需要調整。 –