Mark Giblin Mark Giblin - 1 year ago 93
Javascript Question

How do I add business days in JavaScript?

var businessDays = 10; // this will come from a form
var counter = 0; // I have a counter
var safety = 0; // I have a safety variable
var ship = today = new Date(); // I have the current date and an initialized shipping variable but the buy date will come from a form

while( ++safety <30 ){
ship.setDate( safety ); // add a number of days
switch( ship.getDay() ){

case 0: // Sunday
case 6: // Saturday



if( counter >= businessDays ) break;


// the expected shipping date

console.log(">>> today = " + today);
console.log(">>> days = " + businessDays);
console.log(">>> ship = " + ship);

The problem is: If I buy something off eBay and they say delivery is 7 to 10 business days and I put in the date and the business days before delivery to me, I should get a valid date, but I'm not. I am getting dates that are beginning of Jan this year and not 7 to 10 business days from the purchase date

Answer Source

Thanks for your input guys, I had a long hard re-think over the approach I was making for this and came up with this little number...

var businessDays = 7, counter = 0; // set to 1 to count from next business day
while( businessDays>0 ){
    var tmp = new Date();
    tmp.setDate( tmp.getDate() + counter++ );
    switch( tmp.getDay() ){
            case 0: case 6: break;// sunday & saturday

The idea was to start with the business days and count backwards to zero for each day encountered that fell in to the range of a business day. This use of switch would enable a person to declare a day in the week as a non-business day, for example someone may not work on a monday, therefore the addition of case:1 would include a monday.

This is a simple script and does not take in to account public or bank holidays, that would be asking for a much more complex script to work with.

The result is a date that is set to the date of shipping, the user can then extract the date info in any format that they please, eg.

var shipDate = tmp.toUTCString().slice(1,15);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download