Determining the number of days in a month
Here is a simple method that returns number of days for wanted month and year. If year is ommited current year is selected.
def month_days(month, year=Date.today.year)
mdays = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
mdays[2] = 29 if Date.leap?(year)mdays[month]
end
Simple examples:
month_days(1) => 31
month_days(2, 2007) => 28
month_days(2, 2008) => 29
Now, let’s assume we have a date from a database, and we want to find number of days in a month from that date.
month_days(date.month, date.year)
But with two more lines of code
def month_days(date_or_month, year=Date.today.year)
year = date_or_month.year if date_or_month.class == Date
month = date_or_month.class == Date ? date_or_month.month : date_or_month
mdays = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
mdays[2] = 29 if Date.leap?(year)
mdays[month]
end
we could find it like this:
month_days(date)
It is worth mentioning that if String is passed as an argument
month_days("2007-02-15")
we will get an ERROR, because first argument must be a Fixnum or a Date.
month_days("2007-02-15".to_date)
If you want to use this as a helper in Rails, create the file date_helper.rb in a lib directory of your app, and put this in:
module ActionView
module Helpers
module DateHelper
def month_days(date_or_month, year=Date.today.year)
year = date_or_month.year if date_or_month.class == Date
month = date_or_month.class == Date ? date_or_month.month : date_or_month
mdays = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
mdays[2] = 29 if Date.leap?(year)
mdays[month]
end
end
end
end
and then add this line to config/environment.rb
require lib/date_helper.rb