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?
-
Dylan's answer still works as of Ruby 2.5.0 – oneWorkingHeadphone Jul 2 '19 at 18:16
Add a comment
|
Date::MONTHNAMES[Date.today.month]
would give you "January". (You may need to require 'date'
first).
-
28
Date.today.strftime("%B")
is a better way of doing this, imho. And it's not specific to rails. See answer below by leafo. – Peter Berg Sep 1 '14 at 20:14 -
2@PedroMorteRolo still works for me on Ruby 2.2.0 -- make sure to
require 'date'
first. – Dylan Markow Jan 23 '15 at 23:15
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"
-
As I think, this answer is better than others because I18n returns months names in current locale. – Stepan Zakharov Sep 30 '14 at 11:54
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
-
2Just a warning for anyone using Ruby 2, gotta use
Time.new.strftime("B")
Today & strftime are stripped from Date – Sanarothe Oct 7 '13 at 15:36 -
7
If you care about the locale, you should do this:
I18n.l(Time.current, format: "%B")
-
or
I18n.l(Date.new, format: '%B')
to start with January. If you want to add months, like having February, useDate.new + 1.month
– Rui Nunes Jul 19 '17 at 14:26
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>