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.
I found it most intuitive to break the count into whole weeks, days in first week, days in last week