如果`date`在月末,`date.setMonth`会导致月份设置得太高 [英] `date.setMonth` causes the month to be set too high if `date` is at the end of the month

查看:18
本文介绍了如果`date`在月末,`date.setMonth`会导致月份设置得太高的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Date 对象的 getMonth() 方法似乎有错误.假设日期 d2013-01-31,我尝试在 d 上设置月份,如下所示:

A Date object’s getMonth() method seems to have a bug. Assuming the Date d is 2013-01-31, I attempt to set the month on d like this:

const d = new Date(); // 2013-01-31

d.setMonth(8);
console.log(d.getMonth());

结果是9.为什么?我在 Chrome 和 Firefox 中对此进行了测试.

The result is 9. Why? I tested this both in Chrome and Firefox.

我发现当是一个月的 31 日、30 日或 29 日时,将日期设置为天数较少的月份会导致 getMonth 返回错误值.

I found out that when it’s the 31st, 30th, or 29th of a month, setting the date to a month that has a fewer number of days causes getMonth to return the wrong value.

推荐答案

让我们分解一下:

var d = new Date(); // date is now 2013-01-31
d.setMonth(1);      // date is now 2013-02-31, which is 3 days past 2013-02-28
x = d.getMonth();   // what to do, what to do, 3 days past 2013-02-28 is in March
                    // so, expect x to be March, which is 2

仅当 d 的天值大于传递给 setMonth() 的月份中的最大天数时,才会出现此问题.否则,它会按您的预期工作.

This is only an issue when the day value of d is greater than the maximum number of days in the month passed to setMonth(). Otherwise, it works as you'd expect.

这篇关于如果`date`在月末,`date.setMonth`会导致月份设置得太高的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆