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:
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
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.
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
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
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.
Time.now().to_i works great. For reverse conversion use Time.at(argument)