I needed to find the dates for a plus-minus n weekdays interval, you know, when they say the product will be delivered in 5 working/week days. I couldn’t find anything, so I made this:
function weekdaysinterval(today, weekdays)
function step(x, by)
counter = 0
while counter < weekdays
x += by
if Dates.dayofweek(x) < 6
counter += 1
end
end
x
end
from = step(today, -Dates.Day(1))
to = step(today, Dates.Day(1))
from, to
end
Happy to hear if this is already implemented or if you have any suggestions. Note that this implementation is for weekdays, notworkingdays, and as such it assumes that a week is Monday–Friday, including (however, this is not true for some countries, e.g. Israel).
Yea, for sure, I should check it out and make sure it always works. To be honest, I was sure someone will point me to an already existing implementation. Seems like a really common need…?
I think there is a one off error (at least it skips Friday) and I don’t think it works for negative values.
Here is some code that should suffice:
function weekdays(today, wd)
function skipdays(workdays, today)
adj = (Dates.dayofweek(today) - 1) * sign(workdays)
weekends = div(workdays + adj, 5)
today + Dates.Day(workdays + weekends * 2)
end
skipdays(-wd, today), skipdays(wd, today)
end
There is also the Dates adjuster API with Dates.toprev and Dates.tonext that can be used to find such dates iteratively, but in a generic manner (e.g. add holidays into the mix).