我正在写一个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
其他回答
另一种方法是从后端卸载一些逻辑,让浏览器通过使用Javascript插件来完成工作,例如:
jQuery以前或它的Rails Gem的改编
像这样的东西是可行的。
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
看看这里的实例方法:
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
因为这里的大多数答案建议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
会给你两天前的。
推荐文章
- 最好的打印散列的方法
- 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期间未解决的规格: