Setting Date based on another Date

I'm trying to set a date field with JavaScript based on the value of another Date field. I used the code on the forms example page https://plumsail.com/docs/forms/how-to/conditional-fields.html but it isn't working quite correctly. I'm only adding 2 days, not 14, but I've tried other numbers and it still isn't working.

If the start date is October 1st, I expect the new date to be October 3rd, but the code is returning September 3rd.


Any ideas why?

function setDay3EmailDate() {
	if (fd.field('Start_x0020_Date').value) {
		var startDate = fd.field('Start_x0020_Date').value;
		console.log(startDate);
		var emailDate = new Date();
		emailDate.setDate(startDate.getDate() + 2);
		console.log(emailDate);
		fd.field('Day3EmailDate').value = emailDate;
	}
}

Hi Maura,

It’s a common problem in JavaScript when year and month are calculated incorrectly while adding days to the date. I suggest you use this function:

function addDays(startDate,numberOfDays)
{
    var returnDate = new Date(
        startDate.getFullYear(),
        startDate.getMonth(),
        startDate.getDate()+numberOfDays,
        startDate.getHours(),
        startDate.getMinutes(),
        startDate.getSeconds());
    return returnDate;
}

var startDate = fd.field('Start_x0020_Date').value;
fd.field('Day3EmailDate').value = addDays(startDate, 2);