我如何在Ruby on Rails中检查今晚9点到9点(明天)之间的当前时间
我需要检查当前时间是否在指定的时间间隔(今晚9点到明天上午9点)之间。 如何在Ruby on Rails中完成。
提前致谢
显然这是一个老问题,已经标记了正确的答案,但是,我想发布一个答案,可以帮助人们通过搜索找到相同的问题。
答案标记正确的问题是您当前的时间可能已经过了午夜,并且在该时间点,建议的解决方案将失败。
这是考虑到这种情况的另一种选择。
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
创建一个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#include?
而不是Range#cover?
:
p (start..stop).include? now
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
如果时间在一天之间:
(start_hour..end_hour).INCLUDE? Time.zone.now.hour
这可能在几种情况下读得更好,如果你的“18:45”有18.75
,逻辑会更简单
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个点,因为我不考虑下class后的9:00:00.000。
那么这是一个不同的主题,但值得强调的是cover?
来自Comparable
(如time < now
), include?
来自Enumerable
(如数组包含),所以我更喜欢使用cover?
如果可能。
以下是我如何检查Rails 3.x中是否有明天的事件
(event > Time.now.tomorrow.beginning_of_day) && (event < Time.now.tomorrow.end_of_day)