简体   繁体   中英

Find month names for the last year

In my ruby code I want to display all the months name of last 1 year. For example current date is "April 2013" then I want to display all months name from "May 2012" to "April 2013" such as ["May", "June", .., "April"] . What is the best idea for this?

I tried:

<%= (1.year.ago.to_date.strftime("%B")..Date.today.strftime("%B")).map %> { |a| a } %>

But it gives: ["April"] .

In Rails you can do something like this:

<% 11.downto(0) do |i| %>
  <%= i.months.ago.strftime("%­B %Y") %>
<% end %>
11.downto(0).map { |m| m.months.ago.strftime("%B %Y") }
#=> ["May 2012", "June 2012", ..., "March 2013", "April 2013"]
(0..11).map do |month|
    (11.months.ago + month.months).strftime("%B %Y")
end

Just out of curiosity, there is not wide-known nifty shift operator on Date :

(-12..0).inject([]) { 
  |agg, v| agg << Date::MONTHNAMES[(Date.today << v).month] 
}

or, even simplier:

(-12..0).map { |v| Date::MONTHNAMES[(Date.today << v).month] }

Try this:

(0..11).each { |i|
  month = (Date.today.month + i) % 12 + 1;
  puts Date.new(Date.today.year - 1 + (month < Date.today.month ? 0 : 1), month).strftime("%B %Y")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM