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

问题描述:

以下是Visual Studio立即窗口的输出。我从mondaysDate开始,创建第二个日期,thisDate,然后使用mondaysDate作为基数向它添加整数。请在此javascript日期数学中解释我的错误

我不明白为什么在日期中添加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) 
+0

当你说'日期+ 3',你的意思是添加3天,3个月,3年? – csmckelvey

+0

我假设它是添加日期:https://*.com/questions/3818193/how-to-add-number-of-days-to-todays-date – Tim

+0

你期望的结果是什么? – Cristy

的问题是,你第一次从10月1日加33 days,那么你从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的信息。

+1

为什么不是第一次加入33天? – Tim

+2

@帕特里克埃文斯:如果它增加33天到10月30日,为什么说11月2日? – Tim

+0

@Tim,检查Cristy附加的MDN链接。 'setDate()方法设置Date对象相对于当前设置月份的开始日期。 –