Comparing date dates; date greater than or equal to days ago

The date in my database looks like this: 2012-07-23

I am trying to see if the date is older than 7 days ago and less than 14 days ago, or see if the date is more than 14 days ago, but I’m out of luck ..

Here is my code:

def progress_report_status_check(date)
    progress_date = date.to_date
    seven_days = 7.days.ago.to_date
    fourteen_days = 14.days.ago.to_date

    if seven_days > (progress_date - 7.days.ago.to_date) or (progress_date - 14.days.ago.to_date) < fourteen_days
      "due"
    elsif (progress_date - 14.days.ago.to_date) > fourteen_days 
      "overdue"
    end 
  end
+5
source share
2 answers
def progress_report_status_check(progress_date) # Pass in a date
  if (progress_date < Date.now-14.days)
    "overdue"
  elsif (progress_date < Date.now-7.days) 
    "due"
  end 
end

or (less readable)

def progress_report_status_check(progress_date) # Pass in a date
  (progress_date < Date.now-14.days) ? "overdue" : ((progress_date < Date.now-7.days) ? "due" : "") : "" 
  end 
end

Depending on your use, you can create named scopes, for example:

scope :overdue where(:progress_date < Date.now-14.days)
scope :due where(:progress_date < Date.now-7.days)

Then your calling code might be something like

def progress_report_status_check(progress_date) # Pass in a date
  self.overdue? ? "overdue" : self.due? ? : "due" : ""
  end 
end
+5
source

The accepted answer uses the undefined method in the Date class. It's right:

def progress_report_status_check(progress_date) # Pass in a date
  if (progress_date < (Date.today-14.days))
    "overdue"
  elsif (progress_date < (Date.today-7.days)) 
    "due"
  end 
end
+5
source

All Articles