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
2009-02-19 00:01:28
The accepted answer to this question looks strangely familiar. Curious. I guess I'll put my +1 here.
Tomalak
2009-02-19 00:59:06
I did edit some, but you can see that this version still predated his answer. Ah, well.
Joel Coehoorn
2009-02-19 01:19:47
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
2010-03-31 02:44:05
@sims month is 0 indexed. Month 3 is April
Joel Coehoorn
2010-03-31 03:26:38
+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
2009-02-19 00:10:35
FWIW, the Java Date class works in a similar fashion. Apparently, objects were expensive back in the '90s...
Shog9
2009-02-19 00:15:54
+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
2009-02-19 00:19:24