How to add days to current Date
using JavaScript. Does JavaScript have a built in function like .Net's AddDay
?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
There's a setDate and a getDate method, which allow you to do something like this :
If you want to both subtract a number of days and format your date in a human readable format, you should consider creating a custom
DateHelper
object that looks something like this :(see also this Fiddle)
I created these extensions last night:
you can pass either positive or negative values;
example:
Correct Answer:
Incorrect Answer:
This answer sometimes provides the correct result but very often returns the wrong year and month. The only time this answer works is when the date that you are adding days to happens to have the current year and month.
Proof / Example
Check this JsFiddle
Try
Using setDate() to add a date wont solve your problem, try adding some days to a Feb month, if you try to add new days to it, it wont result in what you expected.
Edit: Instead of
setTime()
(orsetHours()
) you could do it this way:Old:
Instead of using
setTime()
you can usesetHours()
:See the JSFiddle...
For those using Angular:
Just do: