0

I'm trying to figure out the proper way to get the javascript Date object for 8 days in the future from today.

Why? because I want to subtract a given Date from today's date and if it is less than or equal to 8 days in the future then do something.

So, I figured out how to parse the given date with new Date('2014-11-21T00:00:00.000-05:00') and get the date object from that and then I can subtract it from today like so: new Date('2014-12-25T00:00:00.000-05:00') - new Date() and then I have to compare that to the date object for 8 days in the future - today's date object.

Here's how I thought about doing the date object for the date 8 days in the future: I created a new Date with all measurements of time the same as today except I added 8 to the day. This works, except what if today is less than 8 days from the end of the month, then how do I get it to overflow into the next month. For example the 27th + 8 ( of october ) should be november 4th and not october's 35th.

wordSmith
  • 2,993
  • 8
  • 29
  • 50
  • Not probably the answer but you can take a look at [Moment.js](http://momentjs.com/) for easy date and time manipulation. – Joseph Oct 13 '14 at 14:31
  • Downvote for no research. There are [numerous](http://stackoverflow.com/questions/4320019/adding-subtracting-days-from-a-date-doesnt-change-the-year-month-correctly) [duplicates](http://stackoverflow.com/questions/10931288/how-to-add-subtract-dates-with-javascript) [on](http://stackoverflow.com/questions/1296358/subtract-days-from-a-date-in-javascript) [StackOverflow](http://stackoverflow.com/questions/8489500/how-do-i-subtract-one-week-from-this-date-in-jquery). – admdrew Oct 13 '14 at 14:34
  • @admdrew what's the proper way to search SO as nothing that worked came up when I Googled my issue. – wordSmith Oct 13 '14 at 14:38
  • @user3743069 I found all of those from [this Google search](https://www.google.com/search?q=javascript+date+add+subtract+days). – admdrew Oct 13 '14 at 14:39
  • @admdrew okay, what did you search. I searched add 8 days to js Date – wordSmith Oct 13 '14 at 14:51
  • 2
    @user3743069 I know you already have a working answer, but I want to point out a valuable resource to you: MDN (Mozilla Developer Network) has excellent JavaScript reference (among other things). Their [Date.prototype.setDate()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate) page, for instance, provides example of the "month wrapping" behavior (if the number is beyond the # of days in the month). – Troy Gizzi Oct 13 '14 at 14:54

1 Answers1

4
 var date = new Date();
 date.setDate((date.getDate() + 8));
 //date.setDate((date.getDate() - 8)); example of subtracting

This is how you add or subtract days from a date. This will automatically account for month to month role over.

brso05
  • 13,142
  • 2
  • 21
  • 40