Name of this month (Date.today.month as name)

Ruby

Ruby Problem Overview


I'm using Date.today.month to display the month number. Is there a command to get the month name, or do I need to make a case to get it?

Ruby Solutions


Solution 1 - Ruby

Date::MONTHNAMES[Date.today.month] would give you "January". (You may need to require 'date' first).

Solution 2 - Ruby

You can also use 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"

Solution 3 - Ruby

You can use strftime:

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

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

Solution 4 - Ruby

If you care about the locale, you should do this:

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

Solution 5 - Ruby

For Ruby 1.9 I had to use:

Time.now.strftime("%B")

Solution 6 - Ruby

HTML Select month with 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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRod NelsonView Question on Stackoverflow
Solution 1 - RubyDylan MarkowView Answer on Stackoverflow
Solution 2 - RubygrilixView Answer on Stackoverflow
Solution 3 - RubyleafoView Answer on Stackoverflow
Solution 4 - RubyYury LebedevView Answer on Stackoverflow
Solution 5 - RubyjpgeekView Answer on Stackoverflow
Solution 6 - RubyAbelView Answer on Stackoverflow