by
back

Set a custom date format in your Rails 4 view

It's very easy to setup a custom date format in Ruby on Rails.

To get started add your custom format first:

# config/locales/en.yml
   en:
      date:
         formats:
            customformat: '%m %Y'

# ... make sure to also set it for the time format

      time:
         formats:
            customformat: '%m %Y'

To use the new format in your view, just add the format to your output

# views/someview.html.erb
   <%= l Time.now, format: :customformat %>

You can translate a given date string to a date object with the .to_date method.

# views/someview.html.erb
   <%= l mystring.to_date, format: :customformat %>

or use one of the default date formats in Rails such as :long and :short

# views/someview.html.erb
   <%= l mystring.to_date, format: :customformat %>

The l is an alias for the rails intern localization helper. Check http://guides.rubyonrails.org/i18n.html for details.

Cheers,
Flo

comments powered by Disqus