Tuesday, April 5, 2011

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

From stackoverflow
  • This seems like the right thing to do. It's just a math equation, not really that messy.

  • One thing you can do to make it more readable is:

    ((Time.zone.now - myActiveRecord.visit_date) / 1.day).to_i
    

0 comments:

Post a Comment