How to get the number of days in a given month in Ruby, accounting for year?

前端 未结 13 1280
暖寄归人
暖寄归人 2020-12-23 09:22

I\'m sure there\'s a good simple elegant one-liner in Ruby to give you the number of days in a given month, accounting for year, such as \"February 1997\". What is it?

13条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-23 09:52

    How about:

    require 'date'
    
    def days_in_month(year, month)
      (Date.new(year, 12, 31) << (12-month)).day
    end
    
    # print number of days in Feburary 2009
    puts days_in_month(2009, 2)
    

    You may also want to look at Time::days_in_month in Ruby on Rails.

提交回复
热议问题