I want determine if a date is within the current academic year. In order to do that, I've written a function to determine the current academic year. Is there a better way to do this?
# returns start and end date of current academic year
def academic_year
# assumption: an academic year is from sept 1st untill sept 1st
start_date = Date.parse "#{Time.current.year}-09-01"
end_date = Date.parse "#{Time.current.year+1}-09-01"
if Date.today < start_date
start_date = Date.parse "#{Time.current.year-1}-09-01"
end_date = Date.parse "#{Time.current.year}-09-01"
end
{start: start_date, end: end_date}
end
In Ruby you would use Range#cover?
# see https://api.rubyonrails.org/classes/Date.html
start = Date.current.change(month: 9, day: 1)
academic_year = start..start.advance(years: 1)
academic_year.cover?(Date.current.change(month: 6, day: 15)) # false
academic_year.cover?(Date.current.change(month: 10, day: 2).advance(years: 2)) # false
academic_year.cover?(Date.current.change(month: 10, day: 2)) # true
But usually you should be querying by date in the database in which case you pass a range to .where
to create a BETWEEN query:
Order.where(placed: 2.years.ago..Time.current)
# SELECT "orders".* FROM "orders" WHERE "orders"."placed" BETWEEN $1 AND $2 LIMIT $3