I have a model for timeframes defined by:
STARTTIME: HH:MM
ENDTIME: HH:MM
Now i need to do a query with a given time ACTUALTIME
in the format HH:MM, and check whether ACTUALTIME
is within the any of my given Timeframes defined by: STARTTIME
and ENDTIME
.
Since the Ruby time object when defined only by the Hour and Minute is always represented by a date, i wonder wether there is any possibility to query something like: Is 13:40 between 11:00 and 15:00 without taking the date part into account.
Thank Phrogz advice I figured out how to write a method which can compare two times independent from their date. It works fine for me even when the ENDTIME
is after 24:00
def betweenTime(timestart, timeend, timecheck)
getseconds = lambda{ |time| time.hour*60*60 + time.min*60 + time.sec}
timestart = getseconds[timestart]
timeend = getseconds[timeend]
timecheck = getseconds[timecheck]
if (timeend-timestart) < 0
timeend = timeend + (60*60*24) # add seconds for one day if timeend is after 24:00
end
timecheck.between?(timestart, timeend)
end
timestart: 21:30
timeend: 04:30
timecheck: 02:00
Due to the fact that you're not altering timecheck
if timeend
is after 24:00, and therefore in this case it's numeric value is smaller than timestart
AND smaller than timeend
resulting a false
return value.. - Mikey S. 2014-01-13 11:52
If your HH:MM
are strings, and they are always zero-padded (e.g. "03:08") then you can just use a simple string comparison:
irb:02> first = "03:17"; last = "11:54"
#=> "11:54"
irb:03> range = first..last
#=> "03:17".."11:54"
irb:04> range.include? "00:00"
#=> false
irb:05> range.include? "03:50"
#=> true
irb:06> range.include? "03:09"
#=> false
irb:07> range.include? "12:17"
#=> false
irb:08> range.include? "11:17"
#=> true
If your STARTTIME and ENDTIME are coming into Ruby as instances of Time
then you can either write a method to convert them to strings (my_time.strftime('%H:%M')
) or you can simply write a comparator:
# Returns true if hour:min is between the times in t1 and t2
def between(hour,min,t1,t2)
t1.hour<=hour && hour<=t2.hour && t1.min<=min && min<=t2.min
end
getseconds
methods in the same scope (not private) each time you invokebetweenTime
. You may instead wantgetseconds = lambda{ |time| … }; timestart = getseconds[timestart]
- Phrogz 2012-04-07 22:33