我正在写一个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
其他回答
是什么
30.seconds.ago
2.days.ago
还是你的其他目的?
澄清一下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_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/
看看这里的实例方法:
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的改编
推荐文章
- 了解Gemfile。锁文件
- 如何确定一个数组是否包含另一个数组的所有元素
- Rails find_or_create_by多个属性?
- Rails ActiveRecord日期之间
- 是什么导致这个ActiveRecord::ReadOnlyRecord错误?
- 最好的打印散列的方法
- Rails:dependent =>:destroy VS:dependent =>:delete_all
- 我可以在不包含Ruby模块的情况下调用实例方法吗?
- 如何将新项目添加到哈希
- 测试一个Ruby类是否是另一个类的子类
- 什么时候使用Struct vs. OpenStruct?
- 对于PostgreSQL表来说,多大才算太大?
- 数组到哈希Ruby
- 我如何让红宝石打印一个完整的回溯而不是截断一个?
- Rails:如何在Rails 4中引用CSS中的图像