1

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?

0

2 Answers 2

1

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());

Sign up to request clarification or add additional context in comments.

Comments

1

You can add number of milliseconds to given date and it will generate correct date.

getTime() returns milliseconds from epoch.

offset = numDaysToAdd * 24 * 60 * 60 * 1000;

24: Hours in a day

60: Minutes in an hour

60: seconds in a minute

1000: milliseconds in a second

Date constructor takes milliseconds from epoch

function addDays(theDate, numDaysToAdd) {
    var start = theDate.getTime();
    var offset = numDaysToAdd * 24 * 60 * 60 * 1000;
    return new Date(start + offset);
}

var today = new Date();
console.log(today, addDays(today, 10));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.