Rails: How to make Date strftime aware of the default locale?

Ruby on-RailsRubyLocalizationRails I18nStrftime

Ruby on-Rails Problem Overview


I have my default locale set in the environment.rb as de (German).

I also see all the error messages in German, so the locale is picked up by the server. But when I try to print date with strftime like following:

some_date.strftime('%B, %y')

It prints in English (January, 11), and not the expected German (Januar, 11).

How can I print the date according to the default locale?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Use the l (alias for localize) method instead of raw strftime, like this:

l(date, format: '%B %d, in the year %Y')

See here for more information, hope that helps.

You can also define 'named' formats, a couple of them (short, long) are already predefined.

Solution 2 - Ruby on-Rails

you can also make it shorter:

l(some_date, :format => '%d %B %Y')

Solution 3 - Ruby on-Rails

In es.yml put:

es:
  date:
    formats:
      default: "%d / %m / %Y"

In index.html.erb put:

<%= l somemodel.datefield %>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrangaloView Question on Stackoverflow
Solution 1 - Ruby on-RailsMilan NovotaView Answer on Stackoverflow
Solution 2 - Ruby on-RailskstarskiView Answer on Stackoverflow
Solution 3 - Ruby on-RailsDanielView Answer on Stackoverflow