-1

我的问题类似于Rails - 为选择标签返回一个月份数组

但我想要一个这样的数组:

[
  ["September", 9], 
  ["August", 8],
  ["July", 7], 
  ["June", 6],
  ["May", 5], 
  ["April", 4],
  ["March", 3],
  ["February", 2],
  ["January", 1],
  ["December", 0]
  ["November", -1], 
  ["October", -2]
]

如果当前月份是 10 月,它将是:

[
  ["October", 10]
  ["September", 9], 
  ["August", 8],
  ["July", 7], 
  ["June", 6],
  ["May", 5], 
  ["April", 4],
  ["March", 3],
  ["February", 2],
  ["January", 1],
  ["December", 0]
  ["November", -1]
]
4

1 回答 1

5

这应该这样做:

require 'date'
Date::MONTHNAMES[1..12].reverse.rotate(12-Time.now.month).each_with_index.collect{|m, i| [m, Time.now.month-i]}

编辑:

正如您在要显示年份的评论中提到的那样,您需要一种不同的方法来“回到过去”。当您使用 rails 时,您可以使用 activerecord 的日期函数来做到这一点:

require 'active_support/core_ext/date/calculations'
t = Time.now
(0..11).collect { |i| current = t.advance(months:-i); ["#{Date::MONTHNAMES[current.month]} #{current.year}", t.month-i ] }
于 2012-09-22T18:05:20.900 回答