使用Rails计算Postgres中DateTime列的确切持续时间



我正在努力获得比持续时间"大约2小时"更准确的输出。

目前,我们正在使用time_ago_in_words

这看起来像.erb 中的以下函数

Duration: <%= time_ago_in_words(@sitrep.incident.created_at) %>
# I found the gem `dotiw` which lets me use:
distance_of_time_in_words(@sitrep.incident.created_at)
# However, there is an error and I can't get either to work in irb

这是我在尝试两者时的控制台输出。感谢提供的所有帮助

[1] pry(main)> include ActionView::Helpers
=> Object
[2] pry(main)> t = Sitrep.last.incident.created_at
# redacted output    
=> Wed, 28 Nov 2018 21:47:45 UTC +00:00
[3] pry(main)> t
=> Wed, 28 Nov 2018 21:47:45 UTC +00:00
[4] pry(main)> time_ago_in_words(t)
=> "<span class="translation_missing" title="translation missing: en.weeks">Weeks</span>, <span class="translation_missing" title="translation missing: en.days">Days</span>, <span class="translation_missing" title="translation missing: en.hours">Hours</span>, and <span class="translation_missing" title="translation missing: en.minutes">Minutes</span>"
[5] pry(main)> distance_of_time_in_words(t)
NoMethodError: undefined method `seconds' for Wed, 28 Nov 2018 21:47:45 UTC +00:00:Time
Did you mean?  send
Did you mean?  send
from /Users/mmowris/.rbenv/versions/2.3.8/lib/ruby/gems/2.3.0/gems/activesupport-4.2.7.1/lib/active_support/time_with_zone.rb:371:in `method_missing'
[6] pry(main)>

第一种方法time_ago_in_words适用于我们的rails应用程序。这个.erb文件发送一封电子邮件,输出看起来像:

Duration: about 2 hours

关于如何进行有什么想法吗?为什么这在我们的rails项目中有效,而在irb中无效?为什么我不能让dotiw使用相同的输入?为什么我不能让taiw使用生产中使用的相同输入?

谢谢!

使用帮助程序,而不是手动包含帮助程序

> helper.time_ago_in_words(2.hours.ago, true)
=> "2 hours" 
> helper.time_ago_in_words((2.hours.ago + 5.seconds), true)
=> "1 hour, 59 minutes, and 55 seconds" 

最新更新