我试图创建一个条件,如果@challenge.deadline
(这是Date
)在上周(即最后7天)内,那么 x < / em>,否则 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
答案 0 :(得分:7)
当
@challenge.deadline
是过去7天内发生的日期时,如何触发条件?
“在过去7天内”描述的范围来自:
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.days
代替today - 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
答案 1 :(得分:-1)
if @challenge.deadline.to_date < 1.week.ago.to_date
do X
else
do Y
end