From: Brian Adkins Date: 2008-02-28T03:29:54+09:00 Subject: Re: Getting number of days in a month On Feb 27, 1:00 pm, Gregory Seidman wrote: > On Thu, Feb 28, 2008 at 02:49:54AM +0900, Brian Adkins wrote: > > On Feb 27, 11:40 am, Gregory Seidman > > wrote: > > > On Thu, Feb 28, 2008 at 01:17:22AM +0900, Shandy Nantz wrote: > > > > This is probably an easy question but I am trying to get at the number > > > > of days that are in a month. I have this calendar that I have built, the > > > > idea being that when a month turns from February to March, for example, > > > > the calendar should redisplay itself properly formated showing the new > > > > month and the correct number of days. I have it so that it starts > > > > counting the days on the right day of the week, but I have to know when > > > > to stop counting. Any ideas, Thanks, > > > > require 'date' > > > > def days_in_month(month, year) > > > month = month.to_i > > > year = year.to_i > > > raise ArgumentError.new("invalid month") unless (1..12).to_a.include? month > > > first = Date.parse sprintf("%04d%02d01", year, month) > > > next_month = first + 32 > > > (last - last.mday).mday > > > end > > > > > -S > > > --Greg > > > might want to try running that before posting > > Ah, details. Change the last line of the method to: > > (next_month + next_month.mday).mday > > Anyhow, it's worth noting that ActiveSupport includes Time.days_in_month. > > --Greg You still didn't run it, did you? Some ideas you may want to consider: 1) it's probably reasonable to expect numeric month and day arguments, so you can skip the .to_i calls 2) instead of creating a range, converting it to an array and calling include?, wouldn't it be better to just use a simple comparison such as "unless month > 0 && month < 13 3) sprintf'ing a date just to parse it is unnecessary & inefficient 4) it's still broken