Javascript add days to date

Posted by leonc on 20-Nov-2018 15:38

I created a trigger that updates a date (DueDate) field and adds 28 days to a date that is another date field (IssuedDate) in the object.

The code is the following:

var issueDate = new Date({!Issued_Date#iso});
var dueDate = new Date();
dueDate.setDate(issueDate.getDate() + 28);
return dueDate;

But it doesn't work as expected.

Thank you in advance.

Posted by jniemi@vyco.com on 20-Nov-2018 15:56

Hi leonc. The setDate function is used to set the actual date to the value you pass in, not to add days to a given date.  When we update dates, I always convert to the date to milliseconds, add the required number of milliseconds based on what I am trying to do and then use that to create the new date.

Here is a sample from one of my apps that is calculating a reminder date/time based on some inputs. Hopefully this will help.

function setNotificationTime() {

 var startDateTime = new Date("{!startDate}");

     startDateTime = startDateTime.getTime();

 var reminderMS = {!Reminder_Minutes} * 60 * 1000;

 var reminderTime = new Date(startDateTime - reminderMS);

 return reminderTime;

} setNotificationTime();

Something like this should get you a new date 28 days from your issue date.

var issueDate = new Date({!Issued_Date#iso});

    issueDate = issueDate.getTime();

var dayAddInMs = 28 *24*60*60*1000;

var dueDate = new Date(issueDate + dayAddInMs);

return dueDate;

All Replies

Posted by jniemi@vyco.com on 20-Nov-2018 15:56

Hi leonc. The setDate function is used to set the actual date to the value you pass in, not to add days to a given date.  When we update dates, I always convert to the date to milliseconds, add the required number of milliseconds based on what I am trying to do and then use that to create the new date.

Here is a sample from one of my apps that is calculating a reminder date/time based on some inputs. Hopefully this will help.

function setNotificationTime() {

 var startDateTime = new Date("{!startDate}");

     startDateTime = startDateTime.getTime();

 var reminderMS = {!Reminder_Minutes} * 60 * 1000;

 var reminderTime = new Date(startDateTime - reminderMS);

 return reminderTime;

} setNotificationTime();

Something like this should get you a new date 28 days from your issue date.

var issueDate = new Date({!Issued_Date#iso});

    issueDate = issueDate.getTime();

var dayAddInMs = 28 *24*60*60*1000;

var dueDate = new Date(issueDate + dayAddInMs);

return dueDate;

Posted by leonc on 20-Nov-2018 16:13

That was very helpful.

Thanks.

This thread is closed