kenan salim kenan salim - 6 months ago 16
Javascript Question

Adding months to current date and if its saturday adding 2 days to input?

I need to add months so I use

date.getMonth() +8;
and its a Saturday but I need to eliminate weekends. If I add these lines of code:

if(date.getDay() % 6)
var date.getdate()+1;


It doesn't work. So what can i do?
Here to fiddle https://jsfiddle.net/a3f3yb0s/
and here to snippet



var date = new Date();

var day = date.getDate();
var month = date.getMonth() +8;
var year = date.getFullYear();
var year2 = date.getFullYear() +1;


if(month>12) {
month=month%12;
year=year2;
}

if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;

var today = year + "-" + month + "-" + day;


document.getElementById('theDate').value = today;

<input type="date" id="theDate">




Answer

Why not just do the calculations on the date object and let the browser handle all the calendar calculations:

// get a date object
// 8 months from 2016-01-01 is a Saturday
var date = new Date(2016, 1, 1);

// add 8 months
date.setMonth(date.getMonth() + 8);

alert(date); // will show a Saturday

// check if it is a saturday
if(date.getDay() == 6)
{
  // if it is then add two days
  date.setDate(date.getDate() + 2);
}

alert(date); // will show a Monday

Comments