How can I make Rails 3 localize my date formats?

Matthew Savage picture Matthew Savage · Oct 7, 2010 · Viewed 36.7k times · Source

I am working on a Rails 3 project where there is place for date input within a form. The text field with the date uses a date picker so there is no concern about the date being entered in a wrong format, however the date is being displayed in the :db format (e.g. 2010-01-21).

(Note: this is specifically in form fields - e.g. <%= f.text_field :publish_date %>, which should automatically use :default format, and shouldn't need to be provided with a value)

I have tried adding in a customized locale which has the following date configuration:

date:
    formats:
      # Use the strftime parameters for formats.
      # When no format has been given, it uses default.
      # You can provide other formats here if you like!
      default: "%d/%m/%Y"
      short: "%b %d"
      long: "%B %d, %Y"

And then setting my locale to this (config.i18n.default_locale = "en-AU") however this doesn't seem to take and its becoming quite frustrating.

The app will eventually support a number of locales, so setting up an initializer to override the date formats at application startup isn't really suitable, and I know that this should work - I'm guessing I've missed something here.

The locale file is: config/locales/en-AU.yml and in my application.rb I am including:

config.i18n.load_path += Dir[Rails.root.join("config", "locales", "*.yml").to_s]
config.i18n.default_locale = "en-AU"

in my application.rb file.

Answer

Damien MATHIEU picture Damien MATHIEU · Oct 7, 2010

When displaying a date, you can use I18n.l

So you would do :

I18n.l @entry.created_at

And if you want to change it's format :

I18n.l @entry.created_at, :format => :short

The internationalization rails guide is documenting that.