Formatting timestamps

不羁的心 提交于 2019-12-21 03:16:11

问题


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:

<% @created = scenario.created_at %>

Then I will get:

2009-03-27 23:53:38 UTC


回答1:


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.




回答2:


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




回答3:


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




回答4:


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




回答5:


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



回答6:


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.



来源:https://stackoverflow.com/questions/693823/formatting-timestamps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!