计算 ActiveSupport:TimeWithZone 在最“红宝石"中的天数差异风格? [英] Calculate difference in days ActiveSupport:TimeWithZone in the most "rubyish" style?

查看:38
本文介绍了计算 ActiveSupport:TimeWithZone 在最“红宝石"中的天数差异风格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我感觉有人会向我指出另一个可以回答这个问题的问题,但我一直在寻找这个简单的问题,但没有运气.

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.

我有一个带有日期时间属性的 Activerecord.它作为 ActiveSupport:TimeWithZone 返回.我知道我无法将它与 DateTime.now 进行比较,因为它不包含区域,所以我需要使用 Time.zone.有道理.

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.

我想知道的是,有没有比将结果减去和除以 86400 更干净"的方法?

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

这就是我所做的:

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

有效,但似乎不是红宝石,我觉得我错过了一些东西.我应该投射、比较或转换其他路线,还是这真的是在 Rails 中执行此操作的典型方法?感谢任何提示或指向已经涵盖此内容的问题的链接.

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.

谢谢

推荐答案

为了使其更具可读性,您可以做的一件事是:

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

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

实际上你可以去掉一组括号:

Actually you can get rid of one set of the brackets with:

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

这篇关于计算 ActiveSupport:TimeWithZone 在最“红宝石"中的天数差异风格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆