https://stackoverflow.com/questions/...method-has-bug
Anyone else ever run into this weird JS Date issue? One unit test was failing, but only in the CI/CD environment. Turns out that test was through some code taking an initialized Date() object and trying to set the month to June. Well June 31 doesn't exist so JS bumps the date to July 1.
Code:
// we want a Date object for 6/14/2019
const newDate = new Date();
// newDate = 3/31/2020
newDate.setYear(2019);
// newDate = 3/31/2019 - so far so good
newDate.setMonth(5);
// this should set the month to June because months are zero-based,
// while days are 1-based - because GFY that's why
// however now newDate = 7/1/2019 - not good
// JS bumps the date by 1 day, since 6/31 can't exist
newDate.setDate(14);
// newDate = 7/14/2019 - one month off the actual date we wanted
On my local machine it was still 6/30 so we weren't seeing the test fail - but the AWS CICD build job is on GMT so it was 6/31 - ARGH.
20+ years of JS development - never ran into that one before. If I hadn't figured it out today, and went back to test tomorrow - the situation would be reversed - my local would fail while CICD would work - and I'd be even more confused. Then one more day and everything would work again, which would have driven me nuts.
Not my code but this seems like a suboptimal way to create your own arbitrary date object. Is this even recommended?
For now I implemented the solution in the SO issue where you set month and day at the same time:
Code:
newDate.setMonth(6, 14);
Last edited by suzzer99; 03-31-2020 at 12:21 AM.