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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:55:39  来源:igfitidea点击:

"Ago" date/time functions in Ruby/Rails

ruby-on-railsrubydatetime

提问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

You can use:

您可以使用:

10.minutes.ago
2.days.since

Or in your views you have the helpers:

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

distance_of_time_in_words(from_time, to_time)
time_ago_in_words(from_time)

Check the APIfor details and more options.

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

回答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

您可以使用可用的方法使用,以获得在过去或未来的时间agosince别名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

distance_of_time_in_words:

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:

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