1

i have the date 2013-12-28 and i want add one or more more day to it. so if i add one more day it will be 2013-12-29.
i try to add it by adding the value of it's date (date 28+1), it works, but what if i add 7 more day to it? the date will be 35, and of course it is not a valid date format.
can someone help me?
here's the example of my script:

var d = new Date();
var Y = d.getFullYear();
var M = d.getMonth()+1;
var D = d.getDate();
var DT = d.getDate()+1;// what if i + 20 days from today? the format would be invalid

var today = Y+"-"+M+"-"+D;
var tomorrow = Y+"-"+M+"-"+DT;
alert(today+" <> "+tomorrow);
// "<>" means nothing
Oki Erie Rinaldi
  • 1,835
  • 1
  • 22
  • 31

3 Answers3

5

You may try like this using getdate(), setdate() and getdate():

var myDate = new Date();
myDate.setDate(myDate.getDate() + 7);
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
3

If you already have a date object as in the code you show:

 var d = new Date();

...then you can add 7 days to it like this:

d.setDate( d.getDate() + 7 );

...and it will automatically increment the month if needed.

Further reading:

If you need to extract the year, month and day in order to format the result a particular way do so after adding days.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0

The solution is to convert your date string into unix timestamp, and them add 3600 * 24 * <number of days> to the timestamp and them convert it back to date string.

The code can be as follows:

function addDaysToDate(date, days) {
    var time = Date.parse(date) + days * 24 * 3600;
    date = new Date(time);
    return date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();
}
var date = '2013-12-28';
console.log(addDaysToDate(date, 7));
TwilightSun
  • 2,275
  • 2
  • 18
  • 27