[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Calculate number of non-weekend days between two dates?

Chris Morris

1/16/2007 7:34:00 PM

Any date/time libraries out there (I can't seem to find anything in the
std libs) that handle calculations like number of non-weekend days
between two dates, etc.?

2 Answers

Dale Martenson

1/16/2007 8:50:00 PM

0


chrismo wrote:
> Any date/time libraries out there (I can't seem to find anything in the
> std libs) that handle calculations like number of non-weekend days
> between two dates, etc.?

require 'date'

def weekdays(d1, d2)
count = 0
d1.upto(d2) do |date|
count += 1 if [1,2,3,4,5].include?(date.wday)
end
count
end

puts weekdays( Date.new(2006, 12, 1), Date.new(2007, 1, 16) )

A more useful twist might be to collect the weekdays and return an
array:

require 'date'

def weekdays(d1, d2)
_weekdays = []
d1.upto(d2) do |date|
_weekdays << date if [1,2,3,4,5].include?(date.wday)
end
_weekdays
end

puts weekdays( Date.new(2006, 12, 1), Date.new(2007, 1, 16) ).size

Gavin Kistner

1/16/2007 9:05:00 PM

0

Dale Martenson wrote:
> A more useful twist might be to collect the weekdays and return an
> array:

How about:

require 'date'
d1 = Date.new( 2006, 12, 1 )
d2 = Date.new( 2007, 1, 15 )

WEEKDAY_NUMBERS = [1,2,3,4,5]
weekdays = (d1..d2).select{ |d| WEEKDAY_NUMBERS.include?( d.wday ) }
p weekdays.length
#=> 32