javascriptdate-math

please explain my error in this javascript date math


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)

Solution

  • 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.