簡體   English   中英

查找去年的月份名稱

[英]Find month names for the last year

在我的ruby代碼中,我想顯示過去1年的所有月份名稱。 例如,當前日期是"April 2013"然后我想顯示從"May 2012""April 2013"所有月份名稱,例如["May", "June", .., "April"] 對此最好的想法是什么?

我試過了:

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

但它給出了: ["April"]

在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

出於好奇, Date上沒有廣為人知的漂亮shift算子:

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

或者,甚至更簡單:

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

嘗試這個:

(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