Tuesday, April 22, 2008

How to Format Dates in Ruby & Rails

I have seen several techniques used to format dates in blogs and forums threads. This is the technique that worked for me.
  1. Create a file called config/initializers/date_formats.rb with the following contents:
    ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
     :date => '%m/%d/%Y',
     :date_time12  => "%m/%d/%Y %I:%M%p",
     :date_time24  => "%m/%d/%Y %H:%M"
    )
  2. Set the date variable:
    @cacheExpiresAt = 10.minutes.ago
  3. Format the date:
    <%= @cacheExpiresAt.to_s(:date_time12) %>
The :date_time12 parameter to the to_s method simply chooses the formatting from the DATE_FORMATS hash. This technique lets you centralize all date formatting in your application.
Post a Comment