Iterate every month with date objects

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

    Here is something very Ruby:

    first day of each month

    (Date.new(2008, 12)..Date.new(2011, 12)).select {|d| d.day == 1}
    

    It will give you an array of the first day for each month within the range.

    last day of each month

    (Date.new(2008, 12)..Date.new(2012, 01)).select {|d| d.day == 1}.map {|d| d - 1}.drop(1)
    

    Just note that the end date needs to be the month after your end range.

提交回复
热议问题