How do you do relative time in Rails?

前端 未结 11 1609
借酒劲吻你
借酒劲吻你 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条回答
  •  旧时难觅i
    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...)

提交回复
热议问题