Reputation: 33
In the spreadsheet I can have a date in one cell then in the next cell over I can type in =A1+1 and it adds 1 day to the date in cell A1. I would like to do the same thing in a script.
I can set a date variable to today's date using the following.
var dateTracking = "";
dateTracking = currentDate;
But if I try to add 1 to dateTracking then it changes the variable from date format to a string
dateTracking = dateTracking + 1;
I just want a quick easy solution to add 1 or more days to a date variable.
Upvotes: 0
Views: 533
Reputation: 33
The previous answer worked for adding days but as I worked on my script I found myself needing to add months too. I could just add dayInMS*30.4167 but that would get me some variance in the day. I wanted the get the same date each month.
Here is a solution that I had found and it will work for adding days, months, years.
var currentDate = new Date();
var monthTest = "";
var monthTest2 = "";
var monthTest3 = "";
var year = "";
var month = "";
var day = "";
//start at today
dateTracking = currentDate;
//testing month
day = dateTracking.getDate();
month = dateTracking.getMonth();
year = dateTracking.getYear();
monthTest = new Date(year, month, day+1);
monthTest2 = new Date(year, month+1, day);
monthTest3 = new Date(year+1, month, day);
Upvotes: 2
Reputation: 26836
There are several ways to realize your request, but the easiest would probably be:
Sample:
var dateTracking=new Date() // returns the date of today
var dateTrackingInMs=dateTracking.getTime();
var dayInMs=24*60*60*1000;
var newDateTracking=new Date(dateTrackingInMs+dayInMs);
Upvotes: 0