Ruby / Rails中的“ Ago”日期/时间函数


87

我想知道Rails中是否有一种计算时间戳的方法,如-半分钟前,2分钟前,1天前等。类似Twitter实时日期戳。

我想知道Ruby / Rails是否具有用于此类日期时间转换的内置函数吗?

Answers:


187

您可以使用:

10.minutes.ago
2.days.since

或者在您看来,您有帮助者:

distance_of_time_in_words(from_time, to_time)
time_ago_in_words(from_time)

检查API以获取详细信息和更多选项。


8
从Rails 3开始,现在10.minutes.ago是分钟数。
cbron 2012年

4
如果您不在Rails范围内require 'active_support'(至少已安装Rails 2.X)。
JellicleCat 2012年

7
需要'active_support / all'或如果使用捆绑包:gem“ activesupport”,:require =>“ active_support”
Alireza Eliaderani

9

您可以使用ago,的since别名from_now和许多可用方法来使用可用方法来获取过去或将来的时间。

Time.current
#=> Tue, 20 Sep 2016 15:03:30 UTC +00:00

2.minutes.ago
#=> Tue, 20 Sep 2016 15:01:30 UTC +00:00

2.minutes.since
#=> Tue, 20 Sep 2016 15:05:30 UTC +00:00 

1.month.ago
#=> Sat, 20 Aug 2016 15:03:30 UTC +00:00

1.year.since
#=> Wed, 20 Sep 2017 15:03:30 UTC +00:00 

检查Time类中的所有可用方法


2

distance_of_time_in_words

from_time = Time.now

distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour
distance_of_time_in_words(from_time, 50.minutes.from_now) # => about 1 hour
distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute
distance_of_time_in_words(from_time, from_time + 15.seconds, include_seconds: true) # => less than 20 seconds

time_ago_in_words

time_ago_in_words(3.minutes.from_now) # => 3 minutes
time_ago_in_words(3.minutes.ago) # => 3 minutes
time_ago_in_words(Time.now - 15.hours) # => about 15 hours
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.