简体   繁体   English

查找去年的月份名称

[英]Find month names for the last year

In my ruby code I want to display all the months name of last 1 year. 在我的ruby代码中,我想显示过去1年的所有月份名称。 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"] . 例如,当前日期是"April 2013"然后我想显示从"May 2012""April 2013"所有月份名称,例如["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"] . 但它给出了: ["April"]

In Rails you can do something like this: 在Rails中你可以做这样的事情:

<% 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 : 出于好奇, Date上没有广为人知的漂亮shift算子:

(-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")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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