Iterate every month with date objects

后端 未结 9 2418
轻奢々
轻奢々 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:49

    I find that I need to do this sometimes when generating select lists of months. The key is the >> operator on Date, which advances the Date forward one month.

    def months_between(start_month, end_month)
      months = []
      ptr = start_month
      while ptr <= end_month do
        months << ptr
        ptr = ptr >> 1
      end
      months
    end
    
    results = months_between(Date.new(2008,12), Date.new(2009,3))
    

    Of course, you can format the results however you like in the loop.

    months << "#{Date::MONTHNAMES[ptr.month]} #{ptr.year}"
    

    Will return the month name and year ("March 2009"), instead of the Date object. Note that the Date objects returned will be set on the 1st of the month.

提交回复
热议问题