1

I am trying to get the date before a given date in JavaScript. This is what I've come up with.

function getPreviousDay(year, month, day) {
    const date = new Date(year, month - 1, day); // the month is 0-indexed
    date.setDate(date.getDate() - 1);

    console.log(`${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`);
}

getPreviousDay(2016, 9, 30); // 2016-8-29, Expected output: 2016-9-29
getPreviousDay(2016, 10, 1); // 2016-8-30, Expected output: 2016-9-30

Why doesn't it work as expected? Thank you in advance!

user965851
  • 113
  • 2

2 Answers2

1

You make month - 1, when initializing the date, but should be a month.

Alexey Semenyuk
  • 3,263
  • 2
  • 32
  • 36
0

As you said, months, in js date object, are 0-indexed.

So you do very good to substract one from the month, when creating the date object.

Your problem is, that you don't add back that one month when showing the date object :

   console.log(`${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`);
Loïc
  • 11,804
  • 1
  • 31
  • 49
  • 1
    Thank you! The getMonth() method also returns the month in the specified date as a zero-based value (where zero indicates the first month of the year). – user965851 Sep 17 '21 at 22:04