【问题标题】:Calculating exact duration time from a DateTime column in Postgres using Rails使用 Rails 从 Postgres 中的 DateTime 列计算确切的持续时间
【发布时间】:2019-05-11 22:54:23
【问题描述】:

我试图在持续时间内获得比“大约 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 使用与生产环境相同的输入?

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby irb pry rails-console


    【解决方案1】:

    使用助手而不是手动包含助手

     > 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" 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多