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


115

Date.today.month用来显示月份号。是否有获取月份名称的命令,或者我需要说明理由才能获得月份名称?


Dylan的答案从Ruby 2.5.0起仍然有效
oneWorkingHeadphone

Answers:


196

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


28
Date.today.strftime("%B")恕我直言,这是一种更好的方法。它不是特定于导轨的。请参阅leafo的以下答案。
彼得·伯格

2
@PedroMorteRolo在Ruby 2.2.0上仍然对我有效-请务必require 'date'先。
迪伦·马科

121

您也可以使用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"

我认为,此答案比其他答案更好,因为I18n在当前语言环境中返回月份名称。
Stepan Zakharov 2014年



13

对于Ruby 1.9,我必须使用:

Time.now.strftime("%B")

0

使用I18n的HTML选择月份:

<select>
  <option value="">Choose month</option>
  <%= 1.upto(12).each do |month| %>
    <option value="<%= month %>"><%= I18n.t("date.month_names")[month] %></option>
  <% end %>
</select>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.