ActiveSupport · Rails

Defining customized Date / Time format in Rails

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)
Advertisements

One thought on “Defining customized Date / Time format in Rails

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s