0

I am trying to pull some historical data, which has a variety of time stamps. I want the use to a user selected date, and then pull all days + some additional days. Date1 is

var Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020"
var startDate = new Date(Date1)

var Enddate = new Date();
Enddate.setDate(startDate + 10);

This doesn't work. I cant seem to figure out how to add the "10 days" to the Date1 variable.

Carlo B.
  • 119
  • 2
  • 16

2 Answers2

2

You need the getDate function of the Date object, and you'll need to pass the correct value when instantiating the new Date.

Try this:

var Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020"
var startDate = new Date(Date1);
// add it to startDate, using getDate()
startDate.setDate(startDate.getDate() + 10);

// now startDate will be 10 days later:
startDate; // Sun Nov 01 00:00:00 GMT-04:00 2020

// if you want an entirely new Date object, then instantiate a new one:
var Enddate = new Date(startDate);

If you want two different variables, then you can use the approach similar to what you tried, like so:

var Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020"
var startDate = new Date(Date1), second = new Date(Date1);      // we're using another temporary variable

// add the days
second.setDate(second.getDate() + 10);
// now use Enddate with this
var Enddate = new Date(second);

Enddate; // Sun Nov 01 00:00:00 GMT-04:00 2020
Deolu A
  • 752
  • 1
  • 6
  • 13
  • 1
    fantastic! this worked exactly as needed. Didn't realize I needed to use the getDate() after the variable – Carlo B. Dec 10 '20 at 17:19
0

You can't just add a number to a Date object to get a new date.

You can add to a date by:

  1. getting the current day of the month with getDate()
  2. adding a number of days to that result
  3. setting the new date with setDate()

const Date1 = "Thu Oct 22 00:00:00 GMT-04:00 2020";
const addDays = 10;

const startDate = new Date(Date1);
const startDays = startDate.getDate();

const newDate = new Date(startDate);
newDate.setDate(startDays + addDays);

console.log('startDate:', startDate.toISOString());
console.log('newDate:', newDate.toISOString());

Note:

Passing a string into the Date constructor is discouraged, as it produces inconsistent results across browsers.

It is better to pass in the individual date and time values:

const Date1 = new Date(2020, 9, 22, 0, 0, 0);
terrymorse
  • 6,771
  • 1
  • 21
  • 27
  • 1
    Adding a day by adding 24 hours isn't a good idea because where daylight saving is observed, not all days are 24 hours long. See the duplicate. – RobG Dec 10 '20 at 23:19