How do I check if a time is between two times which are stored as Strings in Ruby on Rails?

1.1k views Asked by At

I want to check if Time.now is between two times (start, end) values which are stored as String in a two columns with the "%I:%M:%S" format.

I get the same format if I use Time.now.strftime("%I:%M:%S") ... but then I'm lost.

3

There are 3 answers

0
Billy Tandaypán On

I solved it, by using "time without time zone" in the columns "start" and "end" format.

Also, to check if the Time.now is between the values stored in the database I use Time.zone.now.

start < Time.zone.now and end > Time.zone.now

0
Pedro Muñoz On

Try something like:

n = Time.now
t1 = Time.parse('1:30:4')
t2 = Time.parse('3:30:4')

n.to_f > t1.to_f and n.to_f < t2.to_f
0
ricks On

You can convert the time to seconds since midnight and compare integers.

 require 'date' 
    
 range_start = 79200 # 10pm (22 * 60 * 60)
 range_end = 82800 # 11pm (23 * 60 * 60)
 time_since_midnight = Time.now.to_i - Date.today.to_time.to_i

 #Check if the the time now is between 10pm and 11pm
 print time_since_midnight.between?(range_start, range_end)