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

后端 未结 3 1625
无人共我
无人共我 2020-12-23 16:50

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

相关标签:
3条回答
  • 2020-12-23 16:59

    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 讨论(0)
  • 2020-12-23 17:01

    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.

    0 讨论(0)
  • 2020-12-23 17:15

    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
    
    0 讨论(0)
提交回复
热议问题