本文介绍了我如何检查当前在Ruby on Rails上的晚上9点到9点(明天)之间的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查我当前的时间是否在指定的时间间隔之间(明天晚上9点到明天上午9点)。在Ruby on Rails中如何做到这一点。



提前感谢

解决方案

很明显,这是一个已经标有正确答案的旧问题,但是我想发布一个可以帮助用户通过搜索找到相同问题的答案。



答案标记正确的问题是,您当前的时间可能是午夜过后,在该时间点,提出的解决方案将失败。



  now = Time.now 

如果(0..8)。 now.hour
#注意:您可以测试9:00:00.000
#,但我们正在上午9点进行测试。
#ie。 8:59:59.999
a = now - 1.day
else
a = now
end

start = Time.new a.year,a。月,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?现在

再次,使用 include?而不是 cover? for ruby​​ 1.8.x




I need to check whether my current times is between the specified time interval (tonight 9pm and 9am tomorrow). How can this be done in Ruby on Rails.

Thanks in advance

解决方案

Obviously this is an old question, already marked with a correct answer, however, I wanted to post an answer that might help people finding the same question via search.

The problem with the answer marked correct is that your current time may be past midnight, and at that point in time, the proposed solution will fail.

Here's an alternative which takes this situation into account.

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

Again, use include? instead of cover? for ruby 1.8.x

这篇关于我如何检查当前在Ruby on Rails上的晚上9点到9点(明天)之间的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 18:41