Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

localization - How can I make Rails 3 localize my date formats?

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.

question from:https://stackoverflow.com/questions/3879680/how-can-i-make-rails-3-localize-my-date-formats

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...