How to get the number of days in a given month in Ruby, accounting for year?
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?
If you're working in Rails, chances are you'll get hamstrung eventually if you switch among Time
, Date
, and DateTime
, especially when it comes to dealing with UTC/time zones, daylight savings, and the like. My experience has been it's best to use Time
, and stick with it everywhere.
So, assuming you're using Rails's Time class, there are two good options, depending on context:
-
If you have a month
m
and yeary
, use the class method onTime
:days = Time.days_in_month(m, y)
-
If you have a Time object
t
, cleaner to ask the day number of the last day of the month:days = t.end_of_month.day
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)
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