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?
The mozilla docs for setDate() don't indicate that it will handle end of month scenarios. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
setDate()
That is why I use setTime() when I need to add days.
No, javascript has no a built in function, but you can use a simple line of code
Our team considers date-fns the best library in this space. It treats dates as immutable (Moment.js will probably never adopt immutability), it's faster, and can be loaded modularly.
I am using the following solution.
Date has a constructor that accepts an int. This argument represents total milliseconds before/after Jan 1, 1970. It also has a method setTime which does the same without creating a new Date object.
What we do here is convert days to milliseconds and add this value to the value provided by getTime. Finally, we give the result to Date(milliseconds) constructor or setTime(milliseconds) method.
Just spent ages trying to work out what the deal was with the year not adding when following the lead examples below.
If you want to just simply add n days to the date you have you are best to just go:
or the longwinded version
This today/tomorrow stuff is confusing. By setting the current date into your new date variable you will mess up the year value. if you work from the original date you won't.
I had issues with daylight savings time with the proposed solution.
By using
getUTCDate
/setUTCDate
instead, I solved my issue.