A date in my database looks like this: 2012-07-23
我的数据库中的日期如下所示: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 greater than 14 days ago, but am having no luck..
我想看看日期是否超过7天前且不到14天前或者看看日期是否大于14天前,但我没有运气..
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
2 个解决方案
#1
7
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 usage you may want to create named scopes, say:
根据您的使用情况,您可能希望创建命名范围,例如:
scope :overdue where(:progress_date < Date.now-14.days)
scope :due where(:progress_date < Date.now-7.days)
Then your calling code can be something like
然后你的调用代码就像是
def progress_report_status_check(progress_date) # Pass in a date
self.overdue? ? "overdue" : self.due? ? : "due" : ""
end
end
#2
6
The accepted answer uses an undefined method on the Date class. This is correct:
接受的答案在Date类上使用未定义的方法。这是对的:
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
#1
7
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 usage you may want to create named scopes, say:
根据您的使用情况,您可能希望创建命名范围,例如:
scope :overdue where(:progress_date < Date.now-14.days)
scope :due where(:progress_date < Date.now-7.days)
Then your calling code can be something like
然后你的调用代码就像是
def progress_report_status_check(progress_date) # Pass in a date
self.overdue? ? "overdue" : self.due? ? : "due" : ""
end
end
#2
6
The accepted answer uses an undefined method on the Date class. This is correct:
接受的答案在Date类上使用未定义的方法。这是对的:
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