今月の名前(Date.today.monthを名前として)


115

Date.today.month月番号の表示に使用しています。月名を取得するコマンドはありますか、それを取得するためにケースを作成する必要がありますか?


Dylanの回答はRuby 2.5.0以降でも機能します
oneWorkingHeadphone

回答:


196

Date::MONTHNAMES[Date.today.month]「1月」を与えます。(require 'date'最初に必要になる場合があります)。


28
Date.today.strftime("%B")これを行うには良い方法です、imho。また、レールに固有のものではありません。leafoによる以下の回答を参照してください。
Peter Berg

2
@PedroMorteRoloはRuby 2.2.0でも動作します- require 'date'最初に確認してください。
ディランマルコウ2015年

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年


16

ロケールに関心がある場合は、次のようにする必要があります。

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

またはI18n.l(Date.new, format: '%B')1月から開始します。2月のように月を追加する場合は、次を使用しますDate.new + 1.month
Rui Nunes

13

Ruby 1.9では、以下を使用する必要がありました。

Time.now.strftime("%B")

0

I18nを使用したHTML Select月:

<select>
  <option value="">Choose month</option>
  <%= 1.upto(12).each do |month| %>
    <option value="<%= month %>"><%= I18n.t("date.month_names")[month] %></option>
  <% end %>
</select>
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.