I have a feeling someone is going to point me to another question that answers this but I\'ve been searching with no luck over this simple issue.
I have a Activereco
Rails actually has a method built in for just this sort of thing.
checkout #time_ago_in_words
So, for the original case...
((Time.zone.now - myActiveRecord.visit_date)/86400).to_i
vs
time_ago_in_words(myActiveRecord.visit_date)
I know this question is a bit dated but I came across it while Googling for a similar problem. In my case I needed to know the difference in whole days on a macro and micro scale.
For example, I needed my code to be able to tell me that Dec 31, 2010 is 366 days before Jan 1, 2012 and that Dec 31, 2010 23:59 is 1 day away from Jan 1, 2011 00:00. The method above works in the former but in the case of the latter, it says they are 0 days apart.
What I ended up doing was using Ruby's Date
class to do the math for me. Using the code above my method looks like this:
(Time.zone.now.to_date - myActiveRecord.visit_date.to_date).to_i
This will work with inputs in Time
or DateTime
due to the conversion. Another possible solution would be to first call beginning_of_day
on each of the Times
or DateTimes
but in my case, the minutes were important.
One thing you can do to make it more readable is:
((Time.zone.now - myActiveRecord.visit_date) / 1.day).to_i
Edit:
Actually you can get rid of one set of the brackets with:
(Time.zone.now - myActiveRecord.visit_date).to_i / 1.day