Mo.
Mo.

Reputation: 42513

Checking if date is over a day old, over a year old etc?

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

Answers (5)

anotherdave
anotherdave

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

edgerunner
edgerunner

Reputation: 14973

Use ActiveSupport helpers

@date < 1.day.ago

@some_other_date < 2.years.ago

Upvotes: 7

Jits
Jits

Reputation: 9728

Try:

a_date > 1.day.ago
a_date > 1.year.ago

Upvotes: 1

Sam Coles
Sam Coles

Reputation: 4043

if the_date < 1.day.ago or the_date < 1.year.ago

Upvotes: 3

Devin M
Devin M

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

Related Questions