Check whether an event is within a timeframe

Go To StackoverFlow.com

0

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.

2012-04-05 16:01
by JOxBERGER


0

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 ENDTIMEis 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
2012-04-07 21:59
by JOxBERGER
Note that defining one method inside another like that in Ruby is not like it is in JavaScript: you redefine a new getseconds methods in the same scope (not private) each time you invoke betweenTime. You may instead want getseconds = lambda{ |time| … }; timestart = getseconds[timestart] - Phrogz 2012-04-07 22:33
good hint ... just added that. tnhx for advice - JOxBERGER 2012-04-08 09:02
Note that this does not work in the case of 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



1

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
2012-04-05 16:31
by Phrogz
Thanks Phrogz, both solutions seem to work perfect as long as ENDTIME is not after 24:00 like: STARTTIME 19:00 ; ENDTIME 03:00. But with the hep of your code i figuered out how to write a method which does the job. attached her - JOxBERGER 2012-04-07 21:52
Ads