Ruby Check date to know if it falls within a date range

Viewed 56

Background on Application.
Users write test's and their results expire after 5 years.
I need to give them the option to rewrite after 3 years up to 5 years.
I have the expiry_date which is set to 5 years from the date it got created.

My Question
How would I write my statement
I have the ActiveSupport gem
expiry_date is in Date format

if expiry_date < 3.years.ago && expiry_date > 5.years.ago
#Above is checking the date itself which is not right 

What I'm trying to achieve.

expiry_date = Mon, 25 Mar 2024  #Was created on 25 Mar 2019 (Created_date not a field in db)

# Statement check's if it is past 3 years (from created) but less than 5 years(from created)

returns True

#Any where outside the range returns False

My thoughts

Would need to get today's date. Then see where it is in the 5 year time frame and whether it has been between 3 and 5 years.
It would need to be accurate to the day

Any help or advice would be appreciated.

2 Answers

From what I understand, you have a test_date:

test_date = Date.new(2019,3,3)

and you calculate the expiry date adding 5 years (same day/month in 5 years):

expiry_date = test_date + 5.years

or adding exactly 1.825 days (5y * 365d):

expiry_date = test_date + (5*365).days

and now you want to know if that is expired:

today = Date.today
expired = today > expiry_date

or you want to know if it's in the rewrite period (after 3 years up to 5 years):

is_in_rewrite_period = today.between?(test_date + 3.years, expiry_date)

or

is_in_rewrite_period = today.between?(expiry_date - 2.years, expiry_date)

Hope this helps...

You can use ago and in methods

test_date = Date.new(2019, 3, 3)

expiry_date = test_date.in(5.years).to_date

today = Date.today

today.in?(test_date.in(3.years).to_date..expiry_date)
today.in?(expiry_date.ago(2.years).to_date..expiry_date)
Related