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

前端 未结 13 1232
暖寄归人
暖寄归人 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条回答
  • 2020-12-23 10:03

    Time.now.end_of_month.day - for current month

    Date.parse("2014-07-01").end_of_month.day - use date of first day in month.

    Depends on ActiveSupport

    0 讨论(0)
  • 2020-12-23 10:04

    For a given Date object I feel like the easiest is:

    Date.today.all_month.count
    
    0 讨论(0)
  • 2020-12-23 10:07

    as of rails 3.2... there's a built in version: http://api.rubyonrails.org/classes/Time.html#method-c-days_in_month

    (alas, it shows up after this answer, which takes folks on a long hike)

    0 讨论(0)
  • 2020-12-23 10:09

    Since the time is irrelevant for this purpose then you just need a date object:

    [*Date.today.all_month].size
    
    0 讨论(0)
  • 2020-12-23 10:10

    Use Time.days_in_month(month) where month = 1 for January, 2 for Feb, etc.

    0 讨论(0)
  • 2020-12-23 10:10

    revise the input for other format

    def days_in_a_month(date = "2012-02-01")
      date.to_date.end_of_month.day
    end
    
    0 讨论(0)
提交回复
热议问题