如果日期小于一周前有条件?

If date is less than a week ago conditional?

我正在尝试创建一个条件,如果 @challenge.deadline(即 Date)在上周(即过去 7 天)内,则执行 x,否则做 y.

我试过了:

if @challenge.deadline < 1.week.ago #2017-03-03 01:52:13 -0500
if @challenge.deadline < 7.days.ago.to_date #2017-03-03
if @challenge.deadline < Date.current-7.days #2017-03-03
# All these come up false since I guess it sees 06 as more than 03, but I want the conditional to be based on date such as 06 is less than 7 days ago and therefore should be true

在这个例子中 @challenge.deadline 等于 2017-03-06

if @challenge.deadline.to_date < 1.week.ago.to_date
    do X
else
    do Y
end

how can I trigger the conditional when @challenge.deadline is a date that has happened within the last 7 days?

"within the last 7 days" 描述的范围从:

Date.current - 7 #=> Fri, 03 Mar 2017

至:

Date.current     #=> Fri, 10 Mar 2017

要检查 @challenge.deadline 是否在这些范围内,您可以使用 between?:

today = Date.current
if @challenge.deadline.between?(today - 7, today)
  # within last 7 days
else
  # either before of after
end

除了today - 7,您还可以使用today - 7.daystoday - 1.week

或者,使用实际范围:

today = Date.current
last_week = (today - 7)..today

if last_week.cover?(@challenge.deadline)
  # ...
else
  # ...
end

如果你经常需要这个,你也可以考虑打补丁 Date:

class Date
  def within_last?(duration, date = Date.current)
    between?(date - duration, date)
  end
end

并通过以下方式检查:

if @challenge.deadline.within_last?(1.week)
  # ...
else
  # ...
end