本月的名称(Date.today.month作为名称)

时间:2011-01-30 17:15:36

标签: ruby

我正在使用Date.today.month来显示月份编号。是否有获取月份名称的命令,或者我是否需要提出案例来获取它?

6 个答案:

答案 0 :(得分:185)

Date::MONTHNAMES[Date.today.month]会给你“一月”。 (您可能需要先require 'date'

答案 1 :(得分:114)

您也可以使用I18n:

I18n.t("date.month_names") # [nil, "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
I18n.t("date.abbr_month_names") # [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
I18n.t("date.month_names")[Date.today.month] # "December"
I18n.t("date.abbr_month_names")[Date.today.month] # "Dec"

答案 2 :(得分:76)

您可以使用strftime

Date.today.strftime("%B") # -> November

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/Date.html#strftime-method

答案 3 :(得分:15)

如果你关心语言环境,你应该这样做:

I18n.l(Time.current, format: "%B")

答案 4 :(得分:12)

对于Ruby 1.9,我不得不使用:

Time.now.strftime("%B")

答案 5 :(得分:0)

HTML选择带有I18n的月份:

<select>
  <option value="">Choose month</option>
  <%= 1.upto(12).each do |month| %>
    <option value="<%= month %>"><%= I18n.t("date.month_names")[month] %></option>
  <% end %>
</select>