Never been to DZone Snippets before?

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

days in month (See related posts)

// 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 on this post

jgwong posts on Oct 15, 2007 at 12:11
Another way:

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

timmorgan posts on Oct 15, 2007 at 15:52
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
timmorgan posts on Oct 15, 2007 at 16:05
Here's a fun one:

def days_in_month(month)
  month == 2 ? 28 : 30 + ((month * 1.126).to_i % 2)
end
alakra posts on Jan 23, 2008 at 01:20
Correct me if I am wrong, but none of these appear to work with leap years.
timmorgan posts on Jan 23, 2008 at 09:18
This one does:

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

You need to create an account or log in to post comments to this site.


Click here to browse all 4862 code snippets

Related Posts