-2

I'm trying to add days to a Date object, but the output is not as desired:

// THIS IS JUST A SIMPLIFIED EXAMPLE.

let date = new Date("2019-01-01 00:00:00")
let finalDate = new Date()

finalDate.setDate(date.getDate() + 10)

console.log(finalDate)
Desired output:
11/01/2019 00:00:00

Actual output:
31/08/2019 13:06:30

It's using the current system date as a base and setting it to finalDate. which is not what I'm looking for.

Bruno Souza
  • 198
  • 1
  • 12

2 Answers2

1

The way you were declaring your literal date was in error. Also, you're better passing the existing date as a parameter to the constructor for the second one.

let date = new Date("2019-01-01 00:00:00");
let finalDate = new Date(date);

finalDate.setDate(date.getDate() + 10);

console.log(finalDate)
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
  • That is just a oversimplified example so people can understand whats happening, it's not supposed to work as is. But the problem was that i was not passing ```date``` to ```finalDate``` so it was just adding 11 to the system date instead. – Bruno Souza Aug 21 '19 at 18:01
0

If your desired output is 11/01/2019 then you need to change a few things in how you're calculating your dates.

Here's code that get you what you're looking for:

let date = new Date('2019/01/01 00:00:00');
let finalDate = date;

finalDate.setMonth(date.getMonth() + 10);

console.log(finalDate);

Notice that for finalDate, I'm not setting it to a new instance of a date, but rather assigning it the value of the date variable. This way the two are the exact same date and allows us to begin adding months to the one we wish to add months to. Otherwise the days may not come out the same by initializing finalDate as its own separate date object.

Also notice that I'm calling getMonth rather than getDate, since we're adding months strictly.

Here is a working jsfiddle of your desired results: https://jsfiddle.net/yzmk61xf/#&togetherjs=sSETlrppq6

kenef
  • 183
  • 10
  • you're thinking a different format, my date is day/month/year – Bruno Souza Aug 21 '19 at 17:42
  • My mistake for getting your format backwards. However the result is the same. I updated my answer to contain the same date format as yours. I also updated the jsfiddle. Cheers. – kenef Aug 21 '19 at 18:13