title: How to calculate business hours between two dates in javascript when date difference is large?
body: <p>I'm making home page for employee management.
  I want to get business hours between two dates.
  I already searched and get one method from this link.  <a href="http://rion.io/2014/06/20/calculating-business-hours-in-javascript/" rel="nofollow noreferrer">http://rion.io/2014/06/20/calculating-business-hours-in-javascript/</a></p>
  <pre><code>// Simple function that accepts two parameters and calculates
  // the number of hours worked within that range
  function workingHoursBetweenDates(startDate, endDate) {  
      // Store minutes worked
      var minutesWorked = 0;
  
      // Validate input
      if (endDate &lt; startDate) { return 0; }
  
      // Loop from your Start to End dates (by hour)
      var current = startDate;
  
      // Define work range
      var workHoursStart = 9;
      var workHoursEnd = 18;
      var includeWeekends = false;
  
      // Loop while currentDate is less than end Date (by minutes)
      while(current &lt;= endDate){          
          // Is the current time within a work day (and if it 
          // occurs on a weekend or not)          
          if(current.getHours() &gt;= workHoursStart &amp;&amp; current.getHours() &lt; workHoursEnd &amp;&amp; (includeWeekends ? current.getDay() !== 0 &amp;&amp; current.getDay() !== 6 : true)){
                minutesWorked++;
          }
  
          // Increment current time
          current.setTime(current.getTime() + 1000 * 60);
      }
  
      // Return the number of hours
      return minutesWorked / 60;
  }
  </code></pre>
  <p>I tried this method but performance is bad when date difference large such as <code>2020-01-01 12:45:00 - 2028-10-06 23:10:33</code>.</p>
  <p>So I make new function myself. But sometimes is wrong.</p>
  <pre><code>function workingHoursBetweenDates(startDate, endDate) {
    const startWeekday = startDate.getDay();
    const endWeekday = endDate.getDay();
    let workHours = Math.abs(endDate.getTime() - startDate.getTime()) / 3600000 / 3;
    let restDays = Math.floor(workHours / 8 / 7) * 2;
    workHours -= (restDays * 8);
    return workHours;
  }
  </code></pre>
  <p>Please anyone help. thanks.</p>