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
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
Create a Range object having the two Time instances that define the range you want, then use the
#cover?
method (if you are on ruby 1.9.x):Note that here I used the explicit method constructor just to make clear that we are using a
Range
instance. You could safely use the Kernel constructor(start..stop)
instead.If you are still on Ruby 1.8, use the method
Range#include?
instead ofRange#cover?
: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.
Again, use
include?
instead ofcover?
for ruby 1.8.xOf course you should upgrade to Ruby 2.0
Here is how I check if an event is tomorrow in Rails 3.x
if time is between one day:
(start_hour..end_hour).include? Time.zone.now.hour
This might read better in several situations and the logic is simpler if you have
18.75
for "18:45"I'm using 3 dots because I don't consider 9:00:00.000am after hours.
Then it's a different topic, but it's worth highlighting that
cover?
comes fromComparable
(liketime < now
), whileinclude?
comes fromEnumerable
(like array inclusion), so I prefer to usecover?
when possible.