Forum Moderators: open

Message Too Old, No Replies

Writing a Script to Calculate Delivery Times

         

RandallK

6:34 pm on Aug 25, 2010 (gmt 0)

10+ Year Member



Having a little trouble wrapping my head around this, and would appreciate if someone would point me in the right direction.

I need a script that is going to calculate estimated delivery time. The issue comes from when I need to add BUSINESS DAYS not calendar days.

If a package is ordered Friday, it will arrive in less than 6 business days, or before the second Monday. If a package is ordered on a Monday it will arrive before the following Tuesday... etc.

How do I account for the concept of not counting Saturdays and Sundays when making this calculation? (Not even going to consider holidays yet...)

Thank you in advance for any guidance.

whoisgregg

7:11 pm on Aug 25, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Basically, you loop through future days testing each to see if it's a weekday. Whenever you find weekdays, you increment a counter until you've reached your target # of business days. Then, you break out of the loop and use the last calculated day for your delivery date.

The code below is completely untested and probably broken lol, but should put you in the right direction: :)

var businessDays = 0;
var maxDays = 30;
var today = new Date();
for(var n = 1; n < maxDays; n++){
thisdate = today + ( 1000 * 60 * 60 * 24 * n);
thisdateDay = thisdate.getDay();
if (thisdateDay >= 1 && thisdateDay <= 5){
businessDays++;
}
if(businessDays >= 6) continue;
}
alert(thisdateDay);


I've built similar systems but once you get into holidays you really need to move to a database driven system. You'll want to give them the ability to set what days constitute holidays and then dynamically pull those dates through an AJAX call.

RandallK

3:29 pm on Aug 26, 2010 (gmt 0)

10+ Year Member



Made a few tweaks to get it working, not sure it was the best way to handle things... but it works. Here is is for posterities sake:


var today = new Date();
var businessDays = 0;

for (var n = 1; n < 30; n++) {

var thisdate = new Date(today.getTime() + (1000 * 60 * 60 * 24 * n) );

if (thisdate.getDay() >=1 && thisdate.getDay() <= 5) {
businessDays++;
}

if (businessDays >= 6) {
break;
}

}

alert (thisdate);



Also... if one was going to have a database of holidays to work with... how would you do it?