Check if a date exists between two dates

I have a model called "Tenant" and it has two attributes Date tenant_from

and tenant_until

.

I want to write a method that checks if it is Date.today

between the two dates given above. I want to do something along these lines:

IF Date.today IS BETWEEN tenant.tenant_from AND tenant.tenant_until DO
  ...
ELSE
  ...       

      

+3


source to share


3 answers


Try



if Time.zone.today.between?(tenant.tenant_from, tenant.tenant_until)
  # YOUR CODE GOES HERE
else
  # YOUR CODE GOES HERE
end

      

+15


source


Just for an alternative solution. You can use a date range cover?

to achieve the same effect.



(tenant.tenant_from .. tenant.tenant_until).cover?(Date.today)

      

+9


source


Class Tenant < ActiveRecord::Base
  def current? #name this what you want, but keep the question mark, since it returns a boolean
    (tenant.tenant_from.to_date .. tenant.tenant_until.to_date).include?(Date.today)
  end
end

      

You now have model logic on the model instance (where it belongs). Then your logic if @tenant.current?

.

+1


source







All Articles