2

The following code works for most days. However, I'm having trouble with July 31, 2019.

var augDate = new Date('2019-08-19T00:00:00');
var julyDate = new Date('2019-07-31T00:00:00');

augDate.setMonth(augDate.getMonth() -1);  
console.log(augDate.getMonth());  //retuns 6, good
console.log(julyDate.getMonth());  //returns 6
julyDate.setMonth(julyDate.getMonth() - 1);  //try to get it to be 5, but it's still 
console.log(julyDate.getMonth());  //still returns 6.  I'm expecting 5

console.log(augDate);
console.log(julyDate);

For some reason the for July 31, the getMonth() - 1 doesn't change the date.

mikemurf22
  • 1,851
  • 2
  • 21
  • 32
  • This discussion can be helpful https://stackoverflow.com/questions/44285996/javascript-is-giving-invalid-month-when-month-is-set-to-5 – Forhad Aug 01 '19 at 17:42

3 Answers3

2

As per the MDN documentation of Date#setMonth:

The current day of month will have an impact on the behaviour of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st August 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days.


Actually it's updating the month since there is no 31 on 6th month(June) it's skips to next month first date. So you can update the date instead with a zero value so it will set to the previous month last date.

As per MDN documentation of Date#setDate:

For example if 0 is provided for dayValue, the date will be set to the last day of the previous month.


var augDate = new Date('2019-08-19T00:00:00Z');
var julyDate = new Date('2019-07-31T00:00:00Z');

augDate.setMonth(augDate.getMonth() -1);  
console.log(augDate.getMonth());  
console.log(julyDate.getMonth());  
julyDate.setDate(0); 
console.log(julyDate.getMonth());  

console.log(augDate);
console.log(julyDate);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

Another way of looking at this is that your julyDate.setMonth(julyDate.getMonth() - 1) line is essentially the same as new Date(2019, 5, 31). Since June (month index 5) only has 30 days, js figures that June 31st means July 1st. Up to you to decide whether or not you want a different output, but your current code works exactly as it should.

const dt = new Date('2019-07-31T00:00:00');
dt.setMonth(dt.getMonth() - 1);
console.log(dt); // "2019-07-01T05:00:00.000Z"
console.log(new Date(2019, 5, 31)); // "2019-07-01T05:00:00.000Z"
benvc
  • 14,448
  • 4
  • 33
  • 54
0

There is no june 31... Try substracting 1 month from July 30 and it works fine! This is why your last console.log gives:

Mon Jul 01 2019 00:00:00 GMT-0400 (Eastern Daylight Time)

François Huppé
  • 2,006
  • 1
  • 6
  • 15