Ruby/Rails 中的“Ago”日期/时间函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3278986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Ago" date/time functions in Ruby/Rails
提问by kapso
I was wondering if there's a way in Rails to calculate time stamp like - half a minute ago, 2 minute ago, 1 day ago etc. Something like twitter real time date stamp.
我想知道 Rails 中是否有一种方法可以计算时间戳,例如 - 半分钟前、2 分钟前、1 天前等。诸如 twitter 实时日期戳之类的东西。
I want to know if Ruby/Rails has a built-in function for such date-time conversion?
我想知道 Ruby/Rails 是否具有用于此类日期时间转换的内置函数?
回答by Toby Hede
回答by Deepak Mahakale
You can use available methods to get the time in past or future using ago, sincealias for from_nowand many available methods
您可以使用可用的方法使用,以获得在过去或未来的时间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
Check all the available methods in Timeclass
检查Time类中的所有可用方法
回答by Dorian
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(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

