Coder Perfect

What is the best way to add days to a date?

Problem

How can I use JavaScript to add days to the current date? Is there a built-in function in JavaScript that works like AddDay() in.NET?

Asked by Ashesh

Solution #1

You can make one by combining the following elements:-

If the month needs to be incremented, this takes care of it automatically. Consider the following scenario:

8/31 plus 1 day is 9/1.

The problem with using setDate directly is that it’s a mutator, which should be avoided if possible. Date was treated as a mutable class rather than an immutable structure by ECMA.

Answered by AnthonyWJones

Solution #2

Correct Answer:

function addDays(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}

Incorrect Answer:

This response occasionally delivers the proper result, but it frequently returns the incorrect year and month. Only when the date to which you are adding days has the current year and month will this solution work.

// Don't do it this way!
function addDaysWRONG(date, days) {
  var result = new Date();
  result.setDate(date.getDate() + days);
  return result;
}

Proof / Example

Check this JsFiddle

Answered by sparebytes

Solution #3

var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);

Be cautious because this is a delicate situation. Only because its present value matches the year and month for today does it function when setting tomorrow. Setting it to a date number like “32” will, in most cases, suffice to transfer it to the next month.

Answered by Joel Coehoorn

Solution #4

My basic answer is as follows:

nextday=new Date(oldDate.getFullYear(),oldDate.getMonth(),oldDate.getDate()+1);

Daylight saving time is not an issue with this solution. In addition, any offset for years, months, days, and so on can be added or subtracted.

day=new Date(oldDate.getFullYear()-2,oldDate.getMonth()+22,oldDate.getDate()+61);

is correct code.

Answered by sbrbot

Solution #5

These responses are perplexing to me; instead, I prefer:

var ms = new Date().getTime() + 86400000;
var tomorrow = new Date(ms);

Since 1970, getTime() has returned milliseconds, with 86400000 being the number of milliseconds in a day. As a result, for the specified date, ms contains milliseconds.

The desired date object can be obtained by using the millisecond constructor.

Answered by Jason

Post is based on https://stackoverflow.com/questions/563406/how-to-add-days-to-date