4

I need to use basic javascript here and I'm not well versed with it. I do not want to use jquery (although I would prefer it)

I need to get the current date via javascript, add 2 days to it, then display the new date (with the 2 additional days factored in). This means on the 30 or 31st of the month, the month needs to rollover as does the year on Dec 30/31.

Thanks to this question and Samuel Meadows I can get the current date. I can add 2 days no problem. But I can't work out how to get the months (and year) to rollover properly.

Samuel's code:

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!

var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} var today = mm+'/'+dd+'/'+yyyy;

document.write(today);

Any assistance would be greatly appreciated.

Thanks!

Community
  • 1
  • 1
Scott
  • 21,475
  • 8
  • 43
  • 55

3 Answers3

11

The date object will take care of this for you:

var date = new Date("March 30, 2005"); // get an edge date
date.getMonth(); // 2, which is March minus 1
date.setDate( date.getDate() + 2); //Add two days
date.getMonth(); //Now shows 3, which is April minus 1
Dennis
  • 32,200
  • 11
  • 64
  • 79
2

Convert the number of days to milliseconds, and then add them to the date in question http://jsfiddle.net/Mn5Wz/

MK_Dev
  • 3,291
  • 5
  • 27
  • 45
0

Here is the code to add days to the current date

​var today = new Date();
 console.log(addDate(today, 2));

 function addDate(dateObject, numDays) {

     dateObject.setDate(dateObject.getDate() + numDays);

     return dateObject.toLocaleDateString();
 }
Scorpion-Prince
  • 3,574
  • 3
  • 18
  • 24