Timestamp compared to a time range?

There are currently 2 timestamp fields in my RubyOnRails database, which are defined as:

starttime:timestamp
endtime:timestamp

I want to write a simple function in my controller that will take the current time and return TRUE if it is in the range of start and end times .

How can i do this?

+3
source share
2 answers

Assuming you have a model setup for them, you can 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 a model class. Sort of:

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

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

+4
source
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
+1
source

Source: https://habr.com/ru/post/1786776/


All Articles