{S.A.Z.W.Q.A}

Entries categorized as ‘ActiveSupport’

Defining customized Date / Time format in Rails

February 18, 2008 · 1 Comment

Generally to display customized Date / Time in rails we use helper method like:

# formats the date
def show_date(date)
  date.strftime("%B %d, %Y")
end

But there is another better way to do this, injecting customized rules in respective DATE_FORMATS hash of ActiveSupport::CoreExtensions module.

# define this in your environment.rb
# Default date/time format
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(:standard => "%B %d, %Y")
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(:standard => "%B %d, %Y")

Using it is simple:

Date.today.to_s(:standard)
Time.now.to_s(:standard)

Categories: ActiveSupport · Rails
Tagged: