2011-01-20 191 views
3

我现在有定义为我的RubyOnRails数据库2个时间戳字段:时间戳在时间戳范围内进行比较?

starttime:timestamp 
endtime:timestamp 

我想要写在我的控制器的简单功能,将采取当前时间返回TRUE,如果它处于范围的开始时间& endtime

我该怎么做?

+0

你真的使用时间戳,而不是日期时间?你想让你的测试具有包容性或排他性吗? – jdl 2011-01-20 21:34:31

回答

4

假设你有这些的模型设定,你可以做这样的事情:

def currently_in_range(model) 
    now = DateTime.now 
    model.starttime < now && now < model.endtime 
end 

你或许应该把它放在模型类,虽然。喜欢的东西:

class Thing < ActiveRecord::Base 
    ... 
    def current? 
    now = DateTime.now 
    starttime < now && now < endtime 
    end 
    ... 
end 

然后在你的控制器,你可以叫model.current?

+1

我会`def current?(now = DateTime.now)`让你传入不同的“现在”进行测试或历史审计。否则,你就对了。 – 2011-01-20 22:34:25

1
class YourModel < ActiveRecord::Base 
    def active? 
    (starttime..endtime) === Time.now.to_i 
    end 
end 

class YourController < ApplicationController 
    def show 
    @your_model = YourModel.first 
    @your_model.active? 
    end 
end 
+0

感谢您的回应! – unicornherder 2011-01-20 22:24:52