February 20, 2001 - Computing Business Days | WebReference

# February 20, 2001 - Computing Business Days

 February 20, 2001Computing Business Days Tips: February 2001 Yehuda Shiran, Ph.D.Doc JavaScript
In many applications you need to forward-compute the date, taking into account which days are business days and which ones are not. Suppose you operate a purchasing and delivering site on the Web. Your operation model constrains your delivery service to 5 business days. You probably want to tell your customers at which date the package would be delivered. A bank Web site needs 12 business days to process mortgage applications. The bank would like to inform applicants when they should check back about their applications. These are typical examples where forward-computing the date while counting business days only is very handy. The following function, `getDeliveryDateObj()`, accepts the number of business days as a parameter, and returns the delivery day's `Date` object (national holidays are counted as business days):

``````function getDeliveryDateObj(businessDaysLeftForDelivery) {
var now = new Date();
var dayOfTheWeek = now.getDay();
var deliveryDay = dayOfTheWeek + businessDaysLeftForDelivery;
if (deliveryDay >= 6) {
//deduct this-week days
//count this coming weekend
calendarDays += 2;
//how many whole weeks?
//two days per weekend per week
calendarDays += deliveryWeeks * 2;
}
now.setTime(now.getTime() + calendarDays * 24 * 60 * 60 * 1000);
return now;
}``````

The algorithm is to add the weekend days to the number of business days, yielding the target delivery date. The variable `calendarDays` denotes the number of calendar days. We update it as we go along. The first line creates today's `Date` object:

``var now = new Date();``
The second line computes today's day of the week (Sunday is 0, Saturday is 6):

``var dayOfTheWeek = now.getDay();``
We initialize `calendarDays` with the number of business days accepted by the function as a parameter:

``var calendarDays = businessDaysLeftForDelivery;``
The target delivery day is:

``var deliveryDay = dayOfTheWeek + businessDaysLeftForDelivery;``
The next big loop handles cases where the delivery day is beyond Saturday:

``if (deliveryDay >= 6) {``
We first need to subtract the number of business days in the current week:

``````//deduct this-week days
Then we need to add this coming weekend to the number of calendar days:

``````//count this coming weekend
calendarDays += 2;``````
We compute the number of whole weeks before delivery:

``````//how many whole weeks?
``````//two days per weekend per week
At the exit of the loop, we just compute the delivery date by setting the `Date` object's time. We need to convert the number of calendar days to milliseconds:
``now.setTime(now.getTime() + calendarDays * 24 * 60 * 60 * 1000);``