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

后端 未结 3 1643
无人共我
无人共我 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 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.

提交回复
热议问题