albatross_uk albatross_uk - 2 years ago 117
Javascript Question

Adding Days to Date - Google Scripts

I'm fairly new to this, so apologies if the answer is glaringly obvious.

I am trying to add and subtract days from today's date. The idea is eventually to calculate the date of next Monday and last Monday.

I've looked here which solved my first problem, but the next is perplexing me: subtracting days from today's date works without issue. Adding gives an invalid date.

The code is:

function findDate() {
var d = new Date();
var n = d.getDay();
var makeDate = new Date(d.setDate(d.getDate()));
var weekDaysTo = new Array(7); //array of days to following Monday
weekDaysTo[0]= 1
weekDaysTo[1] = 7
weekDaysTo[2] = 6
weekDaysTo[3] = 5
weekDaysTo[4] = 4
weekDaysTo[5] = 3
weekDaysTo[6] = 2

Logger.log('weekDaysTo gives '+weekDaysTo[n])

var weekDaysFrom = new Array(7); //array of days to previous Monday
weekDaysFrom[0]= 6
weekDaysFrom[1] = 0
weekDaysFrom[2] = 1
weekDaysFrom[3] = 2
weekDaysFrom[4] = 3
weekDaysFrom[5] = 4
weekDaysFrom[6] = 5

var prevMon = new Date(makeDate+weekDaysTo[n]*3600000*24); //Converts ms into days and adds

Logger.log('Next Monday is '+prevMon);

var followingMon = new Date(makeDate-weekDaysFrom[n]*3600000*24); //Converts ms into days
Logger.log('Last Monday was ' +followingMon);

The Log Output is:

[16-05-22 21:17:58:419 ICT] Sun May 22 21:17:58 GMT+07:00 2016
[16-05-22 21:17:58:419 ICT] weekDaysTo gives 1
[16-05-22 21:17:58:420 ICT] Next Monday is Invalid Date
[16-05-22 21:17:58:420 ICT] Last Monday was Mon May 16 2016 21:17:58 GMT+0700 (ICT)

This is irrespective of the value I add to the date. I can't see why subtracting works fine, but adding causes an invalid date. Changing the numbers added has no effect, changing it to subtraction works.

Answer Source

That's because JavaScript handles addition and subtraction different depending on the types of the operands.

> new Date()
Sun May 22 2016 14:45:00 GMT+0000 (UTC)
> new Date()+1
'Sun May 22 2016 14:45:05 GMT+0000 (UTC)1'
> new Date()-1

In your example, you should try converting makeDate to milliseconds before performing addition, either by doing +makeDate or makeDate.getTime().

For example, instead of:

var prevMon = new Date(makeDate+weekDaysTo[n]*3600000*24);


var prevMon = new Date(+makeDate+weekDaysTo[n]*3600000*24);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download