Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript setMonth和getMonth返回的值不相同_Javascript_Date - Fatal编程技术网

Javascript setMonth和getMonth返回的值不相同

Javascript setMonth和getMonth返回的值不相同,javascript,date,Javascript,Date,当我写这篇文章时,我遇到了以下问题: const date = new Date(); date.setMonth(5); date.getMonth(); // returns 6 date.setMonth(4); date.getMonth(); // returns 4 为什么?问题并不是每次都会出现,只要你在某个日期尝试,当当前日期是一个月的31日 所以今天是2018年。五月三十一号 如果您设置的月份不是31天长的月份,则该天将溢出,该月份将自动增加1 const date = n

当我写这篇文章时,我遇到了以下问题:

const date = new Date();
date.setMonth(5);
date.getMonth(); // returns 6

date.setMonth(4);
date.getMonth(); // returns 4

为什么?

问题并不是每次都会出现,只要你在某个日期尝试,当当前日期是一个月的31日

所以今天是2018年。五月三十一号

如果您设置的月份不是31天长的月份,则该天将溢出,该月份将自动增加1

const date = new Date();
console.log(date.getMonth(), date.getDate()); // 4 31
date.setMonth(5);
console.log(date.getMonth(), date.getDate()); // 6 1