Pretty dates in Rails 3

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.


Published by

Trevor Turk

A chess-playing machine of the late 18th century, promoted as an automaton but later proved a hoax.

5 thoughts on “Pretty dates in Rails 3”

  1. 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 😉

  2. 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:

  3. Sorry just read the comment, a bit late, but can't we just add additional date formats in the initializers too?

Comments are closed.