2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018

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


subscribe via RSS