我正在写一个Rails应用程序,但似乎找不到如何做相对时间,即如果给定一个特定的时间类,它可以计算“30秒前”或“2天前”或如果它超过一个月“9/1/2008”等。
当前回答
因为这里的大多数答案建议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/
其他回答
听起来好像您正在从ActiveSupport中寻找time_ago_in_words方法(或distance_of_time_in_words)。这样叫它:
<%= time_ago_in_words(timestamp) %>
因为这里的大多数答案建议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/
如果您正在构建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)
是什么
30.seconds.ago
2.days.ago
还是你的其他目的?
像这样的东西是可行的。
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
推荐文章
- 如何记录Ruby代码?
- Ruby:包含的反义词是什么?Ruby数组?
- 想要在Rails中找到没有关联记录的记录
- helper和helper_method做什么?
- 如何回滚只是一个步骤使用耙db:迁移
- 在Ruby中,proc和lambda有什么区别?
- 如何传递参数到一个Rake任务与环境在Rails?
- 获取当前正在执行的方法的名称
- 如何在Rails中计算相对时间?
- 如何在Rails迁移中将可空列更改为不可空列?
- 在Ruby中使用范围填充数组的正确方法
- “for”和“each”在Ruby中
- Ruby on Rails -从CSV文件导入数据
- 我如何复制一个哈希在Ruby?
- Ruby/Rails:将Date转换为UNIX时间戳