2

Here's the output from the Visual Studio Immediate Window. I start with mondaysDate, create a second date, thisDate, and then add integers to it using mondaysDate as the base.

I don't understand why adding 3 to the date yields November 2 and adding 4 to the date yields December 4th.

Is it illegal to invoke setDate() more than once?

?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)
Tim
  • 8,669
  • 31
  • 105
  • 183

1 Answers1

3

The issue is that first time you add 33 days from Oct 1, then you add 34 days from Nov 1.

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)

The date is set relative to thisDate, starting at 1st of the current month, and adds the day number in mondaysDate + 4 days. Every time you call setDate, you update thisDate.

You can read more about setDate on MDN.

XCS
  • 27,244
  • 26
  • 101
  • 151
  • 1
    Why isn't the first call adding 33 days? – Tim Oct 06 '17 at 19:57
  • 2
    @Patrick Evans: If it is adding 33 days to October 30, why does it say November 2? – Tim Oct 06 '17 at 20:00
  • @Tim, Check the MDN link that Cristy has attached. `The setDate() method sets the day of the Date object relative to the beginning of the currently set month`. – m.spyratos Oct 06 '17 at 20:04