3

I currently have 2 timestamp fields in my RubyOnRails database defined as:

starttime:timestamp
endtime:timestamp

I want to write a simple function in my controller which will take the current time and return TRUE if it lies in the range of the starttime & endtime.

How I can do this?

JJJ
  • 32,902
  • 20
  • 89
  • 102
dpigera
  • 3,339
  • 5
  • 39
  • 60
  • You're really using timestamp and not datetime? Do you want your test to be inclusive or exclusive? – jdl Jan 20 '11 at 21:34

2 Answers2

4

Assuming you have an model setup for these, you could do something like this:

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

You should probably put it in the model's class, though. Something like:

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

Then in your controller you can just call model.current?

Joel Meador
  • 2,586
  • 2
  • 19
  • 24
  • 1
    I'd do `def current?(now=DateTime.now)` to allow you to pass in a different "now" for testing or historical auditing. Otherwise you're right on. – Jacob Mattison Jan 20 '11 at 22:34
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
grobie
  • 148
  • 4