简体   繁体   中英

JavaScript (in browser and Node.JS) if the system time is 29th of any month, date.setMonth(1) will have date.getMonth() = 2

JavaScript (in browser and Node.JS) if the system time is 29th of any month, date.setMonth(1) will have date.getMonth() = 2

Sample code:

for(var i = 2018; i <= 2020; i++) {
for(var j = 0; j < 3; j++) {
    var date = new Date();
    date.setFullYear(i);
    date.setMonth(j);
    date.setDate(1);
    console.log(i + "-" + j + "=" + date)
}

}

If your current PC time is 29th of any month, run this code in browser and Node.JS you get:

2018-0=Mon Jan 01 2018 18:19:32 GMT+0800 (Malay Peninsula Standard Time)
2018-1=Thu Mar 01 2018 18:19:32 GMT+0800 (Malay Peninsula Standard Time)
2018-2=Thu Mar 01 2018 18:19:32 GMT+0800 (Malay Peninsula Standard Time)
2019-0=Tue Jan 01 2019 18:19:32 GMT+0800 (Malay Peninsula Standard Time)
2019-1=Fri Mar 01 2019 18:19:32 GMT+0800 (Malay Peninsula Standard Time)
2019-2=Fri Mar 01 2019 18:19:32 GMT+0800 (Malay Peninsula Standard Time)
2020-0=Wed Jan 01 2020 18:19:32 GMT+0800 (Malay Peninsula Standard Time)
2020-1=Sat Feb 01 2020 18:19:32 GMT+0800 (Malay Peninsula Standard Time)
2020-2=Sun Mar 01 2020 18:19:32 GMT+0800 (Malay Peninsula Standard Time)

If your current PC time is not 29th of any month, run this code in browser and Node.JS you get:

2018-0=Mon Jan 01 2018 18:20:17 GMT+0800 (Malay Peninsula Standard Time)
2018-1=Thu Feb 01 2018 18:20:17 GMT+0800 (Malay Peninsula Standard Time)
2018-2=Thu Mar 01 2018 18:20:17 GMT+0800 (Malay Peninsula Standard Time)
2019-0=Tue Jan 01 2019 18:20:17 GMT+0800 (Malay Peninsula Standard Time)
2019-1=Fri Feb 01 2019 18:20:17 GMT+0800 (Malay Peninsula Standard Time)
2019-2=Fri Mar 01 2019 18:20:17 GMT+0800 (Malay Peninsula Standard Time)
2020-0=Wed Jan 01 2020 18:20:17 GMT+0800 (Malay Peninsula Standard Time)
2020-1=Sat Feb 01 2020 18:20:17 GMT+0800 (Malay Peninsula Standard Time)
2020-2=Sun Mar 01 2020 18:20:17 GMT+0800 (Malay Peninsula Standard Time)

Is someone able to replicate my issue?

for(var i = 2018; i <= 2020; i++) { for(var j = 0; j < 3; j++) { var date = new Date(); date.setFullYear(i); date.setDate(1); date.setMonth(j); console.log(i + "-" + j + "=" + date) } }

Hi, I think I am able to solve it by setDate first before setMonth. As as of now is 29th Sept, when set Month(1), it will gives 29th sept, then 1st Mar. So when we setDate(1) again it stays on 1st Mar. If we setDate(1) first before setMonth(1), the issue solved

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM