Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if time is between two times ruby

I'm looking to check if the DateTime.now is between 2 particular date and times on Ruby on Rails.

I can't seem to figure it out

 def closed?
  (DateTime.now > DateTime.new(2018, 6, 28, 13, 00, 00)) && (DateTime.now < DateTime.new(2018, 6, 28, 14, 00, 00))
 end
like image 321
Jim B Avatar asked Jun 28 '18 12:06

Jim B


Video Answer


2 Answers

I would use the between?(min, max) function from ActiveSupport:

def closed?
  DateTime.now.between?(DateTime.new(2018, 6, 28, 13, 00, 00), DateTime.new(2018, 6, 28, 14, 00, 00))
end
like image 135
cseelus Avatar answered Oct 27 '22 09:10

cseelus


You can use cover? method for that

now = DateTime.now
start = DateTime.new(2018, 6, 28, 13, 00, 00)
stop =  DateTime.new(2018, 6, 28, 14, 00, 00)
p (start..stop).cover? now

Hope it will help you :)

like image 12
Anshul Avatar answered Oct 27 '22 09:10

Anshul