DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Days In Month

08.07.2007
| 13193 views |
  • submit to reddit
        // returns number of days in specified month

def days_in_month(month)
  (Date.new(Time.now.year,12,31).to_date<<(12-month)).day
end
    

Comments

Snippets Manager replied on Mon, 2012/05/07 - 2:41pm

This one does: require 'date' def days_in_month(year, month) (Date.new(year, 12, 31) << (12-month)).day end

Snippets Manager replied on Thu, 2006/08/17 - 8:26pm

Correct me if I am wrong, but none of these appear to work with leap years.

Snippets Manager replied on Mon, 2012/05/07 - 2:41pm

Here's a fun one: def days_in_month(month) month == 2 ? 28 : 30 + ((month * 1.126).to_i % 2) end

Snippets Manager replied on Mon, 2012/05/07 - 2:41pm

Or, of course (ha ha): [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] The beauty of letting Ruby figure it out no doubt is the infamous February, so this might be better: def days_in_month(year, month) (Date.new(year, 12, 31) << (12-month)).day end

Snippets Manager replied on Mon, 2007/10/15 - 12:05pm

Another way: def days_in_month(month) ((Date.new(Time.now.year, month, 1) >> 1) - 1).day end