Rails新手问题:如何检查给定日期是否在现在365天内?
给定从db格式2012-02-12 23:59:30
格式的日期时间,我该如何检查它是否在现在365天内?
我试过以下,但没有奏效:<%= expedite - Date.today %>
Rails新手问题:如何检查给定日期是否在现在365天内?
给定从db格式2012-02-12 23:59:30
格式的日期时间,我该如何检查它是否在现在365天内?
我试过以下,但没有奏效:<%= expedite - Date.today %>
您可以添加的天数Date.today
,看看日期或之前:
if expedite <= (Date.today + 365.days)
# it's within 365 days
end
你可以也可以用Date.today + 1.year
代替,但技术上这将增加365.25天,而不是365.
此解决方案占用了一年多前的日期。
if (Date.today-365..Date.today+365).include? expedite
# it's really within 365 days
end
将365或365天添加到日期可能不是您想要的。 在闰年:
require 'date'
start = Date.new(2012,2,1)
puts start + 365 #=> 2013-01-31
# Human "one year from now":
puts start >> 12 #=> 2013-02-01
假设你的意思是“1从现在起一年”,由365天,因为检查365天不考虑闰年:
if expedite <= 1.year.from_now
# ...
else
# ...
end
非常简洁的解决方案! – user1049097