Ruby / Rails中的“前”date/时间函数

我想知道是否有方法在Rails中计算时间戳 – 半分钟前,2分钟前,1天前等。像Twitter的实时date戳。

我想知道如果Ruby / Rails有这样的date时间转换的内置function?

您可以使用:

10.minutes.ago 2.days.since 

或者在你的观点你有帮手:

 distance_of_time_in_words(from_time, to_time) time_ago_in_words(from_time) 

检查API的细节和更多选项。

您可以使用可用的方法获取以前或将来使用的时间, since from_now和许多可用方法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类中所有可用的方法

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