Add/Subtract Days to a Date and pass to a Record Object

Less than one minute read time.
Dates can be a bit of a challenge. This article explains three points:
  • how to convert a record's date field value into a JavaScript Date object.
  • how to add/subtract days to a JavaScript Date object.
  • how to pass a JavaScript Date object to a record's date field value.

1. How to convert a record's date field value into a JavaScript Date object

var cardate = new Date (carRecord.vcar_DateMade);

Please read the article "Validation of Dates" which discusses the parsing rules that need to be followed to successfully create a date object.

2. How to add/subtract days to a JavaScript Date object

cardate.setDate(cardate.getDate() -14 );


3. How to pass a JavaScript Date object to a record's date field value

// myRecord is a communication record (already created) 
myRecord.Comm_ToDateTime = cardate.getVarDate() ;



That's it!! It's easy once you know!

External Link:

  • When adding days/months/years, be aware of the data types when adding. In my case, I'm getting the 'days to add' value from the database. Example: today is Aug 14 2016 (8/14/2016), and comp_reviewdays = 30

    var result = new Date();

    var revDays = myCompRecord.comp_reviewdays;

    var revDaysInt = parseInt(revDays);

    result.setDate(result.getDate() + revDays); >> result date is 6/20/2020 (huh? this is 1,430 days)

    result.setDate(result.getDate() + revDaysInt); >> result date is 9/13/2016 (correct)

  • Thanks for the comment. You are quite right. The article was too simplistic and didn't take into account the format of the date string passed to the new Date() constructor. I have edited the article and added a link to another article that discusses the allowed string format in more detail.

  • Hi Jeff,

    Please correct me if I am wrong, but I dont think the above code works;

    var cardate = new Date (carRecord.vcar_DateMade);

    When created like this, cardate is showing a date of 04/06/2009, instead of 06/04/2009. I have checked User settings for the user I am logged in as, as well as language. It seems that javascript is assuming mm/dd/yyyy over dd/mm/yyyy. I also checked the machine's locale, which is set to UK English.

    Shawn