0

I have to calculate variables in javascript after x days from current day.I have to add some number of days based on some input parameter.

var currentDate = new Date();
var dd = currentDate.getDate();
var mm = currentDate.getMonth()+1; 
var yyyy = currentDate.getFullYear();

if(dd<10) {
    dd='0'+dd
} 

if(mm<10) {
    mm='0'+mm
} 

currentDate= mm+'/'+dd+'/'+yyyy;

Now I want to get some date after 28 days from currentDate variable but it should not include Saturday and Sunday.

So my question is how to exclude the weekends (2 days) from the 28 (for example).

Any help will be appreciated.

  • what about holidays? Please show what you have tried. There are lots and lots of posts on SO and on the web about getting days difference and also libraries that are useful for this like `moment.js` – charlietfl Sep 15 '15 at 15:42
  • Thanks @charlietfl ..Right now holiday is not in scope as it may differ country to country.I am looking for Saturday and Sunday. –  Sep 15 '15 at 15:43
  • check out this SO link which shows you how to know if the day is a weekend(sat/sun). This may help you to build your logic. http://stackoverflow.com/questions/3551795/how-to-determine-if-date-is-weekend-in-javascript – Gaurav Shah Sep 15 '15 at 15:48
  • Yes it is only determining if the day is weekend.But how many weekends in span of days. –  Sep 15 '15 at 16:04

3 Answers3

1

Here's a generic function to add n business days to a date

function addDays(dt, n) {
    var rem = n % 5;
    var add = 7 * (n - rem) / 5 + rem;
    var ret = new Date(dt);
    ret.setDate(ret.getDate() + add);
    if (ret.getDay() == 6) ret.setDate(ret.getDate() + 2);
    else if (ret.getDay() == 0) ret.setDate(ret.getDate() + 1);
    return ret;
}
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
0

This is really simple. Script below goes through all days between start and end date and checks if it isn't Saturday (tmpDate.getDay() != 6) or Sunday (tmpDate.getDay() != 0)

var start = new Date();
var end = new Date(2016, 6, 1);
var allDays = Math.floor((end.getTime() - start.getTime())/ 86400000);

var workingDays = 0;
for(var i = 0; i < allDays; i++){
    var tmpDate = new Date();
    tmpDate.setTime(today.getTime() + i * 24*60*60*1000);
    if(tmpDate.getDay() != 0 && tmpDate.getDay() != 6)
        wokringDays++;
}

alert(workingDays);
Peter G
  • 155
  • 1
  • 8
0

This will give you the number of working days:

function getWorkingDays(currentDateObj, numberOfDays)
{
  if(numberOfDays < 0) return false;
  var futureDateObj = new Date();
  futureDateObj.setDate(currentDateObj.getDate() + numberOfDays);

  var daysCnt  = 1 + Math.round((futureDateObj.getTime()-currentDateObj.getTime())/(24*3600*1000));
  var weekCnt  = Math.floor( (currentDateObj.getDay() + daysCnt) / 7 );
  var weekends = 2 * weekCnt + (currentDateObj.getDay()==0) - (futureDateObj.getDay()==6);
  return numberOfDays - weekends;
}
console.log(getWorkingDays(new Date(), 28));
Beroza Paul
  • 2,047
  • 1
  • 16
  • 16