0

I have a date object 1/10/2021 and when I set date minus 1. It will return 31/10/2021.

What I expect here is 30/9/2021.

Here is my simulate of code:

const _date = new Date(2021, 10, 1);
_date.setDate(_date.getDate() - 1);
console.log(_date) // Sun Oct 31 2021 00:00:00 GMT+0800 (Singapore Standard Time)

Anyone can explain what wrong with my code? and how to fix this case? I really need your help in this issue.

Hoang Subin
  • 6,610
  • 6
  • 37
  • 56
  • 6
    Months in JavaScript start with zero. _date at first is November 1, then you substract one day and you get October 31. – Iván Pérez Sep 03 '20 at 08:24

2 Answers2

3

Months are 0-indexed. Your first statement initiates the date to be November 1st.

const _date = new Date(2021, 10, 1);
console.log(_date) // Nov 1, 2021

More documentation on the Date object here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

steenbergh
  • 1,642
  • 3
  • 22
  • 40
  • 1
    And the lesson here is to dump the original object to ensure it is how you expect. – rybo111 Sep 03 '20 at 08:29
  • When I run this snippet it logs "2021-10-31T23:00:00.000Z" not November 1st, why is that? Also when I tried to fix this by setting 10 to 9 it returned September 29 instead of 30 and _date.getDate() returns just the day (e.g. 30) so ofc if you subtract 1 from it it evaluates to 29. So there are more problems with this code than just the wrong use of Date object imho – Chaz Sep 03 '20 at 08:35
2

Months are 0-indexed, so you need to change this to 9 for October. Or use something more intuitive like this:

var _date = new Date('October 1 2021');

Also consider using toString() methods.

var _date = new Date(2021, 9, 1);
_date.setDate(_date.getDate() - 1);
console.log(_date.toLocaleString());
Chaz
  • 672
  • 1
  • 5
  • 19