我正在写一个Rails应用程序,但似乎找不到如何做相对时间,即如果给定一个特定的时间类,它可以计算“30秒前”或“2天前”或如果它超过一个月“9/1/2008”等。
当前回答
听起来好像您正在从ActiveSupport中寻找time_ago_in_words方法(或distance_of_time_in_words)。这样叫它:
<%= time_ago_in_words(timestamp) %>
其他回答
听起来好像您正在从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)
像这样的东西是可行的。
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
另一种方法是从后端卸载一些逻辑,让浏览器通过使用Javascript插件来完成工作,例如:
jQuery以前或它的Rails Gem的改编
我已经写了这个,但是必须检查现有的方法,看看它们是否更好。
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
推荐文章
- 最好的打印散列的方法
- Rails:dependent =>:destroy VS:dependent =>:delete_all
- 我可以在不包含Ruby模块的情况下调用实例方法吗?
- 如何将新项目添加到哈希
- 测试一个Ruby类是否是另一个类的子类
- 什么时候使用Struct vs. OpenStruct?
- 对于PostgreSQL表来说,多大才算太大?
- 数组到哈希Ruby
- 我如何让红宝石打印一个完整的回溯而不是截断一个?
- Rails:如何在Rails 4中引用CSS中的图像
- 如何使用RSpec的should_raise与任何类型的异常?
- 如何创建退出消息
- 忽略GEM,因为没有构建它的扩展
- Rails -嵌套包括活动记录?
- 在Gem::Specification.reset期间未解决的规格: