1

Possible Duplicate:
How to add number of days to today’s date?

I would like to add X days , where X is the number I specified earlier, to the certain date.

Eg. the date is the 29/11/2012 (format: DD/MM/YYYY), and I would like to add 5 days to this date so the output should be 03/12/2012.

What have I tried:

var days_to_add = 5;
$myyear = 2012;
$mymonth = 11;
$myday = 29;
date = new Date();
date.setFullYear($myyear,$mymonth,$myday);
date.setDate(date.getDate()+(days_to_add-1));
alert(date.getDate()+'/'+date.getMonth()+'/'+date.getFullYear());

It is working, but only when the date doesnt pass to the next month of a given date, otherwise, the output is good.

Have you guys any solutions for that?

Community
  • 1
  • 1
Scott
  • 5,991
  • 15
  • 35
  • 42

2 Answers2

3

Something simpler like this ?

 var fiveDaysLater = new Date( existingDate.getTime() );
 fiveDaysLater.setDate(fiveDaysLater.getDate() + 5);
topcat3
  • 2,561
  • 6
  • 33
  • 57
1

Your problem isn't in the day addition, as the setDate function increments automatically the year or month if needed :

If the parameter you specify is outside of the expected range, setDate attempts to update the date information in the Date object accordingly

But you're not creating your date correctly. Change

$myyear = 2012;
$mymonth = 11;
$myday = 29;
date = new Date();
date.setFullYear($myyear,$mymonth,$myday);

to

$myyear = 2012;
$mymonth = 11;
$myday = 29;
date = new Date($myyear,$mymonth,$myday);

The Date constructor takes a month in [0, 11]. If you want 11 to be november and not december, use

date = new Date($myyear,$mymonth-1,$myday);

And getMonth returns an integer in [0, 11], which may have surprised you too. You need to output date.getMonth()+1 if you want to have the usual date formating :

alert(date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear());

If you want to add leading zeros, you could do this :

alert(
     (date.getDate()<10 ? "0" : "") + date.getDate()
     +'/'+
     (date.getMonth()<9 ? "0" : "") + (date.getMonth()+1)
     +'/'+
     date.getFullYear() 
);

Demonstration

Note that if you have many date manipulations to do, you should consider using a library like date.js.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758