How do you do relative time in Rails?

前端 未结 11 1446
借酒劲吻你
借酒劲吻你 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:25

    Another approach is to unload some logic from the backend and maek the browser do the job by using Javascript plugins such as:

    jQuery time ago or its Rails Gem adaptation

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

    Since the most answer here suggests time_ago_in_words.

    Instead of using :

    <%= time_ago_in_words(comment.created_at) %>
    

    In Rails, prefer:

    <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:

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

    Main advantage: caching

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

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

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

    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.

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

    Calculating relative time is easy, eg

    Time.zone.now - 10.minute
    Time.zone.today.days_ago(5)
    
    0 讨论(0)
  • 2020-12-02 04:29

    Take a look at the instance methods here:

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

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

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

    <%= time_ago_in_words(timestamp) %>
    
    0 讨论(0)
提交回复
热议问题