10

我有一个错误地生成它的代码,我认为必须有更好的方法来检查时间 > 9.30 am 和时间 < 4 pm 任何想法都受到高度赞赏。

def checkTime

   goodtime=false
   if(Time.now.hour>9 and Time.now.min>30) then

     if(Time.now.hour<16) then
       goodtime=true

     else
       # do nothing
     end
   elsif Time.now.hour>9 and Time.now.hour<16 then
     goodtime=true

   else
      # do nothing
   end
   return goodtime

 end
4

4 回答 4

7
t = Time.now

Range.new(
  Time.local(t.year, t.month, t.day, 9),
  Time.local(t.year, t.month, t.day, 16, 30)
) === t
于 2012-04-10T15:46:15.340 回答
5
def check_time(t=Time.now)
  early = Time.new(t.year, t.month, t.day, 9, 30, 0, t.utc_offset)
  late  = Time.new(t.year, t.month, t.day, 16, 0, 0, t.utc_offset)
  t.between?(early, late)
end
于 2012-04-10T15:49:55.913 回答
4

只是:

def checkTime
  return ((Time.now.hour * 60) + Time.now.min) >= 570 && ((Time.now.hour * 60) + Time.now.min) < 960
end
于 2012-04-10T14:51:22.063 回答
4

在混合版本环境中工作并需要这种确切的方法,这就是我在代码中输入的内容:

if RUBY_VERSION == "1.9.3"
  def check_time(starthour,endhour,t=Time.now)
    early = Time.new(t.year, t.month, t.day, starthour, 0, 0)
    late  = Time.new(t.year, t.month, t.day, endhour, 0, 0)
    t.between?(early, late)
  end
elsif RUBY_VERSION == "1.8.7"
  def check_time(starthour,endhour,t=Time.now)
    early = Time.local(t.year, t.month, t.day, starthour, 0, 0)
    late  = Time.local(t.year, t.month, t.day, endhour, 0, 0)
    t.between?(early, late)
  end
end
于 2013-09-16T12:21:37.220 回答