Formatting timestamps

后端 未结 6 1325
旧时难觅i
旧时难觅i 2021-02-12 12:30

How do you format Rails timestamps in a more human-readable format? If I simply print out created_at or updated_at in my view like this:



        
相关标签:
6条回答
  • 2021-02-12 12:33

    Take a look at the I18n functionality. It allows you to do the following in your views:

    <%= localize(scenario.created_at, :format => :long) %>

    where the formats are defined in your locales. More info

    0 讨论(0)
  • 2021-02-12 12:38

    The strftime (from Ruby's Time) and to_formatted_s (from Rails' ActiveSupport) functions should be able to handle all of your time-formatting needs.

    0 讨论(0)
  • 2021-02-12 12:41

    You can use strftime to format the timestamp in many ways. I prefer some_data[:created_at].strftime('%F %T'). %F shows "2017-02-08" (Calendar date extended), and %T shows "08:37:48" (Local time extended).

    For timezone issues, add this lines to your config/application.rb file

    config.time_zone = 'your_timezone_string'
    config.active_record.default_timezone = :local
    
    0 讨论(0)
  • 2021-02-12 12:45

    Also

    <%= l scenario.created_at, :format => :sample) %>
    

    And in locales/en.yml(depending of language)

      en:
        time:
          formats:
            sample: '%d.%m.%Y'
    

    To learn more, see - http://guides.rubyonrails.org/i18n.html

    0 讨论(0)
  • 2021-02-12 12:46

    you have to modify the timestamp file, in my case this file is located in /usr/local/rvm/gems/ruby-2.0.0-p195/gems/activerecord-4.2.0/lib/active_record/timestamp.rb. You must search for this line:

    self.class.default_timezone == :utc ? Time.now.utc : Time.now
    

    and change it to this:

    self.class.default_timezone == :utc ? Time.now.utc : Time.now.strftime('%Y-%m-%d %H-%M-%S')
    

    The trick is to modify the format with the strftime method, you can change the format if you want.

    Now rails will use your format to update the "updated_at" column.

    0 讨论(0)
  • 2021-02-12 12:47

    Time.now().to_i works great. For reverse conversion use Time.at(argument)

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