Reputation: 42513
What would the best way be to check if a date is more than a day old, or a year old etc?
Upvotes: 11
Views: 10436
Reputation: 6754
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 month ago", which is the exact opposite of what it means.
before?
and after?
allows you to avoid that extra mental hop when parsing it.
Upvotes: 1
Reputation: 14973
Use ActiveSupport helpers
@date < 1.day.ago
@some_other_date < 2.years.ago
Upvotes: 7
Reputation: 9752
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.
Upvotes: 12