69

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?

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
rangalo
  • 5,448
  • 8
  • 46
  • 66

3 Answers3

134

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.

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

starball
  • 20,030
  • 7
  • 43
  • 238
Milan Novota
  • 15,506
  • 7
  • 54
  • 62
  • How to print the date in format with localize ? Does it accept any formatting string like '%B, %y' ? – rangalo Jan 04 '11 at 09:58
  • 26
    I figured it out: I18n.localize(some_date, :format => '%B, %y' Thanks – rangalo Jan 04 '11 at 10:17
  • 1
    You'll want to make sure you have this gem installed: https://github.com/svenfuchs/rails-i18n That way you can have different locale's and call their `format: short` or whatever you'd like to reference. Look here for examples on references: https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/en.yml – bcackerman Mar 10 '13 at 17:31
  • 1
    Or you can do something like this once you have that gem I mentioned above installed... `l @item.created_at, :format => "%b %e, %Y", :locale => 'en'` – bcackerman Mar 10 '13 at 17:36
30

you can also make it shorter:

l(some_date, :format => '%d %B %Y')
kstarski
  • 301
  • 3
  • 2
10

In es.yml put:

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

In index.html.erb put:

<%= l somemodel.datefield %>
Daniel
  • 101
  • 1
  • 3
  • Should it be `time` instead of `date` actually? It depends of the Class of the object passed I believe. – Capripot Nov 08 '19 at 04:12