Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > Calculate number of non-weekend days between two dates?

Reply
Thread Tools

Calculate number of non-weekend days between two dates?

 
 
chrismo
Guest
Posts: n/a
 
      01-16-2007
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.?

 
Reply With Quote
 
 
 
 
Dale Martenson
Guest
Posts: n/a
 
      01-16-2007

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

 
Reply With Quote
 
 
 
 
Phrogz
Guest
Posts: n/a
 
      01-16-2007
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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
calculate the number of days between two dates Luca Villa Perl Misc 2 11-11-2007 11:51 AM
Calculating number of days between two dates. clintonb C++ 9 05-23-2007 09:32 AM
How do you calculate elapsed number of days Anjum Java 3 12-16-2006 06:20 PM
list of days between two days kirke Javascript 7 10-20-2006 07:17 AM
subtracting two dates to get number of days between Brian Henry ASP .Net 6 11-19-2003 09:50 PM



Advertisments