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


当前回答

澄清一下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.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

是什么

30.seconds.ago
2.days.ago

还是你的其他目的?

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

<%= time_ago_in_words(timestamp) %>

我已经写了这个,但是必须检查现有的方法,看看它们是否更好。

module PrettyDate
  def to_pretty
    a = (Time.now-self).to_i

    case a
      when 0 then 'just now'
      when 1 then 'a second ago'
      when 2..59 then a.to_s+' seconds ago' 
      when 60..119 then 'a minute ago' #120 = 2 minutes
      when 120..3540 then (a/60).to_i.to_s+' minutes ago'
      when 3541..7100 then 'an hour ago' # 3600 = 1 hour
      when 7101..82800 then ((a+99)/3600).to_i.to_s+' hours ago' 
      when 82801..172000 then 'a day ago' # 86400 = 1 day
      when 172001..518400 then ((a+800)/(60*60*24)).to_i.to_s+' days ago'
      when 518400..1036800 then 'a week ago'
      else ((a+180000)/(60*60*24*7)).to_i.to_s+' weeks ago'
    end
  end
end

Time.send :include, PrettyDate