请解释我在 javascript 日期数学中的错误

please explain my error in this javascript date math

这是 Visual Studio 即时 Window 的输出。我从 mondaysDate 开始,创建第二个日期 thisDate,然后使用 mondaysDate 作为基础向它添加整数。

我不明白为什么将日期加 3 得到 11 月 2 日,而将日期加 4 得到 12 月 4 日。

多次调用 setDate() 是否违法?

?mondaysDate
Mon Oct 30 2017 00:00:00 GMT-0400 (Eastern Daylight Time)

?thisDate
Mon Oct 30 2017 00:00:00 GMT-0400 (Eastern Daylight Time)

?thisDate.setDate(mondaysDate.getDate() + 3)
1509595200000
?thisDate
Thu Nov 02 2017 00:00:00 GMT-0400 (Eastern Daylight Time)


?thisDate.setDate(mondaysDate.getDate() + 4)
1512363600000
?thisDate
Mon Dec 04 2017 00:00:00 GMT-0500 (Eastern Standard Time)

?mondaysDate
Mon Oct 30 2017 00:00:00 GMT-0400 (Eastern Daylight Time)

问题是,您第一次从 10 月 1 日添加 33 days,然后从 11 月 1 日添加 34 days

thisDate.setDate(mondaysDate.getDate() + 3)
// You set the date to 30 + 3 (33) days from the first day of the current month (Oct 1)
// Oct 1 + 33 days = Nov 2
// thisDate = Thu Nov 02 2017 00:00:00 GMT-0400 (Eastern Daylight Time)

thisDate.setDate(mondaysDate.getDate() + 4)
// You set the date to 30 + 4 (34) days from the first day of the current month (Nov 1)
// Nov 1 + 34 days = Dec 4
// thisDate = Mon Dec 04 2017 00:00:00 GMT-0500 (Eastern Standard Time)

日期是相对于thisDate设置的,从当月1号开始,在mondaysDate+4天内加上天数。每次调用 setDate,都会更新 thisDate

您可以在 MDN 上阅读有关 setDate 的更多信息。