04/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.
- Create a file called
config/initializers/date_formats.rbwith 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" )
- Set the date variable:
@cacheExpiresAt = 10.minutes.ago
- Format the date:
<%= @cacheExpiresAt.to_s(:date_time12) %>
:date_time12parameter to the
to_smethod simply chooses the formatting from the
DATE_FORMATShash. This technique lets you centralize all date formatting in your application.
subscribe via RSS