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


当前回答

看看这里的实例方法:

http://apidock.com/rails/Time

它有一些有用的方法,如昨天,明天,beginning_of_week, ago等。

例子:

Time.now.yesterday
Time.now.ago(2.days).end_of_day
Time.now.next_month.beginning_of_month

其他回答

是什么

30.seconds.ago
2.days.ago

还是你的其他目的?

澄清一下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三元组中的一个视图实体。(我不同意,但在罗马…)

因为这里的大多数答案建议time_ago_in_words。

而不是使用:

<%= time_ago_in_words(comment.created_at) %>

在Rails中,首选:

<abbr class="timeago" title="<%= comment.created_at.getutc.iso8601 %>">
  <%= comment.created_at.to_s %>
</abbr>

连同jQuery库http://timeago.yarp.com/,与代码:

$("abbr.timeago").timeago();

主要优势:缓存

http://rails-bestpractices.com/posts/2012/02/10/not-use-time_ago_in_words/

看看这里的实例方法:

http://apidock.com/rails/Time

它有一些有用的方法,如昨天,明天,beginning_of_week, ago等。

例子:

Time.now.yesterday
Time.now.ago(2.days).end_of_day
Time.now.next_month.beginning_of_month

另一种方法是从后端卸载一些逻辑,让浏览器通过使用Javascript插件来完成工作,例如:

jQuery以前或它的Rails Gem的改编