Is it possible to create a list of months between two dates in Rails

后端 未结 4 524
情书的邮戳
情书的邮戳 2020-12-31 13:38

I am trying to create a page to display a list of links for each month, grouped into years. The months need to be between two dates, Today, and The date of the first entry.<

4条回答
  •  轮回少年
    2020-12-31 13:53

    The following code will add a months_between instance method to the Date class

    #!/usr/bin/ruby 
    
    require 'date'
    
    class Date
    
      def self.months_between(d1, d2)
        months = []
        start_date = Date.civil(d1.year, d1.month, 1)
        end_date = Date.civil(d2.year, d2.month, 1)
    
        raise ArgumentError unless d1 <= d2
    
        while (start_date < end_date)
          months << start_date
          start_date = start_date >>1
        end
    
        months << end_date
    
      end
    end
    

    This is VERY lightly tested, however it returns an Array of dates each date being the 1st day in each affected month.

提交回复
热议问题