Rhs Rhs - 5 months ago 8
Javascript Question

Incorrect Javascript Day When Added?

I have a javascript function that takes in a number

X
and a date, and returns a new
Date
that is
X
number of days away:

function addDays(theDate, numDaysToAdd) {
var newDate = new Date();
return new Date(newDate.setDate(theDate.getDate() + numDaysToAdd));
}


I pass it a day that is
Sat Jul 02 2016 16:03:06 GMT-0700 (Pacific Daylight Time)
and a number
7
, but the result I got was
Thu Jun 09 2016 16:05:32 GMT-0700 (Pacific Daylight Time)
. Why is it giving me the correct date but wrong month?

Answer

The problem is that newDate is always created from the current date (new Date()). In other words, if this function is executed in June it will produce a date in June, then try to set a the day of the month as a offset from the input date.

You need to construct newDate as a copy of theDate:

function addDays(theDate, numDaysToAdd) {
    var newDate = new Date(theDate);
    newDate.setDate(theDate.getDate() + numDaysToAdd);
    return newDate;
}

var d = new Date('Sat Jul 02 2016 16:03:06 GMT-0700 (Pacific Daylight Time)');
console.log(addDays(d, 7).toString());

Comments