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.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" )
- Set the date variable:
@cacheExpiresAt = 10.minutes.ago
- Format the date:
<%= @cacheExpiresAt.to_s(:date_time12) %>
: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.