exclude weekends in javascript date calculation

前端 未结 4 580
甜味超标
甜味超标 2020-11-28 16:22

I have two sets of codes that work. Needed help combining them into one.

This code gets me the difference between two dates. works perfectly:

functio         


        
4条回答
  •  半阙折子戏
    2020-11-28 17:13

    @RobG has given an excellent algorithm to separate business days from weekends. I think the only problem is if the starting days is a weekend, Saturday or Sunday, then the no of working days/weekends will one less.

    Corrected code is below.

    function dateDifference(start, end) {
    
      // Copy date objects so don't modify originals
    
      var s = new Date(start);
      var e = new Date(end);
    
        var addOneMoreDay = 0;
        if( s.getDay() == 0 || s.getDay() == 6 ) {
        addOneMoreDay = 1;
      }
    
      // Set time to midday to avoid dalight saving and browser quirks
      s.setHours(12,0,0,0);
      e.setHours(12,0,0,0);
    
      // Get the difference in whole days
      var totalDays = Math.round((e - s) / 8.64e7);
    
      // Get the difference in whole weeks
      var wholeWeeks = totalDays / 7 | 0;
    
      // Estimate business days as number of whole weeks * 5
      var days = wholeWeeks * 5;
    
      // If not even number of weeks, calc remaining weekend days
      if (totalDays % 7) {
        s.setDate(s.getDate() + wholeWeeks * 7);
    
        while (s < e) {
          s.setDate(s.getDate() + 1);
    
          // If day isn't a Sunday or Saturday, add to business days
          if (s.getDay() != 0 && s.getDay() != 6) {
            ++days;
          }
          //s.setDate(s.getDate() + 1);
        }
      }
      var weekEndDays = totalDays - days + addOneMoreDay;
      return weekEndDays;
    }
    

    JSFiddle link is https://jsfiddle.net/ykxj4k09/2/

提交回复
热议问题