How to check if date falls in a time frame of 3 years from date and 5 years

Viewed 69

My main problem is how would you write the "3 years/ 5 years" I have the date which is the expiry_date. I need to know if this date is between 3 and 5 years old. Hope the question makes sense :)

if expiry_date > 3 years && expiry_date < 5 years

The expiry_date is just a Date format

3 Answers

Just Ruby (so no ActiveSupport):

require 'date'

today = Date.today
a_date = Date.new(2019,1,1)
p a_date.between?(today.prev_year(5), today.prev_year(3)) # => true

You can use the ruby cover? method with ActiveSupport gem to validate the range:

require "active_support/core_ext/integer/time"

(5.years.ago..3.years.ago).cover?(expiry_date)

Using ActiveSupport gem excluding begin and end

require "active_support/core_ext/integer/time"

expiry_date < 3.years.ago && expiry_date > 5.years.ago

If you need to include begin and end of this range

(5.years.ago..3.years.ago).include?(expiry_date)
expiry_date.between?(5.years.ago, 3.years.ago)

There is also in? method in ActiveSupport

expiry_date.in?(5.years.ago..3.years.ago)
Related