【问题标题】:Format date/time in ruby在 ruby​​ 中格式化日期/时间
【发布时间】:2013-04-19 05:50:13
【问题描述】:

我收到了这种格式的日期和时间

2013-04-19 11:07:37 +0530

我想知道如何在 ruby​​ 中以这种方式显示 XYZ hours ago

谢谢

更新:我尝试了time_ago_in_words' and it gives me the errorundefined 方法time_ago_in_words'

【问题讨论】:

标签: ruby ruby-on-rails-3


【解决方案1】:

它是一种导轨方法。您可以通过rails c 进入Rails 控制台并通过include ActionView::Helpers::DateHelper。然后解决类似

t = Time.parse("2013-04-19 11:07:37 +0530")
time_ago_in_words(t)

HTH

【讨论】:

  • 我在我的控制台上试过,但它给出错误 irb(main):013:0> include ActionView::Helpers::DateHelper => Object irb(main):014:0> t = Time .parse(2013-04-19 11:07:37 +0530) SyntaxError: (irb):14: 语法错误,意外 tINTEGER,期待 ')' t = Time.parse(2013-04-19 11:07:37 +0530) ^ 来自 /var/lib/gems/1.9.1/gems/railties-3.2.13/lib/rails/commands/console.rb:47:in start'from script/rails:6:in
    '
【解决方案2】:

使用此功能

time_ago_in_words(from_time, include_seconds = false, options = {})

参考链接:ClickHere

irb> time = "2013-04-19 11:07:37 +0530"
=> "2013-04-19 11:07:37 +0530"
irb> helper.time_ago_in_words(time)
=> "about 3 hours"

或另一种方式:- 包括 ActionView::Helpers::DateHelper:

>> time_ago_in_words("2013-04-19 11:07:37 +0530")
NoMethodError: undefined method `time_ago_in_words' for #<Object:0x3b0454>
from (irb):4
>> include ActionView::Helpers::DateHelper
=> Object
>> time_ago_in_words("2013-04-19 11:07:37 +0530")
=> "about 3 hours"

【讨论】:

  • 我在 IRB 中执行此操作,它给了我一个错误 undefined method time_ago_in_words'`
  • 请查看更新后的答案,其中您必须在 time_ago_in_words 之前添加助手。我希望这对你有用。
【解决方案3】:

time_ago_in_words 和 distance_of_time_in_words 是 Rails 方法。您必须定义自己的方法来执行此操作。也许你可以从 rails 复制代码。

【讨论】:

    猜你喜欢
    • 2019-01-29
    • 2015-08-09
    • 1970-01-01
    • 2012-10-06
    • 2011-11-12
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多