0

I know this question is asked a lot of times. And i did my research, but i really don't understand it. I just started using javascript.

This is my code to calculate days between the two inputs.. I erased my attempts to calculate weekend.

function GetDays(){
var datefrom = new Date(document.getElementById("datefrom").value);
var dateto = new Date(document.getElementById("dateto").value);
return parseInt((dateto - datefrom) / (1000 * 60 * 60 * 24));
}
function cal(){
    if(document.getElementById("dateto")){
        document.getElementById("numdays2").innerHTML=GetDays();
    } 
}

An answer in PHP is also good for me. Hope someone can help me.

Timo
  • 11
  • 4

1 Answers1

0

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>
trincot
  • 317,000
  • 35
  • 244
  • 286
  • Thank you. Note that I made a last-second adjustment to the line with `after--`. Make sure you got that ;-) – trincot Apr 15 '21 at 10:06