在Rails 3中定制en.yml中的datetime格式 [英] Customizing datetime format in en.yml in Rails 3
问题描述
根据 http://guides.rubyonrails.org/上的文档i18n.html#added-date-time-format ,要求日期的特定格式的最佳方法是在/config/locales/en.yml中定义它们。我已复制并粘贴此文件: https: //github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml 到我的语言环境目录。
I已经做了一些修改(仅用于重点的星号):
en-US:
/ pre>
date:
格式:
默认值:%Y-%m-%d
** short:short%b%d**
和
时间:
格式:
default:%a,%d%b%Y%H:%M:%S%z
** short:short%B%d,%Y**
在我的部分:
code><%= l item.create_date,:format => :短%>
其中,create_date是我的数据库中的日期时间行。
我已经重新启动了我的服务器,但仍然收到如下格式的日期:
3月30日00:00
我有一种感觉这是因为我既不使用日期也不使用时间。我找不到datetime的short或long的定义。我尝试通过添加以下代码将其添加到此文件:
datetime:
格式:
short: short%B%d,%Y
没有运气。我失踪了我觉得我正在按照指示。谢谢!
解决方案[几年后...]
如果您想要将日期格式和/或您具有
to_s
的遗留代码,并且不打算将您的应用程序国际化,您可以这样做:I18n.t('date.formats')。
Date :: DATE_FORMATS [key] = value
end
然后只需定义您的格式在
config / locales / en.yml
中。当然,如果您打算翻译您的应用程序,则需要更改所有出现的to_s
以使用I18n.l
方法。
您也可以在没有Rails的情况下使用此方法。在上述代码之前添加以下内容:
require'active_support / time'
I18n.load_path<< 'en.yml'
According to documentation at http://guides.rubyonrails.org/i18n.html#adding-date-time-formats, the best way to ask for specific formats for a date is to define them in /config/locales/en.yml. I've copied and pasted this file: https://github.com/rails/rails/blob/master/activesupport/lib/active_support/locale/en.yml to my locales directory.
I've made a few changes (asterisks for emphasis only):
"en-US": date: formats: default: "%Y-%m-%d" **short: "short %b %d"**
and
time: formats: default: "%a, %d %b %Y %H:%M:%S %z " **short: "short %B %d, %Y"**
And in my partial:
<%= l item.create_date, :format => :short %>
where create_date is a datetime row in my database of items.
I've restarted my server but am still getting a date formatted like this: 15 Mar 00:00
I have a feeling that it is because i'm using neither a date or a time. I can't find the definition of "short" or "long" for datetime. I tried adding it to this file by adding this code:
datetime: formats: short: "short %B %d, %Y"
no luck. What am I missing. I feel like I'm following the instructions directly. Thanks!
解决方案[several years later...]
If you want to DRY up your date formats and/or you have legacy code with
to_s
all over the place and don't plan to internationalize your app, you can do this:I18n.t('date.formats').each do |key, value| Date::DATE_FORMATS[key] = value end
Then just define your formats in
config/locales/en.yml
. Of course if you ever plan to translate your app, you'll need to change all occurrences ofto_s
to use theI18n.l
method suggested below.You can also use this without Rails. Just add the following before the above code:
require 'active_support/time' I18n.load_path << 'en.yml'
这篇关于在Rails 3中定制en.yml中的datetime格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!