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

前端 未结 13 1240
暖寄归人
暖寄归人 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
    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
    

提交回复
热议问题