How do you do relative time in Rails?

前端 未结 11 1447
借酒劲吻你
借酒劲吻你 2020-12-02 03:43

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\"

相关标签:
11条回答
  • 2020-12-02 04:38

    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.

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

    https://github.com/brettshollenberger/hublot

    0 讨论(0)
  • 2020-12-02 04:40

    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
    
    0 讨论(0)
  • 2020-12-02 04:40

    You can use the arithmetic operators to do relative time.

    Time.now - 2.days 
    

    Will give you 2 days ago.

    0 讨论(0)
  • 2020-12-02 04:42

    What about

    30.seconds.ago
    2.days.ago
    

    Or something else you were shooting for?

    0 讨论(0)
  • 2020-12-02 04:45

    Just to clarify Andrew Marshall's solution for using time_ago_in_words
    (For Rails 3.0 and 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::DateHelper imported by default.

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

    0 讨论(0)
提交回复
热议问题