You should really make your function with parameters, so that the function can be unaware of input/output details and does not have to reference document
.
Also, it is a habit to start function names with a lowercase letter unless it is a constructor (which is not the case here).
As to the algorithm: move the two given dates to the Sunday that precedes them (unless they already are Sundays). As getDay()
returns 0 for Sunday, you can just subtract the getDay()
number of days from the date, and it will be a Sunday. Remember how many working days you subtracted like that.
Then when both dates are Sundays, calculate the number of weeks between them and multiply this by 5 (working days).
Finally adjust this number by adding and subtracting the days you altered the dates with in order to make them align with Sunday.
Here is an interactive snippet:
function getDays(datefrom, dateto) {
datefrom = new Date(datefrom);
dateto = new Date(dateto);
let before = datefrom.getDay();
datefrom.setDate(datefrom.getDate() - before); // Go to previous Sunday
if (before) before--; // should be in {0,1,2,3,4,5}
let after = dateto.getDay();
dateto.setDate(dateto.getDate() - after); // Go to previous Sunday
if (after == 6) after--; // should be in {0,1,2,3,4,5}
// Count each 7 day difference as 5 days, and compensate for the changes to Sundays:
return Math.round((dateto - datefrom) / (1000 * 60 * 60 * 24)) / 7 * 5 + after - before
}
document.addEventListener("input", function () {
var datefrom = new Date(document.getElementById("datefrom").value);
var dateto = new Date(document.getElementById("dateto").value);
document.getElementById("numdays2").textContent = getDays(datefrom, dateto);
});
From: <input type="date" id="datefrom" value="2021-01-01"><br>
To: <input type="date" id="dateto" value="2021-01-01"><br>
Number of working days: <span id="numdays2">1</span>