views:

3625

answers:

3

How to add days to current DateTime using Java Script. Does Java Script have a built in function like .Net AddDay?

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

Be careful, because this can be tricky. When setting "tomorrow", it only works because it's current value matches the year and month for "today". However, setting to a date number like "32" normally will still work just fine to move it to the next month.

Joel Coehoorn
The accepted answer to this question looks strangely familiar. Curious. I guess I'll put my +1 here.
Tomalak
I did edit some, but you can see that this version still predated his answer. Ah, well.
Joel Coehoorn
Yeah? But WTF is this? (ran on March 31st, 2010):today = new Date();tomorrow = new Date();tomorrow.setDate(today.getDate()+1);alert(tomorrow.getMonth());Says "3". alert(tomorrow); is correct... Why???
sims
@sims month is 0 indexed. Month 3 is April
Joel Coehoorn
+5  A: 

You can create one with:-

 Date.prototype.addDays = function(days)
 {
     var dat = new Date(this.valueOf())
     dat.setDate(dat.getDate() + days);
     return dat;
 }

var dat = new Date()


alert(dat.addDays(5))

The problem with using setDate directly is that it's mutator and that sort of thing is best avoided. ECMA saw fit to treat Date as a mutable class rather than an immutable structure.

AnthonyWJones
FWIW, the Java Date class works in a similar fashion. Apparently, objects were expensive back in the '90s...
Shog9
+1  A: 

i use

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

This will deal with end of months so adding 32 days will work.

HTH

OneSHOT