Simple & Clean Rails Date/Time Format

Here is a quick, clean and easy way to get use from strftime on your date/time fields. Create a file called date_format.rb in the config/initializers directory and add the following code:

ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
  :datetime_military => '%Y-%m-%d %H:%M',
  :datetime          => '%Y-%m-%d %I:%M%P',
  :time              => '%I:%M%P',
  :time_military     => '%H:%M%P',
  :datetime_short    => '%m/%d %I:%M'
)

Then in your views, you can do the following:

@object.time_field.to_s(:datetime)     # Or any other format you created

Leave a Reply

Your email address will not be published. Required fields are marked *