2

I have two datepicker from which I can calculate the number of day without counting Saturday and Sunday. But I want to do this for Friday and Saturday. I have tried some different ways but failed. It was easy for me to handle number of day excluding Saturday and Sunday but not for Friday and Saturday Following is my javascript code -

$(function() {
    $( "#startDate" ).datepicker({
        onSelect: calculateDays});
    });

    $(function() {
        $( "#endDate" ).datepicker({
            onSelect: calculateDays});
        });

        function calculateDays(startDate, endDate) {
            var form = this.form

            var startDate = document.getElementById("startDate").value;
            var startDate = new Date(startDate);

            var endDate = document.getElementById("endDate").value;
            var endDate = new Date(endDate);

            startDate.setHours(0,0,0,1); // Start just after midnight
            endDate.setHours(23,59,59,999); // End just before midnight

            var oneDay = 24*60*60*1000;
            var diff = endDate - startDate; // Milliseconds between datetime objects
            var days = Math.ceil(diff / oneDay);

            var weeks = Math.floor(days / 7);
            var days = days - (weeks * 2);

            // Handle special cases
            var startDay = startDate.getDay();
            var endDay = endDate.getDay();

            // Remove weekend not previously removed.
            if (startDay - endDay > 1)
                days = days - 2;

            // Remove start day if span starts on Sunday but ends before Saturday
            if (startDay == 0 && endDay != 6)
                days = days - 1

            // Remove end day if span ends on Saturday but starts after Sunday
            if (endDay == 6 && startDay != 0)
                days = days - 1

            if (days)
                document.getElementById("result").innerHTML=days;
        }

And my HTML is:

<form id="dateDifference" style="width:200px;">
    <input name="startDate" id="startDate" value="" >
    <input name="endDate" id="endDate" value="" >
</form>
<span id="result"></span>
HJ05
  • 1,358
  • 2
  • 11
  • 23
Md Riad Hossain
  • 291
  • 4
  • 21

4 Answers4

3
// Count days from d0 to d1 inclusive, excluding Fridays and Saturdays
function calculateDays( d0, d1 )
{
    var ndays = 1 + Math.round((d1.getTime()-d0.getTime())/(24*3600*1000));
    var nsaturdays = Math.floor((ndays + d0.getDay()) / 7);
    return ndays - 2*nsaturdays + (d0.getDay()==6) - (d1.getDay()==5);
}

where d0 and d1 are the start and end Date objects (with same hour of day values).

Matt
  • 20,108
  • 1
  • 57
  • 70
  • This code seemed to have issues to me ... depending on the end date. – Mike Q May 13 '15 at 13:36
  • function calculateBizDays( sDate, eDate ) { var saturday=7; var sunday=1; sDate.setHours(23); // this SHOULD be 0 but server is off by hour. sDate.setMinutes(0); sDate.getSeconds(0); eDate.setHours(0); // BPM is an HOUR OFF ? WHY? eDate.setMinutes(59); eDate.getSeconds(59); var ndays = 1 + Math.round(((eDate.getTime()*1000)-sDate.getTime())/(24*3600*1000)); var nsaturdays = Math.floor((ndays + sDate.getDay()) / 7); return ndays - 2*nsaturdays - (sDate.getDay()==sunday) - (eDate.getDay()==saturday); } – Mike Q May 13 '15 at 20:58
  • I had a few issues (due to some server date issues) but I was trying to calculate business days (i.e. excluding Sat and Sun) and found that it was giving weird results depending on the end date. What I did was set the hours in d0 and d1 with .setHours. – Mike Q May 13 '15 at 21:05
  • ps. ignore that I multiply eDate.getTime()*1000, and sDate.setHours should be 0, not 23 and endHours should be 23 not 0 .. lol – Mike Q May 13 '15 at 21:31
  • This doesnt work across weeks for me. Only returns business days of the last week in the range. – Piotr Kula Jun 02 '15 at 19:28
  • @ppumkin Please give an example of your function call. – Matt Jun 03 '15 at 18:31
  • I moved my call over to C# logic and use ajax to do the calculation. I also needed to do other database related stuff. I think I had an error in my dates, I think I forgot to set the day bit on start, I only noticed that after trying other examples. – Piotr Kula Jun 03 '15 at 19:16
  • 1
    @ppumkin In that case see my C# solution: http://stackoverflow.com/a/22054654/2700898 Note this skips Saturdays and Sundays. – Matt Jun 03 '15 at 19:20
  • @MikeQ Why do you define saturday=7 and sunday=1? It should be 6 and 0, respectively. Use the code as it is before saying it has issues ;) – Matt Nov 07 '15 at 11:35
2

one more approach.

for(var i = startDate ; i <= endDate ;i.setDate(i.getDate() + 1)){
            if( i.getDay() != 6 && i.getDay() != 0)
            {
                days = days + 1;
                }
            }

It will give you no.of days except saturday and Sunday

Jayababu
  • 1,641
  • 1
  • 14
  • 30
  • This approach helps if you want to exclude specific days from the calculation, such as national or banking holidays. The IF statement can include a check for the date within an array of holidays that you build yourself. – Lorien Brune Jul 17 '16 at 19:33
0

javascript Date method, getDay() will return 0 for Sunday, 1 for Monday, etc.

You should be able to use the date objects and check for the current day of the week and exclude them from the count for 5 (Friday) and 6 (Saturday).

http://www.w3schools.com/jsref/jsref_getday.asp

Matt
  • 477
  • 1
  • 5
  • 19
  • I know that. But I already mention that it was easy to calculate days without Saturday and Sunday because Saturday has the highest value(6) and other has the lowest. So every time you calculate the difference of day when it start with Saturday then you will get a value which is greater than 1 and you can easily minus 2 days when day difference is less than a week (7 days). But it was quite hard to do when I start calculate from Friday with day value 5. Sorry for poor English. – Md Riad Hossain Feb 25 '14 at 14:34
0

If you want to calculate number of working days in the year:

const monthWorkDays = (year, month) => 
new Array(32 - new Date(year, month, 32).getDate())
    .fill(1)
    .filter(
        (id, index) =>
            [0, 6].indexOf(
                new Date(year, month, index + 1).getDay()) === -1
            ).length;

const yearWorkDays = (year) =>
new Array(12)
    .fill(1)
    .reduce((pv, cv, index) => pv + monthWorkDays(year, index), 0);

yearWorkDays(2017)
Oleksandr Knyga
  • 625
  • 9
  • 9