如何在 ruby on Rails 中获取月份名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3022163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how do I get name of the month in ruby on Rails?
提问by necker
so i create in my view:
所以我在我看来创建:
<%=date=Date.today%>
How do i get the name of the month out of the date? I was trying to do sth like
如何从日期中获取月份的名称?我试图做某事
<%= DATE::ABBR_MONTHNAMES(date.month)%>
But without success. I keep getting an error: uninitialized constant ActionView::Base::CompiledTemplates::MONTHNAMES
但没有成功。我不断收到错误:未初始化的常量ActionView::Base::CompiledTemplates::MONTHNAMES
How do i initialise the constant or is there any other way to get the name out of the Date format?
我如何初始化常量或者有没有其他方法可以从日期格式中获取名称?
would greatly appreciate any answers!
将不胜感激任何答案!
回答by Salil
回答by Quentin
If you are looking solely to the month name, the Date::MONTHNAMESconstant provided by rails is the easiest solution for you:
如果您只查看月份名称,则Date::MONTHNAMESrails 提供的常量是最简单的解决方案:
Date::MONTHNAMES =
[
[ 0] nil,
[ 1] "January",
[ 2] "February",
[ 3] "March",
[ 4] "April",
[ 5] "May",
[ 6] "June",
[ 7] "July",
[ 8] "August",
[ 9] "September",
[10] "October",
[11] "November",
[12] "December"
]
回答by Repolês
If you want a localized month name, try:
如果您想要本地化的月份名称,请尝试:
I18n.t('date.month_names')[date.month]
Example:
例子:
I18n.t('date.month_names')[12] #=> "Dezembro"
回答by edavey
If you have a particular custom date / time format which you need to use repeatedly then you can extend the ActiveSupport date / time helper.
如果您有需要重复使用的特定自定义日期/时间格式,那么您可以扩展 ActiveSupport 日期/时间助手。
e.g. if you define the following in your config/environment.rb
例如,如果您在 config/environment.rb 中定义以下内容
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(:full_english => "%A %B %d, %Y at %I:%M %p")
then when you call Time.now.to_s(:full_english)in your views you will get something like:
然后当你调用Time.now.to_s(:full_english)你的视图时,你会得到类似的东西:
"Friday June 11, 2010 at 12:53 PM"
Ruby's strftimemethod is well documented at http://apidock.com/ruby/Time/strftime
Ruby 的strftime方法在http://apidock.com/ruby/Time/strftime 中有详细记录
回答by Tanmay Tupe
Choose what you want
选择你想要的
Date.parse('5-jan-2017').strftime('%B')
Result:
结果:
=> "January"
=>“一月”
Date.parse('5-jan-2017').strftime('%b')
Result:
结果:
=> "Jan"
=>“简”
For most of your further date related questions, refer this link http://www.foragoodstrftime.com/
对于大多数与日期相关的进一步问题,请参阅此链接 http://www.foragoodstrftime.com/
回答by Vitya Ivliiev
this should help you https://www.shortcutfoo.com/app/dojos/ruby-dates/cheatsheet
这应该可以帮助您 https://www.shortcutfoo.com/app/dojos/ruby-dates/cheatsheet
Date::MONTHNAMES
Date::DAYNAMES

