Using named DATE_TIME formats

How many times do you find yourself doing something like this:

DateTime.now.strftime('%m-%d-%Y')

Ugh! Ugly and not very DRY!

Instead, create a file called datetime_format.rb in your config/initializers folder. Put the following snippet into that file:

ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
  :year_month_day => '%Y-%m-%d',
  :year_month_day_and_time => '%Y-%m-%d %H:%M'
)

Now, instead of that ugly line above, you can use the following:

DateTime.now.to_s(:year_month_day)
DateTime.now.to_s(:year_month_day_and_time)

Ah, much better. We now have readable maintainable date formats all defined in a single place.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

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