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