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


当前回答

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

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

其他回答

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

<%= time_ago_in_words(timestamp) %>

如果您正在构建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)

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

jQuery以前或它的Rails Gem的改编

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

Time.now - 2.days 

会给你两天前的。

看看这里的实例方法:

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