What would the best way be to check if a date is more than a day old, or a year old et开发者_JS百科c?
See this question: comparision of date in ruby The compare to a value like
1.day.ago
1.month.ago
1.year.ago
Using these produces the following output:
Loading development environment (Rails 3.0.7)
ruby-1.9.2-p180 :001 > 1.year.ago
=> Thu, 27 May 2010 17:45:25 UTC +00:00
ruby-1.9.2-p180 :002 > 1.month.ago
=> Wed, 27 Apr 2011 17:45:32 UTC +00:00
ruby-1.9.2-p180 :003 > 1.day.ago
=> Thu, 26 May 2011 17:45:36 UTC +00:00
ruby-1.9.2-p180 :004 >
and see if that works.
Use ActiveSupport helpers
@date < 1.day.ago
@some_other_date < 2.years.ago
if the_date < 1.day.ago or the_date < 1.year.ago
Try:
a_date > 1.day.ago
a_date > 1.year.ago
Rails 6 now has more idiomatic Time comparitors that you can use:
date.before?(1.day.ago)
date.after?(1.week.ago)
Which I think is much nicer that the standard comparison operators.
As Jan Klimo mentions in a comment above, you'd naturally read last_login > 1.month.ago
as "last_login
is more than 1 day ago", which is the exact opposite of what it means.
before?
and after?
allows you to avoid that extra mental hop when parsing it.
精彩评论