Pretty dates in Rails 3
by Trevor Turk
It’s very easy to define your own custom date formats for display in a Rails 3 app. Just check out the docs.
A quick example:
# config/initializers/time_formats.rb
Time::DATE_FORMATS[:month_and_year] = "%B %Y"
Time::DATE_FORMATS[:pretty] = lambda { |time| time.strftime("%a, %b %e at %l:%M") + time.strftime("%p").downcase }
Then, you can do:
@date.to_s(:month_and_year) # => October 2010 @date.to_s(:pretty) # => Mon, Oct 4 at 7:00pm
The “pretty” example is pretty tricky, actually. It’s using some lesser known strftime conversions to show dates without leading zeros and downcasing the am/pm.
Advertisement
But wouldn't it be nicer, to define own custom date/time formats in locale file (config/locales/en.yml) and use it via l(@date, :format=>:month_and_year)
???
I hadn't thought of that, actually. I like this way, but it's good to have options!
Well, in my opinion locale file is just the first place to look for date formats. Also consider multilingual page – date formats used in Europe are different almost in every country
Maciej Litwiniuk beat me to the punch. Making dates and time formats locale aware is really the best practice for applications (or gems/plugins) that have a longer lifespan or scope.
The more internationalization that makes it into gems and plugins at the start the better.
However, yes, it is good to see the various options. Speaking of which here is the guide for handling dates and times via the :format method to be locale aware:
http://guides.rubyonrails.org/i18n.html#adding-da…
Sorry just read the comment, a bit late, but can't we just add additional date formats in the initializers too?