Iterate every month with date objects

后端 未结 9 2168
轻奢々
轻奢々 2021-02-01 05:47

So I have two ruby Date objects, and I want to iterate them every month. For example if I have Date.new(2008, 12) and Date.new(2009, 3), it would yield me 2008-12, 2009-1, 2009-

9条回答
  •  礼貌的吻别
    2021-02-01 06:28

    MonthRange.new(date1..date2).each { |month| ... }
    MonthRange.new(date1..date2).map { |month| ... }
    

    You can use all the Enumerable methods if you use this iterator class. I make it handle strings too so that it can take form inputs.

    # Iterate over months in a range
    class MonthRange
      include Enumerable
    
      def initialize(range)
        @start_date = range.first
        @end_date   = range.last
        @start_date = Date.parse(@start_date) unless @start_date.respond_to? :month
        @end_date   = Date.parse(@end_date) unless @end_date.respond_to? :month
      end
    
      def each
        current_month = @start_date.beginning_of_month
        while current_month <= @end_date do
          yield current_month
          current_month = (current_month + 1.month).beginning_of_month
        end
      end
    end
    

提交回复
热议问题