Calculate number of non-weekend days between two dates?

Discussion in 'Ruby' started by chrismo, Jan 16, 2007.

  1. chrismo

    chrismo Guest

    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.?
     
    chrismo, Jan 16, 2007
    #1
    1. Advertising

  2. 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
     
    Dale Martenson, Jan 16, 2007
    #2
    1. Advertising

  3. chrismo

    Phrogz Guest

    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
     
    Phrogz, Jan 16, 2007
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Brian Henry
    Replies:
    6
    Views:
    16,174
    Brian Henry
    Nov 19, 2003
  2. David Lozzi

    Dates dates dates dates... SQL and ASP.NET

    David Lozzi, Sep 29, 2005, in forum: ASP .Net
    Replies:
    1
    Views:
    870
    Rob Schieber
    Sep 30, 2005
  3. clintonb
    Replies:
    9
    Views:
    887
    James Kanze
    May 23, 2007
  4. Trent Nelson
    Replies:
    0
    Views:
    596
    Trent Nelson
    May 7, 2008
  5. Luca Villa
    Replies:
    2
    Views:
    151
    Luca Villa
    Nov 11, 2007
Loading...

Share This Page