cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Date setMonth function Calculation result error

xiaoyu2022
Making moves

var d2=new Date("Thu Mar 31 2022 00:00:00");//2022-03-31
d2.setMonth(3);//set April 
console.log(d2);//Become May  2022-05-01

Output result:
Sun May 01 2022 00:00:00 GMT+0800 (中国标准时间)

1 ACCEPTED SOLUTION

jscher2000
Leader

I think I know this one: 31 April 2022 is not a valid date, so Firefox rolls forward to a valid date based on the shortfall of days in the selected month compared with the original month.

Another example:

var d2=new Date("Thu Mar 31 2022 00:00:00"); //2022-03-31
d2.setMonth(1); //set February
console.log(d2); //expect 2022-03-03

If you need to toll back to the last date of the "set" month in this situation, there probably are good code examples on StackOverflow or other sites for that.

View solution in original post

2 REPLIES 2

jscher2000
Leader

I think I know this one: 31 April 2022 is not a valid date, so Firefox rolls forward to a valid date based on the shortfall of days in the selected month compared with the original month.

Another example:

var d2=new Date("Thu Mar 31 2022 00:00:00"); //2022-03-31
d2.setMonth(1); //set February
console.log(d2); //expect 2022-03-03

If you need to toll back to the last date of the "set" month in this situation, there probably are good code examples on StackOverflow or other sites for that.

Thank you very much for your advice. I'll try.