开发者

Calculate difference in days ActiveSupport:TimeWithZone in the most "rubyish" style?

I have a feeling someone is going to point me to another question that answers this but I've been searching with no l开发者_如何学运维uck over this simple issue.

I have a Activerecord with a datetime property. It returns as an ActiveSupport:TimeWithZone. I know I can't compare that to DateTime.now because that doesn't include a zone so I need to use Time.zone. Makes sense.

What I'm wondering is stylewise is there a "cleaner" way to do this than subtracting and dividing the result by 86400?

Here's what I do:

((Time.zone.now - myActiveRecord.visit_date)/86400).to_i

Works but seems un-rubyish and I feel like I'm missing something. Should I be casting, comparing or converting some other route or is this really the typical way to do this in rails? Appreciate any tips or a link to a question that already covers this.

Thank you


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


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.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜