Ruby-on-rails 你如何在 Rails 中做相对时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/195740/
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 20:44:31  来源:igfitidea点击:

How do you do relative time in Rails?

ruby-on-railsruby

提问by Ben Scofield

I'm writing a Rails application, but can't seem to find how to do relative time, i.e. if given a certain Time class, it can calculate "30 seconds ago" or "2 days ago" or if it's longer than a month "9/1/2008", etc.

我正在编写一个 Rails 应用程序,但似乎无法找到如何做相对时间,即如果给定某个时间类,它可以计算“30 秒前”或“2 天前”或者如果它超过一个月“9/1/2008”等

回答by Ben Scofield

Sounds like you're looking for the time_ago_in_wordsmethod (or distance_of_time_in_words), from ActiveSupport. Call it like this:

听起来您正在寻找来自 ActiveSupport的time_ago_in_words方法(或distance_of_time_in_words)。像这样调用它:

<%= time_ago_in_words(timestamp) %>

回答by Matthias Winkelmann

I've written this, but have to check the existing methods mentioned to see if they are better.

我已经写了这个,但必须检查提到的现有方法,看看它们是否更好。

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

回答by seo

Just to clarify Andrew Marshall's solution for using time_ago_in_words
(For Rails 3.0 and Rails 4.0)

只是为了澄清 Andrew Marshall 使用time_ago_in_words的解决方案
(对于 Rails 3.0 和 Rails 4.0)

If you are in a view

如果您在视图中

<%= time_ago_in_words(Date.today - 1) %>

If you are in a controller

如果您在控制器中

include ActionView::Helpers::DateHelper
def index
  @sexy_date = time_ago_in_words(Date.today - 1)
end

Controllers do not have the module ActionView::Helpers::DateHelperimported by default.

默认情况下,控制器没有导入模块ActionView::Helpers::DateHelper

N.B. It is not "the rails way" to import helpers into your controllers. Helpers are for helping views. The time_ago_in_wordsmethod was decided to be a viewentity in the MVCtriad. (I don't agree but when in rome...)

注意,将助手导入控制器不是“轨道方式”。Helpers 用于帮助视图。该time_ago_in_words方法决定是一个视图在实体MVC三元组。(我不同意,但在罗马时......)

回答by Honza

What about

关于什么

30.seconds.ago
2.days.ago

Or something else you were shooting for?

或者你拍摄的其他东西?

回答by TonyLa

You can use the arithmetic operators to do relative time.

您可以使用算术运算符来计算相对时间。

Time.now - 2.days 

Will give you 2 days ago.

2天前会给你。

回答by Gordon Wilson

Something like this would work.

像这样的事情会起作用。

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

回答by Rahul garg

Since the most answer here suggests time_ago_in_words.

由于这里的大多数答案建议time_ago_in_words

Instead of using :

而不是使用:

<%= time_ago_in_words(comment.created_at) %>

In Rails, prefer:

在 Rails 中,更喜欢:

<abbr class="timeago" title="<%= comment.created_at.getutc.iso8601 %>">
  <%= comment.created_at.to_s %>
</abbr>

along with a jQuery library http://timeago.yarp.com/, with code:

连同一个 jQuery 库http://timeago.yarp.com/,代码:

$("abbr.timeago").timeago();

Main advantage: caching

主要优点:缓存

http://rails-bestpractices.com/posts/2012/02/10/not-use-time_ago_in_words/

http://rails-bestpractices.com/posts/2012/02/10/not-use-time_ago_in_words/

回答by davogones

Take a look at the instance methods here:

看看这里的实例方法:

http://apidock.com/rails/Time

http://apidock.com/rails/Time

This has useful methods such as yesterday, tomorrow, beginning_of_week, ago, etc.

这有一些有用的方法,例如昨天、明天、开始_周_、前等。

Examples:

例子:

Time.now.yesterday
Time.now.ago(2.days).end_of_day
Time.now.next_month.beginning_of_month

回答by Brett Shollenberger

I've written a gem that does this for Rails ActiveRecord objects. The example uses created_at, but it will also work on updated_at or anything with the class ActiveSupport::TimeWithZone.

我已经为 Rails ActiveRecord 对象编写了一个 gem。该示例使用 created_at,但它也适用于 updated_at 或具有 ActiveSupport::TimeWithZone 类的任何内容。

Just gem install and call the 'pretty' method on your TimeWithZone instance.

只需 gem install 并在 TimeWithZone 实例上调用“漂亮”方法。

https://github.com/brettshollenberger/hublot

https://github.com/brettshollenberger/hublot

回答by Zack Xu

If you're building a Rails application, you should use

如果你正在构建一个 Rails 应用程序,你应该使用

Time.zone.now
Time.zone.today
Time.zone.yesterday

This gives you time or date in the timezone with which you've configured your Rails application.

这会在您配置 Rails 应用程序的时区中为您提供时间或日期。

For example, if you configure your application to use UTC, then Time.zone.nowwill always be in UTC time (it won't be impacted by the change of British Summertime for example).

例如,如果您将应用程序配置为使用 UTC,Time.zone.now则将始终使用 UTC 时间(例如,它不会受到英国夏令时更改的影响)。

Calculating relative time is easy, eg

计算相对时间很容易,例如

Time.zone.now - 10.minute
Time.zone.today.days_ago(5)