Ruby time range?

I want to know if the time belongs to a schedule or another.

In my case, this is for calculating if the time is in the night schedule or in the regular schedule.

I came to this solution:

NIGHT = ["21:00", "06:00"]
def night?( date )
  date_str = date.strftime( "%H:%M" )
  date_str > NIGHT[0] || date_str < NIGHT[1]
end

But I think that it is not very elegant, and also works only for this particular case, and not for each time range.

(I found several similar questions: SO, but they all refer to date ranges without time ranges)

Update

The solution should work in random time ranges, not only for this particular one. Let them talk:

"05:00"-"10:00"
"23:00"-"01:00"
"01:00"-"01:10"
+5
source share
2 answers

This is actually more or less how I would do it, except maybe a little more concise:

def night?( date )
    !("06:00"..."21:00").include?(date.strftime("%H:%M"))
end

or, if the boundaries of your schedule may remain in the hour:

def night?(date)
    !((6...21).include? date.hour)
end

... - , " 6 21 , 21".

edit: (, , ) :

class TimeRange
    private

    def coerce(time)
        time.is_a? String and return time
        return time.strftime("%H:%M")
    end

    public

    def initialize(start,finish)
        @start = coerce(start)
        @finish = coerce(finish)
    end

    def include?(time)
        time = coerce(time)
        @start < @finish and return (@start..@finish).include?(time)
        return !(@finish..@start).include?(time)
    end
end

:

irb(main):013:0> TimeRange.new("02:00","01:00").include?(Time.mktime(2010,04,01,02,30))
=> true
irb(main):014:0> TimeRange.new("02:00","01:00").include?(Time.mktime(2010,04,01,01,30))
=> false
irb(main):015:0> TimeRange.new("01:00","02:00").include?(Time.mktime(2010,04,01,01,30))
=> true
irb(main):016:0> TimeRange.new("01:00","02:00").include?(Time.mktime(2010,04,01,02,30))
=> false

, .

+10

Rails 3.2 Time.all_day . , , . .

+1

All Articles