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


当前回答

是什么

30.seconds.ago
2.days.ago

还是你的其他目的?

其他回答

因为这里的大多数答案建议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/

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

Time.now - 2.days 

会给你两天前的。

像这样的东西是可行的。

def relative_time(start_time)
  diff_seconds = Time.now - start_time
  case diff_seconds
    when 0 .. 59
      puts "#{diff_seconds} seconds ago"
    when 60 .. (3600-1)
      puts "#{diff_seconds/60} minutes ago"
    when 3600 .. (3600*24-1)
      puts "#{diff_seconds/3600} hours ago"
    when (3600*24) .. (3600*24*30) 
      puts "#{diff_seconds/(3600*24)} days ago"
    else
      puts start_time.strftime("%m/%d/%Y")
  end
end

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

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

https://github.com/brettshollenberger/hublot

是什么

30.seconds.ago
2.days.ago

还是你的其他目的?