问题是这样的,根据开始时间和结束时间,去遍历从开始到结束时间的年份和月份。
year1 = start_time1.year month1 = start_time1.month year2 = end_time.year month2 = end_time.month
然后希望能够已这样的方式去遍历
([year1, month1]..[year2, month2]).each do |y, m| ### y和m分别从开始到结束时间的年和月 end
求帮助~,谢谢🙏
start = start_time.to_datetime finish = end_time.to_datetime while start < finish # do something start += 1.month end
12 进制数
(year1 * 12 + month1 - 1).upto (year2 * 12 + month2 - 1) do |x| year, month = x.divmod 12 month += 1 ... end
不妨定义一个类,实现 succ,<=> 方法,然后就可以用 Range 了:
class Ym include Comparable attr_accessor :year, :month def initialize(year, month) @year, @month = year, month end def succ yyy, mmm = @month == 12 ? [@year + 1, 1] : [@year, @month + 1] Ym.new(yyy, mmm) end def <=>(other) (@year * 12 + @month) <=> (other.year * 12 + other.month) end def to_s sprintf "%4d-%02d", @year, @month end end
使用:
(Ym.new(2008, 9)..Ym.new(2009, 8)).each do |ym| puts ym end
结果:
2008-09 2008-10 2008-11 2008-12 2009-01 2009-02 2009-03 2009-04 2009-05 2009-06 2009-07 2009-08
months = ((end_time - start_time.prev_month) / 1.month).to_i.times.map { |i| start_time + i.months }
谢谢,感谢,都忘回复了
感谢各位