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

前端 未结 13 1231
暖寄归人
暖寄归人 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 09:47

    I think it's the simplest way to get it

    def get_number_of_days(date = Date.today)
      Date.new(date.year, date.month, -1).mday
    end
    
    0 讨论(0)
  • 2020-12-23 09:48

    A simple way using Date:

    def days_of_month(month, year)
      Date.new(year, month, -1).day
    end
    
    0 讨论(0)
  • 2020-12-23 09:49

    In Rails project for current date

    Time.days_in_month(Time.now.month, Time.now.year)
    

    For any date t which is instance of Time

    Time.days_in_month(t.month, t.year)
    

    or

    t.end_of_month.day
    

    .
    If you have UTC seconds, you need to get an instance of Time first

    Time.at(seconds).end_of_month.day
    
    0 讨论(0)
  • 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.

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

    This is the implementation from ActiveSupport (a little adapted):

    COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    
    def days_in_month(month, year = Time.now.year)
       return 29 if month == 2 && Date.gregorian_leap?(year)
       COMMON_YEAR_DAYS_IN_MONTH[month]
    end
    
    0 讨论(0)
  • 2020-12-23 09:58
    require 'date'
    
    def days_in_month(year, month)
      Date.new(year, month, -1).day
    end
    
    # print number of days in February 2012
    puts days_in_month(2012, 2)
    
    0 讨论(0)
提交回复
热议问题