From: Mohit Sindhwani Date: 2008-02-29T14:35:50+09:00 Subject: Re: Getting number of days in a month Brian Adkins wrote: > On Feb 27, 12:07 pm, Morton Goldberg wrote: > >> On Feb 27, 2008, at 11:17 AM, 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" >> d = Date.new(2008, 2, -1) >> d.day # => 29 >> >> >> You can find the last day of a month by creating a Date object for >> day -1. >> >> Regards, Morton >> > > And we have a winner :) > > I wish I had read your post before posting mine. I need to read the > stdlib doc more carefully. > This may be a bit of a silly question, but this problem came up for me recently and I wasn't able to solve it actually. I did it another way and I'll put the code at the end. If you look at the documentation for the Time class - http://www.ruby-doc.org/core/classes/Time.html it has the following: LeapYearMonthDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] CommonYearMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] Why can't I access these constants directly? Perhaps, my Ruby knowledge is a bit lacking, but I guessed that if I could access that, I could have just used that :-S Anyway, this is a snippet of what I used eventually for getting the number of days in a month. It's not as short as some of the others, but I like it :) require 'time' require 'date' #t is a full date from which we use t.month to find the month for which you want the number of days LeapYearMonthDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] CommonYearMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if Date.gregorian_leap?(t.year) days_of_months = LeapYearMonthDays else days_of_months = CommonYearMonthDays end puts "There are #{days_of_months[t.month]} days in this month." Yes, it's not tested - it's been snipped out of a running application, though. Cheers, Mohit. 2/29/2008 | 1:35 PM.