setDate() is using current date as basis instead of desired object

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


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

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

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.

40 thoughts on “setDate() is using current date as basis instead of desired object”

  1. 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);

    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:

  2. 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);

Leave a Comment