【发布时间】:2011-09-28 09:01:13
【问题描述】:
我需要检查我当前的时间是否在指定的时间间隔(今晚晚上 9 点和明天早上 9 点)之间。如何在 Ruby on Rails 中做到这一点。
提前致谢
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 datetime
我需要检查我当前的时间是否在指定的时间间隔(今晚晚上 9 点和明天早上 9 点)之间。如何在 Ruby on Rails 中做到这一点。
提前致谢
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 datetime
显然这是一个老问题,已经标有正确答案,但是,我想发布一个答案,可以帮助人们通过搜索找到相同的问题。
答案标记为正确的问题是,您当前的时间可能已经过了午夜,在那个时间点,建议的解决方案将失败。
这是考虑到这种情况的替代方案。
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
同样,对于 ruby 1.8.x,使用 include? 而不是 cover?
当然你应该升级到 Ruby 2.0
【讨论】:
创建一个 Range 对象,其中包含定义所需范围的两个 Time 实例,然后使用 #cover? 方法(如果您使用的是 ruby 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
【讨论】:
Range.new 而不是(start..stop).cover? now?
cover? 是在 1.9 中引入的。
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
【讨论】:
today + 1 将是第二天。您需要额外检查当前时间是否在 00:00 到 09:00 之间,然后相应地构建您的范围。
如果时间在一天之间:
(start_hour..end_hour).include? Time.zone.now.hour
【讨论】:
这在几种情况下可能会更好读,如果您有 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.000。
那是另外一个话题了,但是值得强调的是cover?来自Comparable(比如time < now),而include?来自Enumerable(比如数组包含),所以我更喜欢使用@ 987654328@ 尽可能。
【讨论】:
这是我在 Rails 3.x 中检查明天是否有事件的方法
(event > Time.now.tomorrow.beginning_of_day) && (event < Time.now.tomorrow.end_of_day)
【讨论】: