Calculate an expected delivery date (accounting for holidays) in business days using JavaScript?

后端 未结 8 1582
悲&欢浪女
悲&欢浪女 2020-12-16 05:04

After revisiting this script, and some modifications, the following is available to allow a user to add a feature that calculates the expected delivery date.



        
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-16 05:13

    Your main problem was that adding safety each time meant you were adding multiple days each time it looped, instead of 1. So first loop = 1, second = 1+2, etc.

    I believe this works as you'd like:

    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
    console.log(">>> today = " + today);
    // now the loop...
    
    while( ++safety <30 ){
    ship.setDate(ship.getDate()+1 );
    switch( ship.getDay() ){
    
        case 0: // Sunday
        case 6: // Saturday
    
        break;
    
        default:
            counter++;
        }
    
    if( counter >= businessDays ) break;
    
    }
      // add a number of days
    // the expected shipping date
    
    
    console.log(">>> days  = " + businessDays);
    console.log(">>> ship = " + ship);
    

提交回复
热议问题