我正在写一个Rails应用程序,但似乎无法找到如何做相对时间,即如果给定某个时间类,它可以计算“30秒前”或“2天前”或者它是否更长超过一个月“9/1/2008”等。
答案 0 :(得分:361)
听起来好像是在寻找ActiveSupport的time_ago_in_words
方法(或distance_of_time_in_words
)。这样称呼:
<%= time_ago_in_words(timestamp) %>
答案 1 :(得分:51)
我写过这个,但必须检查提到的现有方法,看它们是否更好。
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
答案 2 :(得分:21)
只是为了澄清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。
N.B。将助手导入控制器并不是“轨道方式”。助手是为了帮助观点。 time_ago_in_words 方法被确定为 MVC 三元组中的 view 实体。 (我不同意,但在罗马时...)
答案 3 :(得分:20)
怎么样?
30.seconds.ago
2.days.ago
或者你正在拍摄的其他东西?
答案 4 :(得分:12)
您可以使用算术运算符来执行相对时间。
Time.now - 2.days
2天前会给你。
答案 5 :(得分:9)
这样的事情会起作用。
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
答案 6 :(得分:6)
由于此处的答案最多,建议 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/
答案 7 :(得分:5)
在这里看一下实例方法:
这有一些有用的方法,例如昨天,明天,开始_周长,以前等等。
示例:
Time.now.yesterday
Time.now.ago(2.days).end_of_day
Time.now.next_month.beginning_of_month
答案 8 :(得分:1)
我已经为Rails ActiveRecord对象编写了一个gem。该示例使用created_at,但它也适用于updated_at或具有ActiveSupport :: TimeWithZone类的任何内容。
只需安装gem并在TimeWithZone实例上调用'pretty'方法。
答案 9 :(得分:1)
如果您正在构建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)
答案 10 :(得分:0)
另一种方法是从后端卸载一些逻辑,并使浏览器通过使用Javascript插件来完成工作,例如: