Forum: Ruby Calculate number of non-weekend days between two dates?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
on 2007-01-16 20:36
```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.?```
on 2007-01-16 21:56
```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```
on 2007-01-16 22:06
```Dale Martenson wrote:
> A more useful twist might be to collect the weekdays and return an
> array:

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```
on 2007-01-16 22:21
```Cool, thx for the suggestions (though I was hoping for a stdlib bit for
corny reasons of my own)

On 1/16/07, Phrogz <gavin@refinery.com> wrote:
>
> WEEKDAY_NUMBERS = [1,2,3,4,5]

this can shorten to:

WEEKDAY_NUMBERS = (1..5)```
This topic is locked and can not be replied to.