2011-09-28 52 views

回答

13

顯然,這是一個老問題,已經打上了正確的答案,但是,我想發佈可幫助人們通過搜索找到相同問題的答案。

標記爲正確的答案的問題是,您的當前時間可能已經過了午夜,並且在此時,建議的解決方案將失敗。

這是一個考慮到這種情況的替代方案。

now = Time.now 

if (0..8).cover? now.hour 
# Note: you could test for 9:00:00.000 
#  but we're testing for BEFORE 9am. 
#  ie. 8:59:59.999 
    a = now - 1.day 
else 
    a = now 
end 

start = Time.new a.year, a.month, a.day, 21, 0, 0 
b = a + 1.day 
stop = Time.new b.year, b.month, b.day, 9, 0, 0 

puts (start..stop).cover? now 

再次使用include?代替cover?對Ruby 1.8.x的

當然,你應該升級到Ruby 2.0

3

創建具有定義所需的範圍內兩個時刻Range對象,然後使用#cover?方法(如果您是在紅寶石的1.9.x):

now = Time.now 
start = Time.gm(2011,1,1) 
stop = Time.gm(2011,12,31) 

p Range.new(start,stop).cover? now # => true 

請注意,在這裏我使用了顯式方法構造函數來明確我們使用的是一個Range實例。您可以安全地使用內核構造函數(start..stop)

如果你仍然對Ruby 1.8中,使用的方法Range#include?,而不是Range#cover?

p (start..stop).include? now 
+0

爲什麼明確的'Range.new'而不是'(start..stop).cover? now'? –

+0

我得到一個錯誤未定義的方法'封面?'對於星期六01 01 00:00:00 UTC 2011..Sat Dec 31 00:00:00 UTC 2011:範圍 \t from(irb):11 \t from /opt/local/lib/ruby/1.8/date。rb:1770 –

+1

@AmalKumarS:你可能在1.8,'cover?'是在1.9中引入的。 –

2
require 'date' 

today = Date.today 
tomorrow = today + 1 

nine_pm = Time.local(today.year, today.month, today.day, 21, 0, 0) 
nine_am = Time.local(tomorrow.year, tomorrow.month, tomorrow.day, 9, 0, 0) 

(nine_pm..nine_am).include? Time.now #=> false 
+1

這是如何標記爲正確的?如果當前時間_已過午夜,則「今日+ 1」將是第二天。如果當前時間在00:00到09:00之間,則需要額外進行檢查,然後相應地構建您的範圍。 – ocodo

+0

我想它被標記爲正確的,因爲有些人能夠從提供的例子中推斷出他們需要的東西。 –

0

這可能讀在幾種情況下更好的邏輯是,如果簡單你有18.75爲 「18:45」

def afterhours?(time = Time.now) 
    midnight = time.beginning_of_day 
    starts = midnight + start_hours.hours + start_minutes.minutes 
    ends = midnight + end_hours.hours + end_minutes.minutes 
    ends += 24.hours if ends < starts 
    (starts...ends).cover?(time) 
end 

我使用3點,因爲我不考慮在幾小時後的9點00分00分00秒。

那麼它是一個不同的主題,但它是值得強調的是cover?來自Comparable(如time < now),而include?來自Enumerable(如數組包含),所以我更喜歡在可能時使用cover?

0

這是我如何檢查,如果事件是明天的Rails 3.x的

(event > Time.now.tomorrow.beginning_of_day) && (event < Time.now.tomorrow.end_of_day) 
1

如果時間爲一天之間:

(start_hour..end_hour).INCLUDE? Time.zone.now.hour

相關問題