0

I have the following script that when used, allows the user to see a future date, while excluding weekends. The problem i've encountered though is if the current day is Friday, and i set the future date to 3 days it counts the Saturday and Sunday as working days. I'm really hoping one of you may be able to help as I'm not really that great at Javascript.

The correct example would be: If Today = Friday then 3 working days from now would be Wednesday (not Monday as the script currently calculates it).

Any ideas?

          var myDelayInDays = 3; 
          myDate=new Date();
          myDate.setDate(myDate.getDate()+myDelayInDays);

          if(myDate.getDay() == 0){//Sunday
            myDate.setDate(myDate.getDate() + 2);//Tuesday
          } else if(myDate.getDay() == 6){//Saturday
            myDate.setDate(myDate.getDate() + 2);//Monday
          }

          document.write('' + myDate.toLocaleDateString('en-GB'));

Any help would really be great. Thanks

sainu
  • 2,686
  • 3
  • 22
  • 41
head_bigg
  • 241
  • 1
  • 2
  • 8
  • check if myDate.getDay() == 5 then add 2 + (the no of day you wanna extend) 2 for skipping sat and sun – Vinod Louis Apr 07 '17 at 10:15
  • You should work with milliseconds or you could use a library as moment.js – Fabio Campinho Apr 07 '17 at 10:32
  • @VinodLouis I think that would only work if the future date LANDS on a Friday. I need it to calculate TODAY as a friday before proceeding (if that makes sense). Example: Today is Friday, + 3 Days should display Wednesday (not Monday). – head_bigg Apr 07 '17 at 10:38
  • yes if you find today is friday then add 5 instead of 3 taking the 2 sat sun as buffer – Vinod Louis Apr 07 '17 at 10:44
  • @VinodLouis The problem with your solution is that if Today = Mon-Thursday then this will not provide the correct future date. I need something that is variable – head_bigg Apr 07 '17 at 11:37

1 Answers1

1

Try this code by changing date and days to add, A custom loop is used to skip sat and sun

function addDates(startDate,noOfDaysToAdd){
  var count = 0;
  while(count < noOfDaysToAdd){
    endDate = new Date(startDate.setDate(startDate.getDate() + 1));
    if(endDate.getDay() != 0 && endDate.getDay() != 6){
       //Date.getDay() gives weekday starting from 0(Sunday) to 6(Saturday)
       count++;
    }
  }
  return startDate;
}


var today = new Date();
var daysToAdd = 3;
alert(addDates(today,daysToAdd));
Vinod Louis
  • 4,812
  • 1
  • 25
  • 46
  • This is PERFECT! Except, is there a way to have the result displayed as: dd/mm/yyyy? (en-GB) – head_bigg Apr 07 '17 at 13:24
  • There are many ways to do that sew this http://stackoverflow.com/questions/13459866/javascript-change-date-into-format-of-dd-mm-yyyy – Vinod Louis Apr 07 '17 at 13:27