Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 luck 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

like image 599
Nick Avatar asked Jun 16 '10 00:06

Nick


1 Answers

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 
like image 93
Jakub Hampl Avatar answered Oct 19 '22 18:10

Jakub Hampl