Weekdays Between Two Dates

July 5, 2013

It is easy to calculate the number of weekdays between two dates, given a julian function. Begin by calculating the number of days between the two dates, including weekends, by calculating the julian numbers of the two dates and taking their difference.

If you express the difference as 7 w + d, where w is the number of full weeks between the two dates and d is the number of extra days, then the number of weekdays is 5 w plus the number of weekdays in the extra days. You can take the extra days either at the beginning or the end of the period. Weekdays can be identified by taking the julian numbers of the extra days modulo 7. Here’s the function:

(define (weekdays y-from m-from d-from y-to m-to d-to)
  (let* ((from (julian y-from m-from d-from))
         (to (julian y-to m-to d-to))
         (diff (- to from)))
    (+ (* 5 (quotient diff 7))
       (let loop ((k (modulo diff 7)) (w 0))
         (if (zero? k) w
           (loop (- k 1)
                 (+ w (if (< (modulo (- to k) 7) 5) 1 0))))))))

Here are some examples:

> (weekdays 2013 7 5 2013 7 6)
1
> (weekdays 2013 7 5 2013 7 7)
1
> (weekdays 2013 7 5 2013 7 8)
1
> (weekdays 2013 7 5 2013 7 9)
2
> (weekdays 2013 7 5 2013 7 10)
3
> (weekdays 2013 7 5 2013 7 11)
4
> (weekdays 2013 7 5 2013 7 18)
9
> (weekdays 2013 7 5 2013 7 25)
14

You can run the program at http://programmingpraxis.codepad.org/IpMrB5Vs.

About these ads

Pages: 1 2

One Response to “Weekdays Between Two Dates”

  1. I found it most intuitive to break the count into whole weeks, days in first week, days in last week

    def get_weekdays_between_helper(d1,d2):
        diff = (d2 - d1).days
    
        dow1 = d1.isoweekday()
        dow2 = d2.isoweekday()
    
        dd1 = min (6, dow1)
        dd2 = min (6, dow2)
    
        # special case - in same week
        if diff < 7 and dow1 <= dow2:
            return (0,dd2 - dd1)
    
        whole_weeks = diff / 7
    
        if dow1 <= dow2:
            whole_weeks -= 1
    
        comps = (
            5 * whole_weeks,
            (6-dd1),
            + dd2-1)
    
        return sum(comps)
    

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 637 other followers

%d bloggers like this: