我正在写一个Rails应用程序,但似乎找不到如何做相对时间,即如果给定一个特定的时间类,它可以计算“30秒前”或“2天前”或如果它超过一个月“9/1/2008”等。
当前回答
是什么
30.seconds.ago
2.days.ago
还是你的其他目的?
其他回答
看看这里的实例方法:
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
如果您正在构建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)
您可以使用算术运算符来计算相对时间。
Time.now - 2.days
会给你两天前的。
因为这里的大多数答案建议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/
像这样的东西是可行的。
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 On Rails中使用NuoDB手动执行SQL命令
- 是否可以在MiniTest中运行单个测试?
- 如何在Ruby中生成a和b之间的随机数?
- ActiveRecord OR查询
- 无法安装gem -未能建立gem本地扩展-无法加载这样的文件——mkmf (LoadError)
- 如何在Ruby中创建文件
- 什么是Ruby文件。开放模式和选项?
- Ruby数组到字符串的转换
- 如何分割(块)一个Ruby数组成X元素的部分?
- Ruby中“or”和||的区别?
- 在Rails中使用user_id:integer vs user:references生成模型
- 如何测试参数是否存在在轨道
- 验证多个列的唯一性
- Rails:在where语句中使用大于/小于
- Rails:如何为Rails activerecord的模型中的属性创建默认值?