我正在写一个Rails应用程序,但似乎找不到如何做相对时间,即如果给定一个特定的时间类,它可以计算“30秒前”或“2天前”或如果它超过一个月“9/1/2008”等。


当前回答

我已经为Rails ActiveRecord对象编写了一个gem。这个例子使用了created_at,但它也可以在updated_at或任何带有ActiveSupport::TimeWithZone类的东西上工作。

只是gem安装和调用'pretty'方法在你的TimeWithZone实例。

https://github.com/brettshollenberger/hublot

其他回答

您可以使用算术运算符来计算相对时间。

Time.now - 2.days 

会给你两天前的。

澄清一下Andrew Marshall使用time_ago_in_words的解决方案 (适用于Rails 3.0和Rails 4.0)

如果你在一个视图

<%= time_ago_in_words(Date.today - 1) %>

如果你在控制器中

include ActionView::Helpers::DateHelper
def index
  @sexy_date = time_ago_in_words(Date.today - 1)
end

控制器默认情况下没有导入ActionView::Helpers::DateHelper模块。

注意:在你的控制器中导入helper并不是“正常的方式”。helper用于帮助视图。time_ago_in_words方法被决定为MVC三元组中的一个视图实体。(我不同意,但在罗马…)

如果您正在构建Rails应用程序,则应该使用

Time.zone.now
Time.zone.today
Time.zone.yesterday

这将为您提供配置Rails应用程序所用的时区中的时间或日期。

例如,如果您将应用程序配置为使用UTC,那么time .zone.now将始终使用UTC时间(例如,它不会受到英国夏令时更改的影响)。

计算相对时间很容易

Time.zone.now - 10.minute
Time.zone.today.days_ago(5)

听起来好像您正在从ActiveSupport中寻找time_ago_in_words方法(或distance_of_time_in_words)。这样叫它:

<%= time_ago_in_words(timestamp) %>

我已经为Rails ActiveRecord对象编写了一个gem。这个例子使用了created_at,但它也可以在updated_at或任何带有ActiveSupport::TimeWithZone类的东西上工作。

只是gem安装和调用'pretty'方法在你的TimeWithZone实例。

https://github.com/brettshollenberger/hublot