当日为 31 且下个月没有时,javascript 日期 setMonth 失败

标签 javascript date

<分区>

设置下一个月或上一个月没有实际日期的操作日期不按预期工作

>var date = new Date('2018/10/31');
undefined
>date
Wed Oct 31 2018 00:00:00 GMT-0600 (hora estándar central)
>date.setMonth(date.getMonth() + 1);
1543644000000
>date
Sat Dec 01 2018 00:00:00 GMT-0600 (hora estándar central)

这是一个错误吗?是否应该报告或将其视为预期行为?

最佳答案

这是记录在案的行为。引用自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setMonth例如:

If a parameter you specify is outside of the expected range, setMonth() attempts to update the date information in the Date object accordingly. For example, if you use 15 for monthValue, the year will be incremented by 1, and 3 will be used for month.

The current day of month will have an impact on the behaviour of this method. Conceptually it will add the number of days given by the current day of the month to the 1st day of the new month specified as the parameter, to return the new date. For example, if the current value is 31st August 2016, calling setMonth with a value of 1 will return 2nd March 2016. This is because in 2016 February had 29 days.

在您的例子中,它执行上面第二段中描述的操作:您已将月份更改为 11 月,但没有更改日期。当然,没有 11 月 31 日,因此 JavaScript 会自动将日期设置为下一个有效日期,即 12 月 1 日。

关于当日为 31 且下个月没有时,javascript 日期 setMonth 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53054731/

相关文章:

Javascript 设置图像的 src 属性不起作用

javascript - javascript 中的简单 Prolog 谓词

javascript - Chrome 无法解析日期,但 IE 可以

javascript - 将 undefined 作为对象处理

javascript - Firebase 只允许登录用户写入

java - 将毫秒天数加/减到毫秒日期

java - 计时器的日期不断重复

mysql - 使用 "where"和 "order by"子句为我的 sql 表创建索引以进行查询

mysql - DATE 在动态之间

java - 计算给定日期的一天