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

扶醉桌前 提交于 2019-12-18 10:31:18

问题


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?


回答1:


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.




回答2:


you can also make it shorter:

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



回答3:


In es.yml put:

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

In index.html.erb put:

<%= l somemodel.datefield %>


来源:https://stackoverflow.com/questions/4592235/rails-how-to-make-date-strftime-aware-of-the-default-locale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!