Standardize your strftime calls
strftime() is a very helpful tool, especially when displaying the time stamps to the user. A basic use of it can be shown here:
@item.created_at.strftime('%H:%M %b %d %Y')
which should output:
13:12 Jan 08 2014
Here is a link for examples on all the options for strftime():
http://techoctave.com/c7/posts/23-rails-date-formats
However, if you have a ton of these timestamps on your front end, it can be maddening when you want to change it for everything.
In /config/initializers/time_formats.rb
, you can name it and reference it throughout the application by passing the symbol into the *.to_s method:
Time::DATE_FORMATS[:date_with_time] = '%H:%M %b %d %Y'
So for the rest of the app, you can just have:
@item.created_at.to_s(:date_with_time)
And you will only have to change the strftime options in one spot! Miraculous!
Kudos to Alexander for bringing up this option.
EDIT: Since you're editing an initializer file, you will have to restart the rails server in order to see your changes! I found this out after banging my head against the wall for a while.
Also, I originally said Date::DATE_FORMATS[:date_with_time]
, this isn't exactly correct usage. Since I'm using it on a *.created_at
, you will have to use Time::DATE_FORMATS
. I'm assuming because it's a timestamp and not a date object.
Written by Cody Palmer
Related protips
2 Responses
Cool idea.
I'm using a method on the DateTime class in an initializer to achieve the same kind of thing ("def pretty_date", to be exact).
Not sure if this is a bad practice, but it works for me.
In fact I do it in locales files so the format is suited for each language of the app.