How to copy the month value from one Date object to another?
This is a problem with the number of days in each month.
When you do:
b.setMonth(a.getMonth());
You are getting the b date but with february as the month: Thu Feb 29 2019 16:11:03 GMT+0200
And February of 2019 did not have 29 days. So the date is actually March 1st: Thu Mar 01 2019 16:11:03 GMT+0200
That is why you get month 2 in the second set of console logs.
And lastly you are setting b.month not a.month so it's subtracting one month from the a date (from February to January).
The problem is that the setMonth()
method has an optional second parameter which is the day (DOCS). If you don't provide a value for the day it will automatically use the one of the date.
So, your A date is 12 February 2018 while your B date is 29 August 2019.
By doing b.setMonth(a.getMonth());
you are implicitly saying b.setMonth(1,29);
(1 is a.getMonth() while 29 is the day form the b date).
So you are trying to set the date to the 29 February which isn't possible in 2019 and it shift the month by 1 to March (month 2).
If you do b.setMonth(a.getMonth() -1);
you are setting it to the 29 January, which is possible so you get January as a month (month 1).
It's because it's your lucky (or unlucky!) day. It's the particular dates you're working woith.
February only has 28 days this year. When you set the month of "Aug 29 2019" to February, you're trying to create the invalid date "Feb 29 2019". That gets rounded up to "Mar 1 2019".
If you'd tried this experiment yesterday, you wouldn't have seen this problem.